This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• Java is an object-oriented programminglanguage with a built-in applicationprogramming interface (API) that canhandle graphics and user interfaces andthat can be used to create applications orapplets. Because of its rich set of API's,similar to Macintosh and Windows, and itsplatform independence, Java can also bethought of as a platform in itself. Java alsohas standard libraries for doingmathematics.
• Much of the syntax of Java is the same as Cand C++. One major difference is that Javadoes not have pointers. However, thebiggest difference is that you must writeobject oriented code in Java. Proceduralpieces of code can only be embedded inobjects. In the following we assume that thereader has some familiarity with aprogramming language. In particular, somefamiliarity with the syntax of C/C++ is useful.
• In Java we distinguish between applications,which are programs that perform the samefunctions as those written in otherprogramming languages, and applets, whichare programs that can be embedded in aWeb page and accessed over the Internet.Our initial focus will be on writingapplications. When a program is compiled, abyte code is produced that can be read andexecuted by any platform that can run Java.
• Java provides a “firewall” between a networkapplication and compiler.
• Java Compatible browsers can safelydownloaded, java applet with fear of virtualinfection or malicious intent like (private infoas credit card number, bank accountbalance, password ) by searching the contentof computer local file system.
• The compiler generates an architecture neutralobject file format-the compiled code can run onmany processors (8085,8086,386 etc.) give thepresence of java runtime system.
Portable( different kind of O/S)• The java compiler does this by generating
byte code instructions which have nodependency on computer architecturerather they are designed to be easy tointerpret on any machine and easilytranslated to native machine code
-Java compiles to byte-code (not machine code). Byte code is interpreted.
- JIT Compiler as a part of JVM which compiles byte code to machine code or executable code generated on piece by piece to machine not possible to compile entire java program into executable code all at once bcz. Java performs various runtime classes.
• main() must be declared as public, since itmust be called by code outside of its classwhen the program is started.
• The keyword static allows main() to becalled without having to instantiate aparticular instance of the class. This isnecessary since main() is called by javainterpreter before any objects are made.
• In main(), there is only one parameter ,String args[] declares a parameter namedargs, which is an array of String storecharacter strings. In this case, args receivesany command-line arguments present whenthe program is executed.
Javah- It creates header and stub files that letyou extend your java code with the clanguage.
Syntax: javah filename
Javadoc- It creates HTML formatdocumentation from java source code file. Touse javadoc, you have to embed thestatements /** and */. These statements arecalled documentation comment block.
Unicode provides a unique number for every character,no matter what the platform,no matter what the program,no matter what the language
• Unicode allows Java to handle internationalcharacters for most of the world’s livinglanguages, including Arabic, Armenian,Bengali, Bopomofo, Chinese (via unifiedHan), Cyrillic, English, Georgian,
• Greek, Gujarati, Gurmukhi, Hebrew, Hindi (Devanagari), Japanese (Kanji, Hiragana and Katakana via unified Han), Kannada, Korean (Hangul via unified Han), Lao, Maylayalam, Oriya, Tai, Tamil, Telugu, Tibetan… Unicode will make it much easier for non-English speaking programmers to write programs for English speaking users and vice versa.
• The Unicode Standard is a character codingsystem designed to support the worldwideinterchange, processing, and display of thewritten texts of the diverse languages andtechnical disciplines of the modern world.
• Unicode provides a unique number for everycharacter, no matter what the platform, nomatter what the program, no matter what thelanguage.
• The Unicode Standard has been adopted bysuch industry leaders as Apple, HP, IBM,JustSystem, Microsoft, Oracle, SAP, Sun,Sybase, Unisys and many others. Unicode isrequired by modern standards such as XML,Java, ECMAScript (JavaScript), LDAP, CORBA3.0, WML, etc., and is the official way toimplement ISO/IEC 10646. It is supported inmany operating systems, all modern browsers,and many other products.
• The simplest terms that appear inexpressions are constants and variables.The value of a constant does not changeduring the course of a program. A variableis a placeholder for a value that can beupdated as the program runs.
• A variable in Java is most easily envisionedas a box capable of storing a value.
Each variable has the following attributes:•A name, which enables you todifferentiate one variable from another.•A type, which specifies what type ofvalue the variable can contain.•A value, which represents the currentcontents of the variable.
The value changes whenever you assign anew value to the variable. In Java, youmust declare a variable before you can useit. The declaration establishes the nameand type of the variable and, in mostcases, specifies the initial value as well.
• The most common form of a variabledeclaration is
• type or class, name is an identifier thatindicates the name of the variable, andvalue is an expression specifying the initialvalue.
• Most declarations appear as statements inthe body of a method definition. Variablesdeclared in this way are called localvariables and are accessible only insidethat method. Variables may also bedeclared as part of a class. These arecalled instance variables.
The while statementThe while statement evaluates expression,
which must return a boolean value. If theexpression evaluates to true, the whilestatement executes the statement(s) in thewhile block. The while statement continuestesting the expression and executing itsblock until the expression evaluates to false.
• The difference between do-while and while isthat do-while evaluates its expression at thebottom of the loop instead of the top.Therefore, the statements within the do blockare always executed at least once.
• The for statement provides a compact wayto iterate over a range of values.Programmers often refer to it as the "forloop" because of the way in which itrepeatedly loops until a particular conditionis satisfied. The general form of the forstatement can be expressed as follows:
When using this version of the for statement, keep in mind that:
• 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.
• In Java, break statement is used in two waysas labeled and unlabeled.
• break is commonly used as unlabeled.
• Labeled break statement is used forterminating nested loops.
• Nested loops are loops defined inside otherloops in which the topper most loop is defineunder a label with any String value. In theexample a label String value 'weisz' isdefined above the outer most loop while.
• Java has two keywords break and continuein its branching category.
'break' allows users to give end to a loopwhereas with 'continue' statement flow ofcontrol inside a loop can be continued evenwhen the specified loop condition is false.'continue' statement returns the programcontrol from the point where it is passed.
for(int j = 0; j < str.length; j++){System.out.print(str[j] + " ");if(j < str.length)continue; // from here the program control is returned backSystem.out.println("woooooooooooooooooo");}}}
When it reaches a return statementthrowing an exception, whichever occurred
first.• The return statement is used to return the
value within the body of method. The methoddeclared void does not return any value. Incase you try to get the return value from voidthe code show you a compiler error.
class ReturnValue{public static void main (String[] args){System.out.println("The Biggest Number is: "+GetBiggestNumber(10, 15, 20));}public static int GetBiggestNumber (int num1, int num2, int num3){int biggest = 0;
• The new operator allocate memory for anobject during runtime and return referenceto it. In java we cannot manipulate reference(as in C/C++ by using pointers).
• Java runtime allocate memory to an objectdynamically.
Since a class is a logical construct and anobject has physical construct. Declaring anobject of a class is two step process.
• When the garbage collector is ready torelease the storage used for your object, itwill first call finalize( ), and only on the nextgarbage-collection pass will it reclaim theobject’s memory. So if you choose to usefinalize( ), it gives you the ability to performsome important cleanup at the time ofgarbage collection .
This is a potential programming pitfallbecause some programmers, especially C++programmers, might initially mistakefinalize( ) for the destructor in C++, which isa function that is always called when anobject is destroyed. But it is important todistinguish between C++ and Java here,because in C++ objects always get destroyed(in a bug-free program), whereas in Javaobjects do not always get garbage-collected.Or, put another way:
1. Call by value: In java when we pass asimple type to a method, it is passed byvalue. So, the parameter that receives theargument has no effect outside themethod.
2. Call by reference : If we want to change the value of the original variable in the calling program; which is not possible if the call by value method is used.
• Here argument that are objects are passed by a reference to the called method.
• A constructor creates an Object of the classthat it is in by initializing all the instancevariables and creating a place in memory tohold the Object. It is always used with thekeyword new and then the Class name. Forinstance, new String(); constructs a newString object.
• Sometimes in a few classes you may have toinitialize a few of the variables to values apartfrom their predefined data type specificvalues.
• If java initializes variables it would defaultthem to their variable type specific values.For example you may want to initialize aninteger variable to 10 or 20 based on acertain condition, when your class is created.In such a case you cannot hard code thevalue during variable declaration. such kindof code can be placed inside the constructorso that the initialization would happen whenthe class is instantiated.
Inheritance- Creating a new class by taking help of some existing class is known as Inheritance. The new class is known as: Child class or derived class or subclass, and the existing class is known as : base class or parent class or superclass.
class inheritance{public static void main(String s[])
{A a1=new A();B b1=new B();//The superclass may be used by itselfa1.i=10;a1.j=20;System.out.println(“Contents of Superclass”);a1.showij();System.out.println();// The subclass has access to all public members of its superclass */
Another way of initializing lists is by usinginitializer lists.– The array is automatically created– The array size is computed from the numberof items in the list.
You may recall that the main method takes an arrayof String objects as a parameter. This array ofStrings holds the command line parameters whichwere passed to the java program when it wasstarted
• An array is the collection of same data type.Suppose if we have a declare an array oftype String, then it will store only the Stringvalue not any other data type. When we havea closely related data of the same type andscope, it is better to declare it in an array.
• The class String includes methods forexamining individual characters of thesequence, for comparing strings, forsearching strings, for extracting substrings,and for creating a copy of a string with allcharacters translated to uppercase or tolowercase. Case mapping is based on theUnicode Standard version specified by theCharacter class.
The Java language provides special support forthe string concatenation operator ( + ), andfor conversion of other objects to strings.String concatenation is implemented throughthe StringBuilder(or StringBuffer) class andits append method. String conversions areimplemented through the method toString,defined by Object and inherited by all classesin Java. For additional information on stringconcatenation and conversion, see Gosling,
• A String represents a string in the UTF-16format in which supplementary charactersare represented by surrogate pairs in theCharacter class for more information). Indexvalues refer to char code units, so asupplementary character uses two positionsin a String.
• The String class provides methods fordealing with Unicode code points (i.e.,characters), in addition to those for dealingwith Unicode code units (i.e., char values).
Important note: The == operator cannot beused to test String objects for equality
Variables of type String are references toobjects (ie. memory addresses)Comparing two String objects using ==actually compares their memoryaddresses. Two separate String objectsmay contain the equivalent text, but resideat different memory locations.
String Tokenizer:- This class provides amethod to break a string into token parsing.A string involves breaking the string intodifferent words. These words are calledtoken. The StringTokenizer uses whitespaces as separators. This is known asdelimiters.
countToken() // count the no. of tokens in thestring
import java.util.*;public class Test{ public static void main(String args[]) { int idx = 0; int tokenCount; String words[] = new String [500]; String message="The text of the message to
be broken up for analysis"; StringTokenizer st = new
Wrapper Classes: Primitive data types may beconverted into object type by using thewrapper classes. These wrapper classes areavailable in the java.lang package. So wecan use it without an import statement.
There are eight wrapper classes:• Byte• Boolean• Character• Short
Second use for superSimilar to this, excepts it always refer to thesuperclass of the subclass in which it isused.Syntax super.member•Method can be method or variable•This form is applicable to situations in whichmember names of a subclass hidesmembers by the name in the superclass.
First of all, we should understand what is themeaning of 'abstract' in terms of software.
• It's the same meaning as in English, that is,the entities (objects) which do not exist in thereal world are abstract entities.
• For example, Dog, Cat, Bear, Deer are allanimals that exist but animal is also an entitywhich is just a concept and there is noexistence's we can define an abstract classfor 'Animal'.
• That is the very reason this concept isfollowed. The derived classes that we'veseen above are concrete classes since theyare real world objects and have definiteproperties and operations on them.
Abstract: It allows the implementation of abehavior in different ways. The class andmethods declared using abstract modifier arenot complete. The implementation is done insubclass. It is opposite to final modifier.
• A class for which object is not created, i.e. Anabstract class cannot be directly instantiatedwith the new operator, Such objects would beuseless, because an abstract class is notfully defined. Also we cannot declare abstractconstructors, or abstract static methods. Anysubclass of an abstract class must eitherimplement all of the abstract methods in thesuperclass , or be itself declared abstract.
• A final class cannot be subclassed. This isdone for reasons of security and efficiency.Accordingly, many of the Java standardlibrary classes are final, for examplejava.lang.System and java.lang.String. Allmethods in a final class are implicitly final.
• A final method cannot be overridden bysubclasses. This is used to preventunexpected behavior from a subclass alteringa method that may be crucial to the functionor consistency of the class.
Example:
public class MyClass { public final voidmyFinalMethod() {...}}
• A final variable can only be assigned once.This assignment does not grant the variableimmutable status. If the variable is a field of aclass, it must be assigned in the constructorof its class. (Note: If the variable is areference, this means that the variablecannot be re-bound to reference anotherobject. But the object that it references is stillmutable, if it was originally mutable.)
• Unlike the value of a constant, the value of afinal variable is not necessarily known atcompile time.
public class Sphere { public static final double PI =
3.141592653589793; // this is essentially a constant public final double radius; public final double xpos; public final double ypos; public final double zpos; Sphere(double x, double y, double z, double r)
} [...]} Any attempt to reassign radius, xpos, ypos, zpos will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in an compile error.
The Object class: All the classes are subclassof the object class and inherit its methods.Object, which is the root of the java classhierarchy. The toString() method creates astring representation of the value of an objectof the object class.
• wait() and notify() are methods of the objectclass and used for controlling threads, etc.
• clone(), equals() & hashcode(), getClass(), finalize()these methods also belongs to the object class.
• Interfaces are syntactically similar to classes,but they lack instance variables, and theirmethods are declared without any body.
• Once it is defined, any no. of classes canimplement an interface. Also, one class canimplement any no. of interfaces.
• To implement an interface, class must createthe complete set of methods defined by theinterface. However each class is free todetermine the details of its ownimplementation.
Where, access is either public or not used.When no access specifier is included, thendefault access results, and the interface isonly available to other members of thepackage in which it is declared.
• name is the name of interface, and can beany valid identifiers.
• The method which are declared have nobodies. They end with a semicolon after theparameter list.(// like abstract methods)
• Variables can be declared inside of interfacedeclarations. They are implicitly final andstatic, they cannot be changed by theimplementing class. They must alsoinitialized with a constant value.
• The methods that implement an interface must be declared public.
Interfaces are essential to the Java language.Interfaces have advantages over classes becauseof improved information hiding and code re-use.They provide multiple inheritance. Interfaces alsosolve the nasty virtual class problem in C++. Virtualclasses are a counterintuitive solution to theproblem of a class inheriting from the same classmore than once. This is equivalent in Java to thesituation where a base class and derived classimplement the same interface. Interfaces thatextend other interfaces may also produce duplicatereferences. Java merges the duplicate referencesinto one without any fuss
Static (keyword):- Normally a class membermust be accessed only in conjunction with anobject of its class. However, it is possible tocreate a member that can be used by itself,without reference to a specific instance. Tocreate such a member, precede itsdeclaration with the keyword static.
• When a member is declared static, it can beaccessed before any objects of its class arecreated, and without reference to any object
• We can declare both methods and variablesto be static.
e.g. the most common example of a staticmember is main(). main() is declared asstatic because it must be called before anyobject exist.
• Variables-Instance variable declared as staticare, essentially, global variables. Whenobjects of its class are declared, no copy of astatic variable is made. Instead, all instancesof the class share the same static variable.
• interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class.
Similarities:Neither Abstract classes or Interface can be instantiated.
• Interface is also extended by other interface.One interface can inherit another by use ofthe keyword extends. This is much like a wayfor inheriting class. When you inheriting twointerfaces, you must provide implementationsfor all methods defined within the interfaceinheritance path.
• In Java, this is achieved by using what isknown as “packages”, a concept similar to“class libraries” in other languages.
• Packages are Java’s way of grouping anumber of related classes and/or interfacestogether into a single unit. That means,packages act as “containers” for classes.
The benefits of organising classes intopackages are:§ The classes contained in the packages of
other programs/applications can bereused.§ In packages classes can be unique
compared with classes in other packages.That two classes in two different packagescan have the same name. If there is anaming clash, then classes can beaccessed with their fully qualified name.
• Java supports a keyword called “package”for creating user-defined packages. Thepackage statement must be the firststatement in a Java source file (exceptcomments and white spaces) followed byone or more classes.
• Package name is “myPackage” and classesare considered as part of this package; Thecode is saved in a file called “ClassA.java”and located in a directory called“myPackage”.
• As indicated earlier, classes in packages can be accessed using a fully qualified name or using a short-cut as long as we import a corresponding package.
• Store this in “Student.java” file under the directory“pack1”.
• When the “Student.java” file is compiled, the classfile will be created and stored in the directory“pack1”. Now, the package “pack1” will contain boththe classes “Teacher” and “Student”.
• When packages are developed by differentorganizations, it is possible that multiplepackages will have classes with the samename, leading to name classing.
Java offers the real possibility that most programscan be written in a type-safe language. However,for Java to be broadly useful, it needs to have moreexpressive power than it does at present.
It allows students to learn object-orientedprogramming without exposing them to thecomplexity of C++. It provides the kind of rigorouscompile-time error checking typically associatedwith Pascal. It allows instructors to introducestudents to GUI programming, networking, threads,and other important concepts used in modern-daysoftware.
Java is a popular, mature language that ishighly portable, features a large standardlibrary and automatic memory handling. Onthe downside, it’s an interpreted languagewith no support for unsigned types and theautomatic memory management preventsfine control over memory use and makesporting of algorithms harder. Whether Javais a good choice for your scientificprogramming will depend upon which ofthese pros or cons is of most benefit or cost.
Q4) What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3));
Q5) What is the output (Assuming written inside main) String s1 = new String("amit"); String s2 = s1.replace('m','i'); s1.concat("Poddar"); System.out.println(s1); System.out.println((s1+s2).charAt(5));
Q7) What will be output of the following program{ Float f1 = new Float("4.4e99f"); Float f2 = new Float("-4.4e99f"); Double d1 = new Double("4.4e99"); System.out.println(f1); System.out.println(f2); System.out.println(d1); } a) Runtime error b) Infinity -Infinity 4.4E99
Q8) What is the output of following Double d2 = new Double("-5.5"); Double d3 = new Double("-5.5"); System.out.println(d2==d3); System.out.println(d2.equals(d3));
Q9) Which of the following wrapper classes can not take a "String" in constructor
1)Boolean 2) Integer 3) Long 4) Character 5) Byte 6) Short
Q10) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment."); // Looks like a comment The statement results in a compilation error Looks like a comment No output is displayed
Q11)In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true? § It must have a package statement § It must be named Test.java § It must import java.lang
Short answer type QuestionsQ1)What is Java?Q2)How to define an Abstract class?Q3)How to define an Interface in Java ?Q4)If a class is located in a package, what do you need to
change in the OS environment to be able to use it?Q5)What is NullPointerException and how to handle it?Q6)What is the difference between the Boolean & operator and
the && operator?Q7)What is the purpose of finalization?
Long answer type QuestionsQ1)What's the difference between an interface and an abstract
class. Explain with examples?Q2)How Packages allow grouping of related classes into a
single united.Explain with example?Q3)What are wrapper classes in java. Explain with example?Q4)What's the difference between String and StringBuffer
class.Explain with example?Q5)How interacfes are helpful to implement multiple
inheritance in java. Explain with example.Q6)How one can extend the interface. Explain with example?Q7)Differentiate between Java and C++?Q8)What is static keyword in java.Explain with example?
References[1]. Bergin, J., ``Java as a better C++,'' ACM SIGPLAN Notices 31, 11
(November 1996), pp. 21-27. [2]. Bowen, B. D., ``Educators embrace Java,'' JavaWorld (January 1997),
3. Brilliant, S. S., and T. R. Wiseman, ̀ `The first programming paradigm and language dilemma,'' Proceedings of the 27th SIGCSE Technical Symposium on Computer Science Education, Philadelphia, February, 1996, pp. 338-342.
[3]. Jon Byous, Java technology: The early years. Sun Developer Network, no date [ca. 1998]. Retrieved April 22, 2005.
[4]James Gosling, A brief history of the Green project. Java.net, no date [ca. Q1/1998]. Retrieved April 29, 2007.
[5]James Gosling, Bill Joy, Guy Steele, and Gilad Bracha, The Java language specification, third edition. Addison-Wesley, 2005. ISBN 0-321-24678-0 (see also online edition of the specification).
What is the difference between error and anexception?
• An error is an irrecoverable conditionoccurring at runtime. Such as OutOfMemoryerror, StackOverFlow.
• These JVM errors and you can not repairthem at runtime. While exceptions areconditions that occur because of bad inputetc. e.g. FileNotFoundException will bethrown if the specified file does not exist.
• Runtime exceptions are those exceptionsthat are thrown at runtime because of eitherwrong input data or because of wrongbusiness logic etc. These are not checked bythe compiler at compile time
• An exception is an abnormal condition thatarises in a code sequence at run time.
• An exception is a run time error.• A java exception is an object that describe an
exceptional condition that has occurred in apiece of code.When an exceptional condition arises, andobject representing that exception is createdand thrown in the method that cause theerror, that method may choose to handle theexception itself or pass it on.
• Exception type is the type of exception thathas occurred.
• Uncaught Exception Any exception that is notcaught by the program, will ultimately beprocessed by the default handler.
• Default handler displays a string describingthe exception, prints a stack trace from thepoint at which the exception occurred, andterminates the program, default handlerprovided by the Java run-time system.
try- to handle a run time error, simply enclosethe code that you want to monitor inside a tryblock. Immediately following the try block,include a catch clause that specifies theexception type that you wish to catch.
Multiple catch clause- In some cases, morethan one exception could be raised by asingle piece of code. To handle this type ofsituation, use two or more catch clause, eachcatching a different type of exception. When
an exception is thrown, each catchstatement is inspected in order, and thefirst one whose type matches that of theexception is executed. After one catchstatement executes, the others arebypassed, and execution continues aftertry/catch block.
C:\java\bin>java multia=0divide by zerojava.lang.ArithmeticException: / by zeroAfter try/catch blocksC:\java\bin>javac multi.javaC:\java\bin>java multia=0divide by zeroAfter try/catch blocks
The try statement can be nested. That is , atry statement can be inside the block ofanother try. Each time a try statement isentered, the context of that exception ispushed on the stack. If a inner try statementdoes not have a catch statement’s catchhandlers are inspected for a match.
This continues until one of the catchstatements succeeds, or until all of thenested try statements are exhausted. If nocatch statement matches, then the java run-time system will handle the exception.
• So far, you have only been catchingexceptions that are thrown by Java run-timesystem. However, it is possible for yourprogram to throw an exception explicitly, usingthe throw statement. The general form ofthrow is shown here:
• throw ThrowableInstance;
• Here, ThrowableInstance must be an object oftype Throwable or a subclass of Throwable.
• There are two ways you can obtain a Throwableobject: using a parameter into a catch clause, orcreating one with the new operator.
• The flow of execution stops immediately after thethrow statement; any subsequent statements arenot executed. The nearest enclosing try block isinspected to see if it has a catch statement thatmatches the type of the exception. If it does find amatch, control is transferred to that statement. Ifnot, then the next enclosing try statement isinspected, and so on. If no matching catch is found,then the default exception handler halts theprogram and prints the stack trace.
• If a method is capable of causing anexception that it does not handle, it mustspecify this behavior so that callers of themethod can guard themselves against thatexception. We do this by including a throwsclause in the method’s declaration. A throwsclause exceptions, except those of the typeError or RuntimeException, or any of theirsubclasses. All other exceptions that amethod can throw must be declared in thethrows clause. If they are not, a compile-timeerror will result.
• finally creates a block of code that will beexecuted after a try/catch block hascompleted and before the code followingthe try/catch block. The finally block willexecute whether or not an exception isthrown. If an exception is thrown, the finallyblock will execute even if no catchstatement matches the exception. Any timea method is about to return to the callerfrom inside a try/catch block, via anuncaught exception or an explicit returnstatement, the finally clause is alsoexecuted just before the method returns.
• This can be useful for closing file handlesand freeing up any other resources thatmight have been allocated at the beginningof a method with the intent of disposing ofthem before returning. The finally clause isoptional. However, each try statementrequires at least one catch or a finally clause.
class finallyDemo{static void procA(){try{System.out.println(“inside procA”);throw new RuntimeException(“demo”);}Finally{System.out.println(“ProcA’s finally”);}}
Checked Exception- Java compiler checks that youhave indeed stated what is to be done when theyarise, and it is because of this checking that theyare called checked exception. The checkedexceptions describe problems that can arise in acorrect program, typically difficulties with theenvironment such as user mistake or I/O programs.In any method that contains some statements thatmight throw checked exception you must eitherthrows the exception using a throws constraint inthe declaration of the method.
Checked ExceptionClassNotFoundException Class not foundIlligalAccessException Access to a class is deniedInstantiationException Attempt to create an object of an
abstract class or interfaceInterruptedException One thread has been interrupted
by another threadNoSuchFieldException A requested field does not existNoSuchMethodException A requested method does not exist
• Thread- A thread is similar to a sequentialprogram. A sequential program has abeginning, a sequence of steps to beexecute, and an end. A thread also has abeginning, a sequence and an end.However, a thread is not a program on itsown but runs within a program.
• A thread can be defined as the sequentialflow of control within a program.
Use-Threads are very useful when we havelarge computation that take severalseconds to complete, and user should notperceive the delay. Animation is anotherarea where threads are used.
• Most computer games use graphics and thescore and the audio effects go onsimultaneously.
• A single game has all these elements beingprocessed at the same time. The programhas been divided into three sub-units andeach subunit is handled by a thread.
• Java has built-in support for threads. A majorportion of the java architecture ismultithreaded.
• In java programs, the most common use of a threadis to allow the applet to accept input from user andat the same time , display animation in another partof the screen.
Multithreading is the mechanism in which more than one thread run independent of each other within the process.
• wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class.
• wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state.
• notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
• Multiple threads in a process run at thesame time, perform different tasks andinteract with each other.
• e.g. Microsoft internet explorer, is a webbrowser within browser, we can print a pagein the background , while you are scrolling apage. You can play audio and watchanimated images at the same time.
• This behavior is close to real life whereyou perform several tasks concurrently.
• The microprocessor allocates memory tothe processes that we execute. Eachprocess occupies its own address space(memory). However all the threads in aprocess share the same address space.
• Therefore, resources like memory,devices, data of a program, andenvironment of a program are availableto all the threads of that program
• A thread is also known as “lightweightprocess” or “execution context”
• Once you create a Thread Class. It Instantiate the Thread and invoke the method start. It intern triggers the run method on the Thread. Once the run method is completed, The thread will be in dead state.
Ready-to-run
A thread starts its life cycle with a call to start().
• Thread.yield();Please note that yield() is astatic method. Even if it is called on anythread object, it causes the currentlyexecuting thread to give up the CPU.
Waiting• A call to java.lang.Object's wait() method
causes the current thread object to wait. Thethread remains in "Waiting" state until someanother thread invokes notify() or thenotifyAll() method of this object.
• The current thread must own this object'smonitor for calling the wait().
• Please note that static method sleep() onlyguarantees that the thread will sleep forpredefined time and be running some timeafter the predefined time has been elapsed.
• For example, a call to sleep(60) will causethe currently executing thread to sleep for 60milliseconds. This thread will be in ready-to-run state after that.
• It will be in "Running" state only when thescheduler will pick it for execution.
• Thus we can only say that the thread will runsome time after 60 milliseconds.
• Multiple threads in a process run at thesame time, perform different tasks andinteract with each other.
• e.g. Microsoft internet explorer, is a webbrowser within browser, we can print apage in the background , while you arescrolling a page .You can play audio andwatch animated images at the same time.
• This behavior is close to real life whereyou perform several tasks concurrently.
• To create a thread, is to create a new classthat extends Thread, an then to create aninstance of that class. The extending classmust override the run() method, which is theentry point for the new thread.It must alsocall start() method to begin execution of thenew Thread.
• Inside run(), you will define the code thatconstitutes the new thread.
• run() can call other methods, use otherclasses, and declare variables, just like themain thread can.
• The only difference is that run() establishesthe entry point for another, concurrent threadof execution within your program. This threadwill end when run() returns.
After you create a class that implementsRunnable, you will instantiate an object oftype Thread from within that class.
Thread(Runnable threadob,String threadName)
• In this constructor, threadob is an instance ofa class that implements the Runnableinterface.This defines where execution of thethread will begin, the name of the new threadis specified by threadName.
// This is the entry point for the second threadpublic void run(){try{for(int i=5;i>0;i--)System.out.println("Child THREAD"+i);Thread.sleep(500);}catch(InterruptedException e){System.out.println("child interrupted");}System.out.println("child thread exited");}}
class NewThread implements Runnable{String name;// name of threadThread t;NewThread(String threadname){name=threadname;t=new Thread(this, name);System.out.println("New Thread"+":"+t);t.start(); //start the thread}
• As you can see, once started, all three childthreads share the CPU. Notice the call tosleep()in main().This cause the main threadto sleep for ten seconds and ensures that itwill finish last.
There are two ways to determine whether athread has finished .
• First-You can call isAlive() on the thread.final boolean isAlive()The isAlive() method returns true if the threadupon which it is called is still running, itreturns false otherwise.
• Second-While isAlive() is occasionally useful,the method that you will more commonly useto wait for a thread to finish is called join()
• When two or more threads need access to ashared resource, they need some way toensure that the resource will be used by onlyone thread at a time. The process by whichthis is achieved is called synchronization.
Monitor: The monitor is mechanism, can hold only one thread. Once a thread enters a monitor, all other threads must wait until that threads exits the monitor.
Sometimes one thread may be interested inthe activities of another. Or, one could havea functional dependency on another.§ Reading from a file or over a network?§Waiting for a given thread to return a
result.§ Polling (Busy Waiting) vs. Notification§ BadConsumer Example
• As defined in object, every object has a wait(),notify(), and notifyAll() method.§ These should never be overridden
• They can only be called from inside synchronizedblocks, and they only effect other threads insynchronized blocks which are synchronized onthe same object.Note that you don’t specify what is being awoken in notify(). If there are more than 1 thread waiting on the same condition, you have no control of which awakens.notify() only awakens 1 thread.notifyAll() awakens all threads.
• A collection of things wrapped or boxedtogether.
• A package is a namespace that organizes aset of related classes and interfacesConceptually you can think of packages asbeing similar to different folders on yourcomputer. You might keep HTML pages inone folder, images in another, and scripts orapplications in yet another.
• Because software written in the Javaprogramming language
• can be composed of hundreds or thousandsof individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
• Java includes the import statement to bring certain classes, or entire packages, into visibility.
Stream-A stream is an abstraction that either produce or consume information. A stream is linked to a physical device by the java I/O system.
• An input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise an output stream may refer to console, a disk file, or a network socket.
byte streams contain bytes each 8-bit long.character streams contain (Unicode)characters each 16-bit long.
Before the JDK1.1, you could only use bytestreams. However, if you wanted to read instrings, you were in trouble, cause themethod to do that did not properly convertbytes to characters.
IOException: Signals that an I/O exception ofsome sort has occurred. This class is thegeneral class of exceptions produced byfailed or interrupted I/O operations.
• Each of these abstract classes has severalconcrete subclasses, that handles thedifferences between the various devices,such as disk files, network connection andeven memory buffers.
• The above four abstract classes defineseveral key methods that the other streamclasses implements.Two most importantmethods are:
• A file is a collection of related records placed in a specific area on the disk.
• Java.io package provides a class known as the File class that provide support for creating files.
• A file object is used to obtain or manipulate the information associated with a disk file. It will give the permission , directory path and so on.there are some constructors can be used to create a file Objects.
• The File class is very useful for information about files and the directory structure.
• Constructer takes a String for the nameUseful methods:§ .exists()§ .isDirectory()§ .listFiles() - Lists the files if it’s a directory§ .canRead() / .canWrite() - check permissions§ File.listRoots() - returns an array of the roots of a file
• Introduction• Elements of Client Server Computing• Networking Basics• Understanding Ports and Sockets• Java Sockets§ Implementing a Server§ Implementing a Client
Socket: It is used for transmission controlprotocol/Internet protocol (TCP/IP). The advantageof TCP/IP is the client can be any kind of computer.So all the computers in a network implementingTCP/IP can communicate with each other throughsockets.
• A socket is one end point of a two_waycommunication link between two programs runningon the network.
• The socket classes is used to represent theconnection between a client program and a serverprogram.
IP Address: The internet protocol (IP) providesevery network device with a logical addresscalled an IP address. It is represented as aseries of four 8 bit numbers. So, An IPaddress consists of 32 bit patterns eachrange is in the value from 0 to 255.
• In java InetAddress is a class under netpakage used for finding IP addresses. It hasthe following methods getLocalHost,getByName or getAllByName.
DNS: DNS is also used to identify the anyspecific host in the network.
It will give either name or 32 bit address“203.26.48.100”.
Port: data transmitted over the internet isaccompanied by addressing information thatidentifies the computer and the port for whichit is destined. The computer is identified by a32 bit IP address , which IP uses to deliverdata to the right computer in the networks.
• Ports are identified by a 16 bit number, whichTCP and UDP use the port to deliver the datato the right application.
• The TCP/UDP protocols use ports to mapincoming data to a particular process runningon a computer.
• Port numbers ranges from 0 to 65535,because ports are represented by 16 bitnumbers. The port numbers ranges from 0-1023 are reserved for use by well knownservices. These ports are called well knownports.
• Java is a programming language for theinternet. It provides the package java.net fornetworking programs.
• Internet: It is a networks of network.It is amechanism for information dissemination,and a medium for collaboration andinteraction between individuals and theircomputers without regards for geographiclocations.
• Java supports two types of protocolsbasically: TCP/IP and UDP/IP.
• Internet and WWW have emerged as globalubiquitous media for communication andchanging the way we conduct science,engineering, and commerce.
• They also changing the way we learn, live,enjoy, communicate, interact, engage, etc. Itappears like the modern life activities aregetting completely centered around theInternet.
• To take advantage of opportunities presented bythe Internet, businesses are continuously seekingnew and innovative ways and means for offeringtheir services via the Internet.
• This created a huge demand for software designerswith skills to create new Internet-enabledapplications or migrate existing/legacy applicationson the Internet platform.
• Object-oriented Java technologies—Sockets,threads, RMI, clustering, Web services-- haveemerged as leading solutions for creating portable,efficient, and maintainable large and complexInternet applications.
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival.
• Sockets provide an interface for programmingnetworks at the transport layer.
• Network communication using Sockets is verymuch similar to performing file I/O§ In fact, socket handle is treated like file handle.§ The streams used in file I/O operation are also
applicable to socket-based I/O• Socket-based communication is programming
language independent.§ That means, a socket program written in Java
language can also communicate to a programwritten in Java or non-Java socket program.
• A server (program) runs on a specificcomputer and has a socket that is bound to aspecific port. The server waits and listens tothe socket for a client to make a connectionrequest.
• If everything goes well, the server acceptsthe connection. Upon acceptance, the servergets a new socket bounds to a different port.It needs a new socket (consequently adifferent port number) so that it can continueto listen to the original socket for connectionrequests while serving the connected client.
// SimpleServer.java: a simple server programimport java.net.*;import java.io.*;public class SimpleServer {public static void main(String args[]) throws IOException
{// Register service on port 1234ServerSocket s = new ServerSocket(1234);Socket s1=s.accept(); // Wait and accept a connection// Get a communication stream associated with the socketOutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);// Send a string!dos.writeUTF("Hi there");// Close the connection, but not the server socketdos.close();s1out.close();s1.close();
// SimpleClient.java: a simple client programimport java.net.*;import java.io.*;public class SimpleClient {public static void main(String args[]) throws IOException
{// Open your connection to a server, at port 1234Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234);// Get an input file handle from the socket and read the inputInputStream s1In = s1.getInputStream();DataInputStream dis = new DataInputStream(s1In);
Run Server on mundroo.cs.mu.oz.au§ [raj@mundroo] java SimpleServer &
Run Client on any machine (including mundroo):§ [raj@mundroo] java SimpleClient
Hi there
If you run client when server is not up:§ [raj@mundroo] sockets [1:147] java SimpleClientException in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320)at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133)at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120)at java.net.Socket.<init>(Socket.java:273)at java.net.Socket.<init>(Socket.java:100)at SimpleClient.main(SimpleClient.java:6)
public ServerSocket(int port) throws IOException§ Creates a server socket on a specified port. § A port of 0 creates a socket on any free port. You can
use getLocalPort() to identify the (assigned) port on which this socket is listening.
§ The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.
Throws:§ IOException - if an I/O error occurs when opening the
socket.§ SecurityException - if a security manager exists and its
// SimpleServerLoop.java: a simple server program that runs forever in a single thread
import java.net.*;import java.io.*;public class SimpleServerLoop {public static void main(String args[]) throws IOException {// Register service on port 1234ServerSocket s = new ServerSocket(1234);while(true){
Socket s1=s.accept(); // Wait and accept a connection// Get a communication stream associated with the
Programming client/server applications inJava is fun and challenging. Programmingsocket programming in Java is much easierthan doing it in other languages such as C.
Objective Type QuestionsQ.1Exceptions can be caught or rethrown to a calling method.(a) True(b) FalseQ.2 The subclass exception should precede the base class
exception when used within the catch clause.(a) True(b) FalseQ.3 Can a catch block exist without a try block?(a) Yes(b) No
Short Type QuestionsQ.1 What are the different ways to generate and Exception?Q.2 Is it compulsory to use the finally block? Q.3 How are try, catch and finally block organized?Q.4 What is the difference between throw and throws?Q.5 What is the difference between Exception and Error in
Long QuestionsQ.1What are Checked Exceptions and Unchecked
Exceptions?Explain with Example?Q.2What are User defined Exceptions? Give an Example?Q.3 Write a program to implement thread priority?Q.4 Write a program to implement client-server application?Q.5 Explain java thread life cycle?
Event Handling• Different Mechanism (AWT Introduction)• Delegation Event Model• Event Classes• Event Listener Interfaces• Adapter and Inner Classes• Working with windows• Graphics and Text• Using AWT Controls• Layout Managers and Menus• Handling Image• Animation• Sound and VideoJava AppletBeansSwingsServlets
• All the various types of AWT events, areplaced in a separate package calledjava.awt.event for the sake of convenience.
• The Abstract Window Toolkit (AWT) isJava's original platform-independentwindowing, graphics, and user-interfacewidget toolkit. The AWT is now part of theJava Foundation Classes (JFC) — Thestandard API for providing a graphical userinterface (GUI) for a Java program.
Container:- It is a subclass of Componentclass. It has additional methods that allowother Component objects to be nested withinit. Other Container objects can be storedinside of a Container (since they arethemselves instance of Component). It usesvarious Layout Managers.
• When you run an applet using an appletviewer, the applet viewer provides the titleand border.
• Other components can be added to a panelobject by its add() method. (inherited fromcontainer).
• Once these components have been added,you can position and resize them manuallyusing the setLocation(), setSize(), orsetBounds() methods defined by Component.
• A source must register listeners in order forthe listeners to receive notifications about aspecific type of event. Each type of event hasits own registration method.
• The methods that add or remove listenersare provided by the source that generatesevents.
4. The advantage of this design is that theapplication logic that processes events iscleanly separated from the user interfacelogic that generates those events.
5. A user interface element is able to“delegate” the processing of an event to aseparate piece of code.
6. In this event model, listener must registerwith a source in order to receive an eventnotification. This provide an importantbenefit: notification are sent only to listenersthat want to receive them.
7. This is a more efficient way to handle eventsthan the design used by the old java 1.0approach.
Old java 1.0 approach:- an event waspropagated up the containment hierarchyuntil it was handled by a component. Thisrequired components to receive events thatthey did not process, and it wasted valuabletime.
Note: The delegation model eliminates thisoverhead.
8. Facilitate the creation of robust eventhandling code which is less error-prone(strong compile-time checking)
Events: In the delegation model, an event is anobject that describes a state change in asource.
• Some of the activities that cause events to begenerated are “pressing a button”, “entering acharacter via the keyboard”, “selecting anitem in a list”, and “clicking the mouse”, etc.
• Events may also occur that are not directlycaused by interactions with a user interface.
e.g. an event may be generated when “atimer expires”, “a counter exceeds a value”,“a software or hardware failure occurs”, or“an operation is completed”, etc.
ActionEvent generated by component activationAdjustmentEvent generated by adjustment of adjustable components
such as scroll barsContainerEvent generated when components are added to or removed
from a containerFocusEvent generated when a component receives input
focusItemEvent generated when an item is selected from a list,
choice or check boxKeyEvent generated by keyboard activityMouseEvent generated by mouse activityPaintEvent generated when a component is paintedTextEvent generated when a text component is modifiedWindowEvent generated by window activity like minimizing or
• An event listener may be removed from anEvent Source's list of interested Listeners bycalling a remove...Listener() method, passingin the listener object to be removed.
• For example, in the above code fragment,the code below removes the action listenerobject listenerObject from the buttonm_Button.
• Many buttons can register the same listenersince all buttons generate the same type ofevent. This type of event may be generatedby other types of sources as well.
• In the case of a single source that generatesmultiple types of events you can create asingle listener that implements all interfaces(remember: a class may extend only onesuperclass but implement more than oneinterfaces).
• A Frame is a top-level window with a title anda border.The size of the frame includes any areadesignated for the border. The dimensions ofthe border area may be obtained using thegetInsets method, however, since thesedimensions are platform-dependent, a validinsets value cannot be obtained until theframe is made displayable by either callingpack or show. Since the border area isincluded in the overall size of the frame, the
border effectively obscures a portion of theframe, constraining the area available forrendering and/or displaying subcomponentsto the rectangle which has an upper-leftcorner location of (insets.left, insets.top), andhas a size of width - (insets.left + insets.right)by height - (insets.top + insets.bottom).
Frame() //creates a standard window that does not contain a title.
Frame(String title) //creates a window with the title specified by title.
MethodsSetting the windows dimensionvoid setSize(int w,int h);Hiding and Showing a windowsetVisible(boolean flag)Setting a window titlevoid setTitle(String str)Closing a frame windowsetVisible(false)
java.lang.Object java.awt.Graphics public abstract class Graphics extends Object
The Graphics class is the abstract base class for all graphicscontexts that allow an application to draw onto componentsthat are realized on various devices, as well as onto off-screen images.
(public class ObjectClass Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays,implement the methods of this class.)
drawLinepublic abstract void drawLine(int x1, int y1, int x2,
int y2)§ Draws a line, using the current color, between the points
(x1, y1) and (x2, y2) in this graphics context's coordinatesystem.
§ Parameters:üx1 - the first point's x coordinate.üy1 - the first point's y coordinate.üx2 - the second point's x coordinate.üy2 - the second point's y coordinate.
drawRectpublic void drawRect(int x, int y, int width, int height)§ Draws the outline of the specified rectangle. The left and
right edges of the rectangle are at x and x + width. Thetop and bottom edges are at y and y + height. Therectangle is drawn using the graphics context's currentcolor.
§ Parameters:üx - the x coordinate of the rectangle to be drawn.üy - the y coordinate of the rectangle to be drawn.üwidth - the width of the rectangle to be drawn.üheight - the height of the rectangle to be drawn
fillRectpublic abstract void fillRect(int x, int y, int width, int height)§ Fills the specified rectangle. The left and right edges of
the rectangle are at x and x + width - 1. The top andbottom edges are at y and y + height - 1. The resultingrectangle covers an area width pixels wide by heightpixels tall. The rectangle is filled using the graphicscontext's current color.
§ Parameters:üx - the x coordinate of the rectangle to be filled.üy - the y coordinate of the rectangle to be filled.üwidth - the width of the rectangle to be filled.üheight - the height of the rectangle to be filled.
drawRoundRectpublic abstract void drawRoundRect(int x, int y, int width,
int height, int arcWidth, int arcHeight)§ Draws an outlined round-cornered rectangle using this graphics
context's current color. The left and right edges of the rectangle areat x and x + width, respectively. The top and bottom edges of therectangle are at y and y + height.
§ Parameters:üx - the x coordinate of the rectangle to be drawn.üy - the y coordinate of the rectangle to be drawn.üwidth - the width of the rectangle to be drawn.üheight - the height of the rectangle to be drawn.üarcWidth - the horizontal diameter of the arc at the four corners.üarcHeight - the vertical diameter of the arc at the four corners.
fillRoundRectpublic abstract void fillRoundRect(int x, int y,
int width, int height, int arcWidth, int arcHeight)§ Fills the specified rounded corner rectangle with the
current color. The left and right edges of the rectangle areat x and x + width - 1, respectively. The top and bottomedges of the rectangle are at y and y + height - 1.
§ Parameters:üx - the x coordinate of the rectangle to be filled.üy - the y coordinate of the rectangle to be filled.üwidth - the width of the rectangle to be filled.üheight - the height of the rectangle to be filled.
drawOvalpublic abstract void drawOval(int x, int y, int width,
int height) § Draws the outline of an oval. The result is a circle or
ellipse that fits within the rectangle specified by the x, y, width, and height arguments. The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.
§ Parameters:üx - the x coordinate of the upper left corner of the oval to be
drawn. üy - the y coordinate of the upper left corner of the oval to be
drawn. üwidth - the width of the oval to be drawn. üheight - the height of the oval to be drawn.
drawArcpublic abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle)§ Draws the outline of a circular or elliptical arc covering
the specified rectangle. The resulting arc begins atstartAngle and extends for arcAngle degrees, using thecurrent color. Angles are interpreted such that 0 degreesis at the 3 o'clock position. A positive value indicates acounter-clockwise rotation while a negative valueindicates a clockwise rotation.
§ The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.
§ The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.
§ The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle. As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.
§ Parameters:üx - the x coordinate of the upper-left corner of the arc to be drawn. üy - the y coordinate of the upper-left corner of the arc to be drawn. üwidth - the width of the arc to be drawn. üheight - the height of the arc to be drawn. üstartAngle - the beginning angle. üarcAngle - the angular extent of the arc, relative to the start angle.
fillArcpublic abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)§ Fills a circular or elliptical arc covering the specified
rectangle. The resulting arc begins at startAngle andextends for arcAngle degrees. Angles are interpretedsuch that 0 degrees is at the 3 o'clock position. A positivevalue indicates a counter-clockwise rotation while anegative value indicates a clockwise rotation.
§ The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.
§ The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.
§ The angles are specified relative to the non-squareextents of the bounding rectangle such that 45 degreesalways falls on the line from the center of the ellipse tothe upper right corner of the bounding rectangle. As aresult, if the bounding rectangle is noticeably longer inone axis than the other, the angles to the start and end ofthe arc segment will be skewed farther along the longeraxis of the bounds.
§ Parameters:üx - the x coordinate of the upper-left corner of the arc to be filled.üy - the y coordinate of the upper-left corner of the arc to be filled.üwidth - the width of the arc to be filled.üheight - the height of the arc to be filled.üstartAngle - the beginning angle.üarcAngle - the angular extent of the arc, relative to the start angle.
Text stringsYou already met the instruction used todisplay strings on the screen. In case youdidn't, you won't be surprised to hear that it isdrawString. Just to remind you - a string is apiece of text, anything from a singlecharacter (a term which includes letters,punctuation, symbols such as @ or ^, andeven the space character) to a wholesentence. Strings are specified by placingthem within double quotation marks.
The method drawString is given three parametersbetween brackets. The first item is the string itselfto be displayed on the screen. The other twonumbers specify where the string is to appear. Itrepresents the top-left corner of the string.However, the second number actually specifies they-co-ordinate of a line on which the text sits. Somecharacters, such as 'g' or 'y' will drop down belowthis imaginary line, as shown in the followingexample:
If you don't specify a colour for drawing shapes ortext, then Java uses the default colour of black.Specifying a colour is fairly easy - although youcan only specify one of 13 standard colours(including white).There is a standard method built into graphicsenvironment variables called setColor (note the
American spelling of 'Color'). It expects to begiven a colour name, but the colour namemust be of a standard type specified in yetanother class called Color. What all thismeans is that colours are chosen as follows:
Here are the thirteen standard colours. Makesure you use them exactly as specified -don't alter the case of the letters or insertspaces in the middle of them, and note thespelling of 'Gray'.
Black Gray Orange Yellow BlueGreen Pink Cyan lightGray ReddarkGray Magenta white
Any colour that you choose will then be usedfor drawing all lines, text, shapes and as thefill-in colour for shapes until you chooseanother colour. You can also determine thecolour of the background to the applet. Thisis done using the following instruction:
setBackground(Color.cyan);
Again, like the setColor method, it isimportant to note that the name of themethod is all lower case letters except for the
capital B in the middle. However, please notethat setBackground is not part of the graphicsenvironment, and as such, does not need tobe preceded by g. In fact, if you do put g. atthe beginning, then the Java compilercomplains. I have fallen into this trap manytimes!
program where you will want it redraw thescreen. Perhaps the screen has changed(the paint method can easily cope with ifstatements that get it to draw different thingsin different circumstances). To call the paintmethod in these circumstances, use thefollowing instruction:
repaint(); Note that there are no parameters(no numbers, strings or graphicsenvironments) passed to this method, butyou still must include the two brackets andfollow them with the obligatory semicolon,like this ();
It is vital that you don't include this methodinside the paint method itself. If you did, thepaint method would never terminate, as itwould always be calling itself.
Controls are components that allows a user tointeract with your application in various ways- e.g. acommonly used control is the push button.
The AWT supports the following types of controls:• Lables• Push buttons• Check boxes• Choice lists• Lists• Scroll bars• Text editingThese controls are subclass of Component.
• lets you implement an area that contains different components at different times.
• A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays.
• is a sophisticated, flexible layout manager. Italigns components by placing them within agrid of cells, allowing some components tospan more than one cell.
The java.awt.Image class is actually abstract.However, methods such as getImage(URL)in the Applet class return an instance of aconcrete subclass provided by the particularJVM implementation. The details of thatsubclass are not important since you invokeonly methods listed in the Image class, manyof which are overridden by the subclass.
The only functions we have seen in applets sofar are init(), paint(), and functions called inresponse to input events. All of thesefunctions are supposed to do a small amountof work and return quickly. There has beenno opportunity, so far, for a function to loopand do some continuous work.
This applet creates a thread, a separatestream of execution, to perform abackground task. The body of the thread'scode is in the run() function. In this case, thepurpose of the thread is to increment thevariable i once every 1000 milliseconds, andcause the applet to redraw itself. The result isa simple animation.
The Java Media Framework API (JMF)enables audio, video and other time-basedmedia to be added to applications andapplets built on Java technology. Thisoptional package, which can capture,playback, stream, and transcode multiplemedia formats, extends the Java 2 Platform,Standard Edition (J2SE) for multimediadevelopers by providing a powerful toolkit todevelop scalable, cross-platform technology.
The principal difference between ActiveXcontrols and JavaBeans are that ActiveXcontrols can be developed in anyprogramming language but executed only ona Windows platform, whereas JavaBeanscan be developed only in Java, but can runon any platform.
We learned that JavaBeans are Java classeswhich adhere to an extremely simple codingconvention. All you have to do is toimplement java.io.Serializable interface, usea public empty argument constructor andprovide public getter and setter methods toget and set the values of private variables
Swing is a widget toolkit for Java. It is part ofSun Microsystems' Java Foundation Classes(JFC) — an API for providing a graphicaluser interface (GUI) for Java programs.
Swing was developed to provide a moresophisticated set of GUI components thanthe earlier Abstract Window Toolkit.
The Java Swing provides the multipleplatform independent APIs interfaces forinteracting between the users and GUIscomponents. All Java Swing classes importsform the import javax.swing.*; package. Javaprovides an interactive features for designthe GUIs toolkit or components like: labels,buttons, text boxes, checkboxes, comboboxes, panels and sliders etc. All AWTflexible components can be handled by theJava Swing.
The Java Swing supports the pluggingbetween the look and feel features. The lookand feel that means the dramaticallychanging in the component like JFrame,JWindow, JDialog etc. for viewing it into theseveral types of window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
Above code sets the operation of close operation toExit the application using the System exit method.
Efficient, Convenient, Powerful, Portable, Secure, Inexpensive§ Lightweight threads instead of OS threads created§ Single copy of code brought into memory for all threads
versus per thread§ Data (session state) can be stored across threads within
servlet container§ Java is portable and secure§ Requires little expense once servlet container integrated
The advantages of using servlets is their fastperformance and ease of use combined withmore power over traditional CGI. TraditionalCGI scripts written in Java have a number ofdisadvantages when it comes toperformance. When a HTTP request is madea new process is created for each call of theCGI script. This overhead of process creationcan be very system intensive especiallywhen the script does relatively fast
operations (process creation will take moretime than CGI script execution). Java servletssolve this problem by allowing each requestto be handled by a separate Java threadwithin the Web server process, omittingseparate process forking by the HTTPdaemon. In addition, simultaneous CGIrequest causes the CGI script to be copiedand loaded into memory as many times asthere are requests. However with servletsthere are same amount of threads as requestbut there will only be one copy of the servletclass created in memory.
In this chapter, you learnt about Java eventsand the delegation event model necessaryto support them. More specifically, youlearned about Java events, including theevent listener capable of generating themand how they are handled by the Java AWTlibrary. You saw examples of using theswings that are more useful in eventhandling and a Java Servlet is an efficient,convenient, powerful, portable, secure,inexpensive that’s why it is more useful.
Event-driven programming provides the means todevelop flexible applications where the userdetermines program flow. Implementing eventhandlers in Java is generally straightforward, but it'simportant to know which approach is best for whichsituation. In this article, we looked at three of themost common ways to implement event handling:dispatching events to an object, using ananonymous class to dispatch an event directly tothe method that handles it, and using reflection towrite a generic class that dispatches events to theevent handler method.
Short QuestionsQ1)What is the difference between JDBC and ODBC?Q2)What are the types of JDBC Driver Models and explain
them?-Q3)What is source and listener?-Q4)What is adapter class?-Q5)What is meant by controls and what are different types of
controls in AWT?-Q6)What is the difference between choice and list?-Q7)What is the difference between scrollbar and scrollpane?Q8)What is an event and what are the models available for
Long QuestionsQ1)What are the steps involved for making a connection with a
database or how do you connect to a database?Q2)What is the difference between applications and applets?-Q3)How are the elements of different layouts organizedQ4)What are the advantages of the even delegation model
over the event-inheritance model?Q5)What is a layout manager and what are different types of
• The Internet, sometimes called the"Information Superhighway", is a worldwide,publicly accessible series of interconnectedcomputer networks that transmit data (bypacket switching) using the standard InternetProtocol (IP).
• It is a "network of networks" that consists ofmillions of smaller domestic, academic,business, and government networks, whichtogether carry various information andservices, such as electronic mail, online chat,file transfer, and the interlinked web pages).
• An intranet is a private computer network that usesInternet protocols and network connectivity tosecurely share part of an organization's informationor operations with its employees.
• Sometimes the term refers only to the most visibleservice, the internal website. The same conceptsand technologies of the Internet such as clients andservers running on the Internet protocol suite areused to build an intranet. HTTP and other Internetprotocols are commonly used as well, such as FTP.
• An intranet is an information portal designedspecifically for the internal communications ofsmall, medium or large businesses,enterprises, governments, industries orfinancial institutions of any size or complexity.Intranets can be custom-designed to fit theexact needs of businesses no matter wherethey are situated. Users of intranets consistsmainly of:
1. Members of the executive team.2. Accounting and order billing.3. Managers and directors.4. Sales people and support staff.5. Customer service, help desk, etc..
An extranet is somewhat very similar to anintranet. Extranets are designed specificallyto give external, limited access to certain filesof your computer systems to:
1. Certain large or privileged customers.2. Selected industry partners.3. Suppliers and subcontractors... etc.
• Spamming –Email spamming is when peoplesend out large batches of emails (mail shots)to unknown recipients. This is similar to 'junkmail' you get through the post. Search enginespamming is used by people trying toimprove their rankings by repetitive use ofkeywords and submissions.
• HTML tags can have attributes. Attributesprovide additional information to an HTMLelement. Attributes always come inname/value pairs like this: name="value".
• Attributes are always specified in the start tagof an HTML element.
The <a> tag is used to create an anchor to linkfrom, the href attribute is used to address thedocument to link to, and the words betweenthe open and close of the anchor tag will bedisplayed as a hyperlink.
Create Hyperlink<html><body><p><a href="lastpage.htm">This text</a> is a link to a page on this Web site.</p><p><a href="http://www.microsoft.com/">This text</a> is a link to a page on the World Wide Web.</p></body></html>
Note: The frameset column size value can also be set in pixels (cols="200,500"), and one of the columns can be set to use the remaining space (cols="25%,*").
• The IFRAME element allows you to insert aframe within a block of text. Inserting aninline frame within a section of text is muchlike inserting an object via the OBJECTelement: they both allow you to insert anHTML document in the middle of another,they may both be aligned with surroundingtext, etc.
• The information to be inserted inline isdesignated by the src attribute of thiselement. The contents of the IFRAMEelement, on the other hand, should only bedisplayed by user agents that do not support
Backgrounds• The <body> tag has two attributes where you
can specify backgrounds. The backgroundcan be a color or an image.
Bgcolor• The bgcolor attribute specifies a background-
color for an HTML page. The value of this attribute can be a hexadecimal number, an RGB value, or a color name:<body bgcolor="#000000"> <body bgcolor="rgb(0,0,0)"> <body bgcolor="black">
Textarea -Multi line input in a form<HTML><body><textarea name= address rows=“10” cols=“30”>bvicam , new delhi</textarea></body></html>Where name=namerows= number of visible text lines cols= number of visible width of text, in average character widths
<marquee behavior="alternate">This text willbounce from left to right</marquee>
Bgcolor: Sets the background color of themarquee.
<marquee bgcolor="blue">This marquee'sbackground color will be blue.</marquee>
Direction: Sets the direction of the marqueebox to either left-to-right or right-to-left. Laterbrowsers added support for a movie creditstyle bottom-up and top-down values.
Scrollamount: This is how many pixels the text moves between 'frames', in pixels.
<marquee scrollamount="10">This text will move ten pixels per 'frame'</marquee>
Scrolldelay: This sets the amount of time, in milliseconds, between 'frames'.
<marquee scrolldelay="1000">This would be so slow, you'd get no sense of animation.</marquee> <marquee scrolldelay="1">This would be so fast, you couldn't see it!</marquee>
• DHTML is not a standard defined by theWorld Wide Web Consortium (W3C). DHTMLis a "marketing term" - used by Netscape andMicrosoft to describe the new technologiesthe 4.x generation browsers would support.
• DHTML is a combination of technologiesused to create dynamic Web sites.
• To most people DHTML means acombination of HTML 4.0, Style Sheets andJavaScript.
• DHTML Technologies• With DHTML a Web developer can control
how to display and position HTML elementsin a browser window.
• HTML 4.0• With HTML 4.0 all formatting can be moved
out of the HTML document and into aseparate style sheet. Because HTML 4.0separates the presentation of the documentfrom its structure, we have total control ofpresentation layout without messing up thedocument content.
• Cascading Style Sheets (CSS)• With CSS we have a style and layout model
for HTML documents.• CSS was a breakthrough in Web design
because it allowed developers to control thestyle and layout of multiple Web pages all atonce. As a Web developer you can define astyle for each HTML element and apply it toas many Web pages as you want. To make aglobal change, simply change the style, andall elements in the Web are updatedautomatically.
• PWS is a smaller - but fully functional - version ofIIS
• PWS can be found on your Windows 95/98 CD
ASP Compatibility• ASP is a Microsoft Technology• To run IIS you must have Windows NT 4.0 or later• To run PWS you must have Windows 95 or later• ChiliASP is a technology that runs ASP without
Windows OS• InstantASP is another technology that runs ASP
ASP is used to add server-side scripts toyour web site, to make your web site moredynamic and interactive. You have learnedhow to dynamically edit, change or add anycontent of a web page, respond to datasubmitted from HTML forms, access anydata or databases and return the results to abrowser, customize a web page to make itmore useful for individual users.
<html><body><%response.write("<h2>You can use HTML tags to format the text!</h2>")%><%response.write("<p style='color:#0000ff'>This text is styled with the style attribute!</p>")%></body>
Request.QueryString• The Request.QueryString command is used to
collect values in a form with method="get".
• Information sent from a form with the GET methodis visible to everyone (it will be displayed in thebrowser's address bar) and has limits on theamount of information to send.
• If a user typed “Divya" and "Goel" in the formexample above, the URL sent to the server wouldlook like this:
<% dim a,ba=Request.QueryString("fname")b=Request.QueryString("lname")If a<>"" ThenResponse.Write("Hello " & a & "!<br />")response.write("How are you today?")End If%>
Assume that the ASP file "simpleform.asp"contains the following script:
<body> Welcome <% response.write(request.form("fname")) response.write(" " & request.form("lname")) %> </body>• The browser will display the following in the body of the
<html><body><%fruits=Request.Form("fruits")%><form action="checkboxes.asp" method="post"><p>Which of these fruits do you prefer:</p><input type="checkbox" name="fruits" value="Apples"<%if instr(fruits,"Apple") then Response.Write("checked")%>>Apple<br />
<html><body><p><b>You are browsing this site with:</b><%Response.Write(Request.ServerVariables("http_user_agent"))%></p><p><b>Your IP address is:</b><%Response.Write(Request.ServerVariables("remote_addr"))%></p><p>
<b>The DNS lookup of the IP address is:</b><%Response.Write(Request.ServerVariables("remote_host"))%></p><p><b>The method used to call the page:</b><%Response.Write(Request.ServerVariables("request_method"))%></p>
• Set objConnection = Server.CreateObject(“ADODB.Connection”)
The only parameter that the CreateObject takes (“ADODB.Connection” in the above example) specifies the type of object to be created. The Server.CreateObject doesn’t have a return value.
• executes an ASP page as a part of theparent (calling) ASP page.
• An object oriented library written in PHP thatabstracts database operations for portability.
• It is modelled on Microsoft's ADO, but hasmany improvements that make it unique (eg.pivot tables, generating HTML for pagingrecordsets with next and previous links,cached recordsets, HTML menu generation,etc).
JavaScript usually runs on the client-side (thebrowser's side), as opposed to server-side(on the web server). One benefit of doing thisis performance. On the client side, JavaScriptis loaded into the browser and can run assoon as it is called. Without running on theclient side, the page would need to refresheach time you needed a script to run.
Basic knowledge of HTML and graphicdesign work will go a long way in yourdesigning a website. Database templatesalso facilitate you to make changes to yoursite much more easily, and help you changecertain elements without recreating the entirepage from scratch the dividends of simplicitycan not be ignored and put at stake Whiledesigning a website it is important that thesite is attractive, fast-loading, user friendly,focuses on your content and has a highstickiness factor to it.
A Web page is really just a text document indisguise and HTML tags, CSS, ASP,JavaScript, etc are used. You can cleanlyorganize content using headings andparagraphs. Lists can help break up contentinto more web-friendly chunks .Tables aregrids with headings, rows and cells.Hypelinks and Animation are used to make awebsite more interactive.
Short QuestionsQ1)How Cell Padding is differ from Cell Spacing?Q2)How you define HEAD in HTML?Q3)How you define SPAN in HTML?Q4)What are basic HTML tags how we use them?Q5)Can we write a comment into the HTML?Q6)How to use Line Break and Horizontal Line tags in HTML?Q7)How many types of cookies are available in asp?Q8)What is ServerVariables collection?
Long QuestionsQ1)Explain the POST & GET Method or Explain the
difference between them?Q2)What is the difference between Server-side
validation and Client-side validation?Q3)What is the difference between Querystring
collection and Form collection?Q4)How are sessions maintained?Q5)Explain to implement a connection string?Q6)how can i connect to ms-access database, with