Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.
Department of Information TechnologyOOPS THROUGH JAVALab Manual for the Academic Year 2007-2008II B. TechGuru Nanak Engine...
Prepared by: Approved &Reviewed by:Issued by: w.e.f Date:D. RAMA RAOG. PRABHAKAR RAJUGuru Nanak Engineering CollegeIbrahim...
Head IT3
Guru Nanak Engineering CollegeIbrahimpatnam, R R District – 501 506 (A. P.)Department of Information TechnologyLab Manual ...
S.No Contents Page No1 Lab Objective 42 Introduction About Lab 53 Guidelines to Students 64List of Lab Exercises4.1 Syllab...
Lab Objective1) Introduction to object oriented programming concepts- java as an objectoriented programming language. Intr...
INTRODUCTION ABOUT LABThere are 66 systems ( Compaq Presario ) installed in this Lab.Their configurations are as follows :...
GUIDELINES TO STUDENTS:1 Equipment in the lab for the use of student community. Students need to maintaina proper decorum ...
Lab ProgramsOOPS THROUGH JAVA Lab schedulesSubmissions should include-a) Aim of the programb) Descriptionc) Procedured) Al...
21 Write a java program to create an ordinary file.22 Write a java program to copy contents from one file into another fil...
OBJECT ORIENTED PROGRAMMING:OOP Concepts:The object oriented paradigm is built on the foundation laid by thestructured pro...
Data Abstraction and Encapsulation:the wrapping up of data and functions in to a single unit is known as encapsulation.Dat...
the bird robin  is a part of the class flying bird which is agian a part of the classbird. the concept of inheritance prov...
Java History:Java is a general-purpose; object oriented programming languagedeveloped by Sun Microsystems of USA in 1991. ...
theyre being used for - names like sum, total, average and so on. If you are translating aformula then use variable names ...
For example:int a;declares that you want to create an int variable called a.To assign a value to our integer variable we w...
Character VariablesC only has a concept of numbers and characters. It very often comes as a surprise to someprogrammers wh...
The answer depends upon how a was declared. If it was declared as type int the answerwill be 3; if a is of type float then...
Process of building and running java application programs:The way these tools are applied to build and run application pro...
A String is a series of characters enclosed in double quotes and is treated as a singleunit.Unlike c/c++ string in java is...
}OUTPUT:Length of the String s1 =4s1(java) equals s2(java): falses1(java)equalsignorecases2(java):trues1(java)==s2(java):f...
Multitasking is performing two or more tasks at the same time. Nearly all operatingsystems are capable of multitasking by ...
environment, such as those that process transactions from many computers, need to makea CPU’s idle time productive.LIFE CY...
A suspended thread can be revived by using the resume () method.This approach is useful when we want to suspend a thread f...
ClassCast ExceptionArrayIndexOutBounds Exception.Other exceptions :These include exceptions for multithreading, malformedU...
Public class MultipleCatch {Public static void main(String args[]) {Int a=8, b=0, c, d, marks[]={10,20,30,40,50};TryC= a/b...
Applet enters the running state when the system calls the start()method of Applet class. This occurs automatically after t...
1. Experiment no .1 : Write a Program to find Simple Interest.1. AIM:Write a java program to find the simple interest.2. A...
2. Experiment no .2 : Program To Find The Arithmetic Operations1. AIM:Write a java program to find the given numbers of ar...
3. Experiment no .3 : Program To Find The Single Digit Number1. AIM:Write a java program to find the given single digit nu...
case 6:System.out.println("Six");break;case 7:System.out.println("Seven");break;case 8:System.out.println("Eight");break;c...
4. Experiment no .4 : Program To Find The Factorial Of A Number1. AIM:Write a java program to find the given factorial num...
5. Experiment no. 5: Program to check whether the first number is amultiple of second number.1. AIM:To check whether the f...
6. Experiment no. 6: Program to check the given array is sorting order1. AIM:Write a java program to check given numbers i...
7. Experiment no. 7: Program To generate the ARMSTRONG number1. AIM:Write a java program to generate the Armstrong number....
8. Experiment no. 8: Program To generate the Quadratic equation1. AIM:Write a java program to generate the quadratic equat...
{System.out.println("Roots are Real");r1=(-b+Math.sqrt(d))/(2*a);r2=(-b-Math.sqrt(d))/(2*a);System.out.println("Root1 = "+...
9. Experiment no. 9: Program to Find The Primary Numbers1. AIM:Write a java program to find the given primary numbers.2. A...
10. Experiment no. 10: Program to generate the Fibonacci series1. AIM:Write a java program to generate the Fibonacci serie...
System.out.println("Enter how many numbers you want in febinoci series");BufferedReader stdin=new BufferedReader(new Input...
11. Experiment no. 11: Program to generate the sorting order of array1. AIM:Write a java program to generate the sorting o...
}}4. OUTPUT:Enter 10 integers in to array:9 8 7 6 5 4 3 2 1 0Required order is: 0 1 2 3 4 5 6 7 8 942
12. Experiment no. 12: Program to find the 2 largest numbers of a given array1. AIM:To find the largest number of given nu...
System.out.println("The second largest number in the array is " + a[8]);} //End of main} //End of class Largest4. OUTPUTEn...
13. Experiment no. 13: Program to find product, sum and difference of 2matices1. AIM:Write a java program to find the sum ...
{b[i][j]=Integer.parseInt(stdin.readLine());}}for(i=0;i<3;i++) //Calculating additon and substraction{for(j=0;j<3;j++){s[i...
4. OUTPUTEnter the elements of 1st matrix 1 2 3 4 1 2 3 4 1Enter the elements of 2nd matrix 2 3 4 5 6 1 2 3 4The sum of th...
14. Experiment no. 14: Program To implement abstract keyword1. AIM:Write a java program to implement the abstract keyword ...
double area(){return((dim1*dim2)/2);}}class Abstract{public static void main(String args[]){Rectangle r=new Rectangle(5,5)...
15. Experiment no. 15: Program to implement constructor OverLoading1. AIM:Write a java program to implement the constructo...
{A a=new A(6);A a2=new A(7,8);A a1=new A(9,10,11);a.show();a1.show();a2.show();}}4. OUTPUT:The value of a is 6The value of...
16. Experiment no. 16: Program To Implement Dynamic(super class)method dispatch1. AIM:Write a java program to implement th...
17. Experiment no. 17: Declaring and implementing an interface1. AIM:Write a java program to implement the Interface comma...
wt=id.weight(24.58);System.out.println("Dog weights" +wt + "kgs");}}4. OUTPUT:Dog barksDog has got 4 legsdog moves on four...
18. Experiment no. 18: Program To Implement "Inheritance"1. AIM:Write a java program to implement the Inheritance program....
}}class Inherit{public static void main(String args[]) throws IOException{BufferedReader stdin=new BufferedReader(new Inpu...
19. Experiment no. 19: Program to show the Use of This Keyword andConstructor Overloading1. AIM:Write a java program to sh...
class Methover{public static void main(String args[]) throws IOException{System.out.println("Enter the integer number you ...
20. Experiment no. 20: Program to invoke constructors using "Super" Keyword1. AIM:Write a java program to Invoke construct...
{public static void main(String args[]){A a=new A(10,20); //Creating object for class Aa.show();B b=new B(10,20,30); //Cre...
21. Experiment no. 21: Program to show The Separate Window multiplication1. AIM:Write a java program to show the separate ...
4. OUTPUT:62
22. Experiment no. 22: Program To show The MULTITHREADING1. AIM:Write a java program to show the multithreading using try ...
{int i;UserThread ut=new UserThread();try{for(i=1;i==2;i++){System.out.println("main Thread value is" +i);Thread.sleep(100...
23. Experiment no. 23: Program to implement Packages1. AIM:Write a java program to implement Arithmetic operations the pac...
import java.io.*;import Mypack.*;class Usepack{public static void main(String args[]) throws IOException{BufferedReader st...
24. Experiment no. 24 : Program which imports the package Mathc1. AIM:Write a java program to implement Arithmetic operati...
25. Experiment no. 25 : Program to print JAVA IS SIMPLE in differentstyles and fonts1. AIM:Write a java program to impleme...
4. OUTPUT*/69
26. Experiment no. 26: Program to draw Lines, Rectangles, RoundedRectangles, filled Polygons and Ovals1. AIM:Write a java ...
4. OUTPUT:71
27. Experiment no. 27: Program to implement Action Event thatperforms Arithmetic Operations1. AIM:Write a java program to ...
c.add(t1);c.add(l2);c.add(t2);c.add(b1);c.add(b2);c.add(b3);c.add(l3);b1.addActionListener(this);b2.addActionListener(this...
28. Experiment no. 28: Program to implement Mouse Listener(Mouse Events)1. AIM:Write a java program to implement the APPLE...
}public void mousePressed(MouseEvent me){mx=30;my=60;msg="Mouse Pressed";repaint();}public void mouseReleased(MouseEvent m...
g.drawString(msg,60,40);}}4. OUTPUT76
29. Experiment no. 29: Program to implement KeyListener (Key Events)1. AIM:Write a java program to implement the APPLET PA...
switch(key){case KeyEvent.VK_UP:msg=msg+"<up>";break;case KeyEvent.VK_SHIFT:msg=msg+"<shift>";break;case KeyEvent.VK_F1:ms...
30. Experiment no. 30: Program to implement BorderLayout1. AIM:Write a java program to implement the APPLET PACKAGES, Crea...
4. OUTPUT80
31. Experiment no. 31: Program to implement Radio Listener1. AIM:Write a java program to implement the APPLET PACKAGES, Cr...
}public void actionPerformed(ActionEvent ae){if(ae.getActionCommand()=="CSE"){l1.setText("You selected CSE");}if(ae.getAct...
References:1. The complete reference Java, J2SE 5thedition, Herbert Schild, TMH publishing Companylimited, New Delhi.2. Bi...
Próxima SlideShare
Cargando en…5
×

66781291 java-lab-manual

  • Inicia sesión para ver los comentarios

66781291 java-lab-manual

  1. 1. Department of Information TechnologyOOPS THROUGH JAVALab Manual for the Academic Year 2007-2008II B. TechGuru Nanak EngineeringCollegeIbrahimpatnam, R R District – 501 506 (A. P.)In-charge HODPrincipal
  2. 2. Prepared by: Approved &Reviewed by:Issued by: w.e.f Date:D. RAMA RAOG. PRABHAKAR RAJUGuru Nanak Engineering CollegeIbrahimpatnam, R R District – 501 506 (A. P.)Department of Information TechnologyLab Manual for the Academic Year 2007-08(In accordance with JNTU syllabus)SUBJECT : JAVA LABSUBJECT CODE : CS (05338)SEMESTER : II - IISTREAM : Information TechnologyINSTRUCTOR : D. RAMA RAO: G. PRABHAKAR RAJUPROGRAMMERS : 1) G. SRINIVASULU2) M.B. NEELAKANTESHWARA REDDY2
  3. 3. Head IT3
  4. 4. Guru Nanak Engineering CollegeIbrahimpatnam, R R District – 501 506 (A. P.)Department of Information TechnologyLab Manual for the Academic Year 2007-08(In accordance with JNTU syllabus)Suggestions from Principal:Enhancement if any:Comments:4
  5. 5. S.No Contents Page No1 Lab Objective 42 Introduction About Lab 53 Guidelines to Students 64List of Lab Exercises4.1 Syllabus Programs (JNTU)4.2 Additional and AdvancedPrograms7-85 Description about Oops Concepts 9-176 Solutions for Programs 18-597Solutions for AdditionalPrograms60-808 References 815
  6. 6. Lab Objective1) Introduction to object oriented programming concepts- java as an objectoriented programming language. Introduction to java application and applets-control structures-methods-arrays.2) Object based and object oriented programming creating packages-usingoverloaded constructors-static class variables-data abstraction and informationhiding-relation between super class objects and subclass objects compositionverses inheritance-polymorphism- dynamic method binding abstract superclasses and concrete super classes –inheriting interface-use of inner classes andwrapper classes-String to kenizer and String Suffer classes.3) Role of object oriented programming in designing GUI –Graphs andJava20overview of swing- event handling, adapter classes and layout managers.Advance GUI components- JPopup Menus- JDesktopPane- advance layoutmanagers.4) Exception handling and multithreading in object oriented programming- Whenexception handling should be used-java exception handling – exceptions andinheritance-multithreading in java-thread synchronization-daemon threadsRunnable interface- Files and streams in java.5) Network and Database handling through object oriented programming –usingJOSC –processing queries-overview of servlet –introduction to networking –establishing a simple server and a client – introduction to RMI – implementingthe remote interface.6
  7. 7. INTRODUCTION ABOUT LABThere are 66 systems ( Compaq Presario ) installed in this Lab.Their configurations are as follows :Processor : AMD Athelon ™ 1.67 GHzRAM : 256 MBHard Disk : 40 GBMouse : Optical MouseNetwork Interface card : PresentSoftware1 All systems are configured in DUAL BOOT mode i.e, Students can boot fromWindows XP or Linux as per their lab requirement.This is very useful for students because they are familiar with differentOperating Systems so that they can execute their programs in differentprogramming environments.2 Each student has a separate login for database accessOracle 9i client version is installed in all systems. On the server, account for eachstudent has been created.This is very useful because students can save their work ( scenarios’,pl/sql programs, data related projects ,etc) in their own accounts. Each studentwork is safe and secure from other students.3 Latest Technologies like DOT NET and J2EE are installed in somesystems. Before submitting their final project, they can start doing miniproject from 2ndyear onwards.4 MASM ( Macro Assembler ) is installed in all the systemsStudents can execute their assembly language programs using MASM.MASM is very useful students because when they execute their programsthey can see contents of Processor Registers and how each instruction isbeing executed in the CPU.1 Rational Rose Software is installed in some systemsUsing this software, students can depict UML diagrams of theirprojects.2 Software installed : C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOTNET, Rational Rose.3 Systems are provided for students in the 1:1 ratio.4 Systems are assigned numbers and same system is allotted for students when theydo the lab.7
  8. 8. GUIDELINES TO STUDENTS:1 Equipment in the lab for the use of student community. Students need to maintaina proper decorum in the computer lab. Students must use the equipment with care.Any damage is caused is punishable.2 Students are required to carry their observation / programs book with completedexercises while entering the lab.3 Students are supposed to occupy the machines allotted to them and are notsupposed to talk or make noise in the lab. The allocation is put up on the labnotice board.4 Lab can be used in free time / lunch hours by the students who need to use thesystems should take prior permission from the lab in-charge.5 Lab records need to be submitted on or before date of submission.6 Students are not supposed to use floppy disks8
  9. 9. Lab ProgramsOOPS THROUGH JAVA Lab schedulesSubmissions should include-a) Aim of the programb) Descriptionc) Procedured) Algorithme) Program( printout, which includes Name, rollno, date on the top)f) Expected outputg) Observed output.Week 11 Write a Java program to find simple Interest.2 Defining a class called Student. Observe the members of the class i.e the data andfunctions.3 Program on Method overloading4 Program on Constructor overloadingWeek-25 Program on usage of final keyword6 Using Static key in a variable7 Java Program using Object reference variablesWeek-38 Program on inheritance.10 Write a java program that prompts the user for an integer and then prints out all primenumbers up to that integer.11 Write a java program that checks whether a given string is palindrome or not. Ex:MADAM is a palindrome.12 Write a java program to find the biggest & smallest number from the given array of 10integers.Week -413 Write a java program to sort given array of 10 integers in ascending & descending order.14 Write a java program to delete an element from an array of 10 elements.15 Write a java program to add two given matrices.16 Write a java program that prints transpose of a given matrix.Week-517 Write a java program to multiply two given matrices.18 Write a java program for sorting a given list of names in ascending order.19 Write a java program to display literal values of all the elements in a given matrix.Week-620 Write a java program that reads a line of integers, and then displays each integer, and thesum of all the integers (use string tokenizer class).9
  10. 10. 21 Write a java program to create an ordinary file.22 Write a java program to copy contents from one file into another file.23 Write a java program to display the contents in a given file.Week-724 Write a java program reads one file name from the user then displays information aboutwhether the file exists, whether the file is readable, whether the file is writable, the type offile and the length of the files in bytes.25 Write a java program that reads a file and display file on the screen, line number beforeeach line.26 Write a java program that displays the numbers of characters, lines and words in a text file.Week-827 Write a java program to implement inheritance and overloading methods.28 Write a java program to create a package and importing the package.29 Write a java program that implements stack ADT.30 Write a java program to convert infix expression into postfix form.31 Write a java program to implement exception handling.Week-931 Write an applet that displays a simple message32 Creating a moving banner applet.Week-1033 Write an applet that computes the payment of a loan based on the amount of the loan, theinterest rate and the number of months. It takes one parameter from the browser: Monthlyrate; if true, the interest is per month; Other wise the interest rate is annual.Week-1134 Write a java program that works as a simple calculator. Use a grid layout to arrange buttonsfor the digits and for the + - * % operations. Add a text field to display the result.35 Write a java program to for handling mouse events.Week 1236 Write a java program for creating a thread using Thread class.37 Write a java program for creating a thread by implementing runnable interface.38 Write a java program for creating a multiple threadsWeek-1339 Write a java program that correctly implements producer consumer problem using theconcept of inter thread communication.40 Write a java program that lets users create pie charts. Design your own user interface (withswing & AWT)Week-1441 Write a java program that allows the user to draw-lines, rectangles etc..42 Write a java program that illustrates how run time polymorphism is achieved.Week-1543 Write a java program that implements a simple client/server application. The client sendsdata to a server. The server receives the data, uses it to produce a result, an then sends theresult back to the client. The client displays the result n the console. For Ex. The data sentfrom the client is the radius of a circle, and the result produced by the server is the area ofthe circle.10
  11. 11. OBJECT ORIENTED PROGRAMMING:OOP Concepts:The object oriented paradigm is built on the foundation laid by thestructured programming concepts. The fundamental change in OOP is that a program isdesigned around the data being operated upon rather upon the operations themselves.Data and its functions are encapsulated into a single entity.OOP facilitates creatingreusable code that can eventually save a lot of work. A feature called polymorphismpermits to create multiple definitions for operators and functions. Another feature calledinheritance permits to derive new classes from old ones. OOP introduces many new ideasand involves a different approach to programming than the procedural programming.Benefits of object oriented programming:Data security is enforced.Inheritance saves time.User defined data types can be easily constructed.Inheritance emphasizes inventions of new data types.Large complexity in the software development cn be easily managed.Basic C++ Knowledge:C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language in theearly 1980s. C++ is a powerful and flexible programming language. Thus, with minorexceptions, C++ is a superset of the C Programming language.The principal enhancement being the object –oriented concept of a class.A Class is a user defined type that encapsulates many important mechanisms. Classesenable programmers to break an application up into small, manageable pieces, or objects.Basic concepts of Objectoriented programming:Object:Objects are the basic run time entities in an object-oriented system.thy may represent a person, a place,a bank account,a table of data or any item thatthe program has to handle.class:the entire set of data and code of an object can be made of auserdefined data typewith the help of a clss.in fact,Objects are variables of the type class.once a class has been defined ,we can create any number of objects belonging tothat class.A class is thus a collection of objects of similar type.for example:mango,apple,and orange are members of the class fruit.ex:fruit mango;will create an object mango belonging to the class fruit.11
  12. 12. Data Abstraction and Encapsulation:the wrapping up of data and functions in to a single unit is known as encapsulation.Data encapsulation is the most striking feature of a class.the data is not accessabile to the outside world,and only those functions which arewrapped in the class can access.this insulation of the data from direct access by the program is calld data hiding.Abstraction :abstraction referes to the act of representing esseential feartures without includingthe background details or explanations.since the classes use the concept of data abstraction ,thy are known as abstractiondata type(ADT).Inheritance :interitance is the process by which objects of one class acquire theproperities of objects of another class. Inheritance supports the concept of hierarchicalclassification.for example:12BirdAttributes:FeathersLay eggsFlyingbirdAttributes:---------------------Non flyingbirdAttributes:----------------------RobinAttributes:_________SwallowAttributes:_________PenguinAttributes:_________KiwiAttributes:_________
  13. 13. the bird robin is a part of the class flying bird which is agian a part of the classbird. the concept of inheritance provide the idea of reusability.POLYMORPHISM:Polymorphism is another important oop concept. Polymorphism means the ability totake more than one form. an operation may exhibit different instances. The behaviordepends upon the types of data used in the operation.The process of making an operator to exhibit different behaviors in different instanceis known as operator overloading.Polymorphism plays an important role in allowing objects having different internalstructures to share the same external interface. Polymorphism is extensively used ifimplementing inheritance.The Object-Oriented ApproachThe fundamental idea behind object-oriented languages is to combine into a singleprogram entity both data and the functions that operate on that data. Such an entity iscalled an object.An objects functions, called member functions in C++ (because they belong to aparticular class of objects), typically provide the only way to access its data. If you wantto read a data item in an object, you call a member function in the object. It will read theitem and return the value to you. You cant access the data directly. The data is hidden, soit is safe from accidental alteration. Data and its functions are said to be encapsulated intoa single entity. Encapsulation and data hiding are key terms in the description of object-oriented languages.13ShapeDraw()Circle ObjectDraw()Box ObjectDraw()Triangle ObjectDraw()
  14. 14. Java History:Java is a general-purpose; object oriented programming languagedeveloped by Sun Microsystems of USA in 1991. Originally called “oak” by JamesGosling, one of the inventors if the language. This goal had a strong impact on thedevelopment team to make the language simple, portable, highly reliable and powerfullanguage.Java also adds some new features. While C++ is a superset of C. Java isneither a superset nor a subset of C or C++.Data Types--------------------------------------------------------------------------------ObjectivesHaving read this section you should be able to:declare (name) a local variable as being one of Cs five data typesinitialise local variablesperform simple arithmetic using local variables--------------------------------------------------------------------------------There are five basic data types associated with variables:int - integer: a whole number.float - floating point value: ie a number with a fractional part.double - a double-precision floating point value.char - a single character.void - valueless special purpose type which we will examine closely in later sections.One of the confusing things about the C language is that the range of values and theamount of storage that each of these types takes is not defined. This is because in eachcase the natural choice is made for each type of machine. You can call variables whatyou like, although it helps if you give them sensible names that give you a hint of what14C++C Java
  15. 15. theyre being used for - names like sum, total, average and so on. If you are translating aformula then use variable names that reflect the elements used in the formula. Forexample, 2pr (that should read as "2 pi r" but that depends upon how your browser hasbeen set-up) would give local variables names of pi and r. Remember, C programmerstend to prefer short names!Note: all Cs variables must begin with a letter or a "_" (underscore) character.--------------------------------------------------------------------------------Integer Number VariablesThe first type of variable we need to know about is of class type int - short for integer. Anint variable can store a value in the range -32768 to +32767. You can think of it as alargish positive or negative whole number: no fractional part is allowed. To declare an intyou use the instruction:int variable name;15DATA TYPES IN JAVAPrimitive(intrinsic)Non-Primitive(Derived)NumericNon-NumericInteger Floating-point Character BooleanClassInterfaceArraysIntegerFloating pointByte Short Int LongDoubleFloat
  16. 16. For example:int a;declares that you want to create an int variable called a.To assign a value to our integer variable we would use the following C statement:a=10;The C programming language uses the "=" character for assignment. A statement of theform a=10; should be interpreted as take the numerical value 10 and store it in a memorylocation associated with the integer variable a. The "=" character should not be seen as anequality otherwise writing statements of the form:a=a+10;will get mathematicians blowing fuses! This statement should be interpreted as take thecurrent value stored in a memory location associated with the integer variable a; add thenumerical value 10 to it and then replace this value in the memory location associatedwith a.--------------------------------------------------------------------------------Decimal Number VariablesAs described above, an integer variable has no fractional part. Integer variables tend to beused for counting, whereas real numbers are used in arithmetic. C uses one of twokeywords to declare a variable that is to be associated with a decimal number: float anddouble. They are each offer a different level of precision as outlined below.floatA float, or floating point, number has about seven digits of precision and a range of about1.E-36 to 1.E+36. A float takes four bytes to store.doubleA double, or double precision, number has about 13 digits of precision and a range ofabout 1.E-303 to 1.E+303. A double takes eight bytes to store.For example:float total;double sum;To assign a numerical value to our floating point and double precision variables wewould use the following C statement:total=0.0;sum=12.50;--------------------------------------------------------------------------------16
  17. 17. Character VariablesC only has a concept of numbers and characters. It very often comes as a surprise to someprogrammers who learnt a beginners language such as BASIC that C has nounderstanding of strings but a string is only an array of characters and C does have aconcept of arrays which we shall be meeting later in this course.To declare a variable of type character we use the keyword char. - A single characterstored in one byte.For example:char c;To assign, or store, a character value in a char data type is easy - a character variable isjust a symbol enclosed by single quotes. For example, if c is a char variable you can storethe letter A in it using the following C statement:c=ANotice that you can only store a single character in a char variable. Later we will bediscussing using character strings, which has a very real potential for confusion because astring constant is written between double quotes. But for the moment remember that achar variable is A and not "A".--------------------------------------------------------------------------------Assignment StatementOnce youve declared a variable you can use it, but not until it has been declared -attempts to use a variable that has not been defined will cause a compiler error. Using avariable means storing something in it. You can store a value in a variable using:name = value;For example:a=10;stores the value 10 in the int variable a. What could be simpler? Not much, but it isntactually very useful! Who wants to store a known value like 10 in a variable so you canuse it later? It is 10, always was 10 and always will be 10. What makes variables useful isthat you can use them to store the result of some arithmetic.Consider four very simple mathematical operations: add, subtract, multiply and divide.Let us see how C would use these operations on two float variables a and b.adda+bsubtracta-bmultiplya*bdividea/bNote that we have used the following characters from Cs character set:+ for add- for subtract* for multiply/ for divideBE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?a=10/317
  18. 18. The answer depends upon how a was declared. If it was declared as type int the answerwill be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to thereader to find out the answer for a of type char.Two points to note from the above calculation:C ignores fractions when doing integer division!when doing float calculations integers will be converted into float. We will see later howC handles type conversions.--------------------------------------------------------------------------------Arithmetic OrderingWhilst we are dealing with arithmetic we want to remind you about something thateveryone learns at junior school but then we forget it. Consider the following calculation:a=10.0 + 2.0 * 5.0 - 6.0 / 2.0What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got thatanswer by following each instruction as if it was being typed into a calculator. Acomputer doesnt work like that and it has its own set of rules when performing anarithmetic calculation. All mathematical operations form a hierarchy which is shownhere. In the above calculation the multiplication and division parts will be evaluated firstand then the addition and subtraction parts. This gives an answer of 17.Note: To avoid confusion use brackets. The following are two different calculations:a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0You can freely mix int, float and double variables in expressions. In nearly all cases thelower precision values are converted to the highest precision values used in theexpression. For example, the expression f*i, where f is a float and i is an int, is evaluatedby converting the int to a float and then multiplying. The final result is, of course, a floatbut this may be assigned to another data type and the conversion will be madeautomatically. If you assign to a lower precision type then the value is truncated and notrounded. In other words, in nearly all cases you can ignore the problems of convertingbetween types.18
  19. 19. Process of building and running java application programs:The way these tools are applied to build and run application programs is create aprogram. We need create a source code file using a text editor. The source code is thencompiled using the java compiler javac and executed using the java interpreter java. Thejava debugger jdb is used to find errors. A complied java program can be converted into asource code.ARRAYS, STRINGS AND STRINGBUFFERSArrays are used to stroe large number data of same data types. which are groupedtogether and called by a common name.These are called elements of the array. Arrays canstore both primitive data types and objects.but they must be of same type.These elementsare stored in contiguous memory locations. Arrays are ordered in the sense that eachelement is indexed. starting from 0 and can be retreived based on the indexedvalue.Arrays in java unlike in C are objects, and are of fixed size.STRINGS19Text EditorJava SourceCodeJavadocHTMLfilesJavacJava ClassFileJavahHeaderFilesJava (only file name) Jdb (database)JavaprogramOutput
  20. 20. A String is a series of characters enclosed in double quotes and is treated as a singleunit.Unlike c/c++ string in java is an object from class string.A string in java does notterminate with a null character(o).A string may be assigned in declaration to a stringreference.The declaration String age="old"; initializes a String reference age to refer tothe anonymous string object "old".String ConcatenationString can be concatenated with + operator.String concatenation using string referencespublic class StringConcatenation {public static void main(String args[]){String first_name="Nagesh";String last_name="Rao";String sir_name = "Sure";String concat1=sir_name+first_name+last_name;String concat2= sir_name+"+first_name+""+last_name;System.out.println(concat1);System.out.println(concat1);System.out.println(concat2);}}OUTPUT:SureNegeshRaoSure Negesh RaoThe length(size) of a string can be found with the string method length().Two string canbe compared with equals() method, if both strings are same, the method returns aboolean value of true and if not false. In equals() method the case ( upper or lower) of theletters will be taken into consideration and if case is not a matter, th methodequalsIgnoreCase() may be used. The operator. == is used to compare two objectsreferences to see if they refer the same instance.using equals(), equalsIgnoreCase() and to see the differece between the usage of equalsand() and ==public class StringComparision{public static void main(String args[]) {String s1 = "java"String s2 = "java"String s3 = "java"String s4 = s1;System.out.println("Length of the string s1= "+s1.lenght());System.out.println("s1(java)equals s2(java):"+ s1.equals(s2));System.out.println("s1(java) equalsIgnoreCaseS2(java):+s1.equalsignoreCase(s2));System.out.println("s1(java) == s2(java):" + s1==s2);System.out.println("s2(java) == s3(java):" +s2== s3);System.out.println("s1(java)==s4(java):" + s1==s4);}20
  21. 21. }OUTPUT:Length of the String s1 =4s1(java) equals s2(java): falses1(java)equalsignorecases2(java):trues1(java)==s2(java):falses2(java)==s3(java): falses1(java)== s4(java): falseThe method compareTo() can also be used to compare two string but comparision is donelexographically(that is letter by letter in a dictionary order(). Method compareTo() returns0 if both strings are equal, a negative number if the string that invokes compareTo is lessthan the string that is passed an an argument and a positive number if the string thatinvokes compareTo is greater than the string that is passed as an argument.A part of astring can be copied with the method substring() method.STRINGBUFFERS Class:Once a String object is created, it’s contents can never be changed. That is to say Stringsare immutable and if tried to change a nbew reference is created.This can be overcomeby using the objects of class StringBuffer. With StringBuffer strings can be manipulateddynamically. String objects are constant strings and StringBuffer objects are modifiablestrings.Program on finding the length and capacity of a StringBuffer object.Public class LengthCapacity {Public static void main(String args[]){StringBuffer sb1 = new StringBuffer();StringBuffer sb2 = new StringBuffer(“ObjectOne”);System.out.println(“Length of sb1 = “+sb.lenth());System.out.println(“Length of sb2 = “ sb2.lenght());System.out.println(“Capacity of sb1 = “sb1.capacity());System.out.println(“Capacity of sb2 = “sb2.capacity());}}OUTPUTLength of sb1 = 0Length of sb2 = 9Capacity of sb1 = 16Capacity of sb2 = 25MULTITHREADINGMultithreading allows two parts of the same program to run concurrently. This articlediscusses how to pull off this performance-improving feat in Java. It is excerpted fromchapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne,2004; ISBN: 007225454821
  22. 22. Multitasking is performing two or more tasks at the same time. Nearly all operatingsystems are capable of multitasking by using one of two multitasking techniques:process-based multitasking and thread-based multitasking.Process-based multitasking is running two programs concurrently. Programmers refer toa program as a process. Therefore, you could say that process-based multitasking isprogram-based multitasking.Thread-based multitasking is having a program perform two tasks at the same time. Forexample, a word processing program can check the spelling of words in a documentwhile you write the document. This is thread-based multitasking.A good way to remember the difference between process-based multitasking and thread-based multitasking is to think of process-based as working with multiple programs andthread-based as working with parts of one program.The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU asthe engine of your car. Your engine keeps running regardless of whether the car ismoving. Your objective is to keep your car moving as much as possible so you can getthe most miles from a gallon of gas. An idling engine wastes gas.The same concept applies to the CPU in your computer. You want your CPU cycles to beprocessing instructions and data rather than waiting for something to process. A CPUcycle is somewhat similar to your engine running.It may be hard to believe, but the CPU idles more than it processes in many desktopcomputers. Let’s say that you are using a word processor to write a document. For themost part, the CPU is idle until you enter a character from the keyboard or move themouse. Multitasking is designed to use the fraction of a second between strokes toprocess instructions from either another program or from a different part of the sameprogram.Making efficient use of the CPU may not be too critical for applications running on adesktop computer because most of us rarely need to run concurrent programs or run partsof the same program at the same time. However, programs that run in a networked22Main thread_______________________________________Thread A____________________________________Thread B____________________________________Thread C____________________________________
  23. 23. environment, such as those that process transactions from many computers, need to makea CPU’s idle time productive.LIFE CYCLE OF A THREAD:New born state:We created a thread object, the thread is born and is said to be innewborn state. The thread is not yet scheduled for running.• Schedule it for running using start() method.• Kill it using stop() method.Runnable state:The runnable state means that the thread is ready for execution andis waiting for the availability of the processor. That is, the thread has joined the queueof threads that are waiting for execution. If all threads have equal priority, then theyare given time slots for execution in round robin, first-come, first-serve manner.If we want a thread to relinquish control to another thread of equal priority before itsturn comes, we can do so by using the yield() method.Running state:Running means that the processor has given its time to the threadfor its execution. The thread runs until it relinquishes control on its own or it ispreempted by a higher priority thread. Suspend () method:23NewbornBlockedRunning RunnableDeadKilled ThreadyieldstartstopstopstopNew threadActiveThreadIdle Thread(not Runnable)ResumenotifySuspendsleep wait
  24. 24. A suspended thread can be revived by using the resume () method.This approach is useful when we want to suspend a thread for some time due to certainreason, but do not want to kill it. Sleep() method:We can put a thread to sleep for a specified time period using the methodsleep (time) where time is in milliseconds. This means that the thread is out of the queueduring this time period.the thread re-enters the runnable state as soon as this time periodis elapsed. Notify () method:It has been told to wait until some event occurs. This is done usingthe wait () method. The thread can be scheduled to run again using the notify () method.Blocked state:A thread is said to be blocked when it is prevented from enteringinto the runnable state and subsequently the running state. This happens when the threadis suspended, sleeping , or waiting in order to satisfy certain requirements. A blockedthread is considered “not runnable” but not dead and therefore fully qualified to runagain.Dead state:Every thread has a life cycle. A running thread ends its life when is hascompleted executing its run() method. We can kill it by sending the stop message to it atany state thus causing a premature death to it. A thread can be killed as soon it is born, orwhile it is running, or even when it is in “not runnable” (blocked) condition.EXCEPTION HANDLINGExceptions :Exceptions are part of the inheritance hierarchy and are derived from the Throwableclass.That is an exception is an instance of theThrowable class.Error: This class describes internal errors,such as out of disk space etc.The user can onlybe informed about such errors and so objects of these cannot be thrown.Exceptions Two classes shown above are derived from this classRun Time Exception Exceptions that inherit from this class includea bad cast.out of bound array accessa null pointer acess.These problems arise out of wrong programming logic and must be corrected by theprogrammer himself. Some of these exceptions areArithmetic ExceptionNullPointer Exception24
  25. 25. ClassCast ExceptionArrayIndexOutBounds Exception.Other exceptions :These include exceptions for multithreading, malformedURL,reading past end of file etc.Some of the subclasses:IOExceptionAWTExceptionClassNotFoundExceptionIllegalAcessExceptionThrowing ExceptionsA method tha returns a value can also be made to throw an exception.What is exception handling?An exception signifies an illegal, invalid or unexcected, issue during program execution.Since exceptions are always assumed to be anticipated., you need to provide appropriateexception handlingWhat are the keywords that are frequently used in exception handling?The important keywords of exception handling are try and catch and they are notmethods, but generally termed as try block and catch block and in these blocks we writethe handling code.As usual each block contains statements delimeted by braces ({}).The statements that aresuspected to raise the exceptions ae written in try block and the statements to handle thesituation when the try block statements raises an exception are written in catch block(likecatch(ArithmeticException ae)Example:Public class Arrayindex{Public static void main(String args[]) {Int marks[]={10,20,30,40,50}Try{System.out.println(marks[10]);}Catch(ArrayIndexOutOfBoundsException ai) {System.out.println(“Hello! Exceptions is caught by me” +ai);}Finally {System.out.println(“This executes irrespective of raising of an exception”);}System.out.println(“marks[4]=”+marks[4]);}}Multiple catch BlocksIn some cases a method may have to catch different types of exceptions. Java supportsmultiple catch blocks, that is a single try block can contain any number of catch blocks. Aprecation to be observed is each block must specify a different type of exception.25
  26. 26. Public class MultipleCatch {Public static void main(String args[]) {Int a=8, b=0, c, d, marks[]={10,20,30,40,50};TryC= a/b;System.out.println(“a/b = “+c);d=marks[10];System.out.println(“marks[10]=+d);}Catch(ArrayIndexOutBoundException aie){System.out.println(“Exception caught by me is “+aie);}Catch(ArithmeticException e) {Syetem.out.println(“Excepion caught by me is” +e);}Catch(Exception e) {System.out.pritnln(“From Exception :”+e);}}}APPLETSAn applet is a program written in the Java programming language that can be included inan HTML page, much in the same way an image is included in a page. When you use aJava technology-enabled browser to view a page that contains an applet, the applets codeis transferred to your system and executed by the browsers Java Virtual Machine (JVM).For information and examples on how to include an applet in an HTML page, refer to thisdescription of the <APPLET> tag.Java Plug-in software enables enterprise customers to direct applets or beans written inthe Java programming language on their intranet web pages to run using Suns JavaRuntime Environment (JRE), instead of the browsers default. This enables an enterpriseto deploy applets that take full advantage of the latest capabilites and features of the Javaplatform and be assured that they will run reliably and consistently.APPLET LIFE CYCLE:Initialization state:Applet enters the initialization state when it is first loaded. This isachieved by calling the init() method of Applet class. Create objects needed by the applet. Set up initial values. Load images or fonts. Set up colors.Running state:26
  27. 27. Applet enters the running state when the system calls the start()method of Applet class. This occurs automatically after the applet is initialized. Startingcan also occur if the applet is already in “stopped” (idle) state.Idle or Stopped State:An applet becomes idle when it is stopped from running. Stoppingoccurs automatically when we leave the page containing the currently running applet. Wecan calling the stop () method explicitly.Dead State:An applet is said to be dead when it is removed from memory. Thisoccurs automatically by invoking the destroy() method when we quit the browser.Display State:Applet moves to the display state whenever it has to perform someoutput operation on the screen. This happens immediately after the applet enters into therunning state.27Stop()Start()Paint()DisplayBornDeadRunningIdleBegin(load Applet) initializationStart()stoppedDestroy()DestroyedExit of BrowserApplet state transition diagram
  28. 28. 1. Experiment no .1 : Write a Program to find Simple Interest.1. AIM:Write a java program to find the simple interest.2. Algorithm:1. Start the program.2. Declare the variables and assume values3. InterestTopay=principle*time*rate/100;4. print the values.5. End of class and main method.6. stop the program.3. PROGRAM:import java.io.*;import java.lang.*;class Simpleinterest{public static void main(String args[]){int principle=25000;float rate = 12.5f;double interestToPay,time = 2.75;interestToPay=principle*time*rate/100;System.out.println("Principle amount is Rs."+principle+ "interest=Rs."+interestToPay);System.out.println ("Total amount to pay to clear the loan = Rs."+(principle+interestToPay));}}4. OUTPUT:Principle amount is Rs.25000 interest = Rs.8593.75Total amount to pay to clear the loan = Rs.33593.7528
  29. 29. 2. Experiment no .2 : Program To Find The Arithmetic Operations1. AIM:Write a java program to find the given numbers of arithmetic operations.2. Algorithm:1. Start the program.2. Declare the variables a and b.3. Read a string with inputstreamReader(System.in).4. convert the string into Integer.parseInt(stdin.readLine());5. Given variables addition, subtraction, multiplication, division.6. End of class and main method.7. stop the program.3. PROGRAM:import java.io.*;class arthematic{public static void main(String s[]) throws IOException{int a,b,add,sub,mul,div;DataInputStream stdin=new DataInputStream(System.in);System.out.println("Enter First Number:");a=Integer.parseInt(stdin.readLine());System.out.println("Enter Second Number:");b=Integer.parseInt(stdin.readLine());add=a+b;sub=a-b;mul=a*b;div=a/b;System.out.println("Addition of a and b = "+add);System.out.println("Subtraction of a and b = "+sub);System.out.println("Multiplication of a and b = "+mul);System.out.println("Division of a and b = "+div);}}4. OUTPUT:Enter first number: 5Enter second number: 3Addition of a and b = 8Subtraction of a and b=2Multiplication of a and b=15Division of a and b=1.029
  30. 30. 3. Experiment no .3 : Program To Find The Single Digit Number1. AIM:Write a java program to find the given single digit number using switch case.2. Algorithm:1. Start the program.2. Read a string with inputstreamReader(System.in).3. convert the string into Integer.parseInt(stdin.readLine());4. By using switch case ( multi way decision statement) when a match isfound, that case is executed.5. Default it is a break statement exit the switch statement.6. Stop the program.4. PROGRAM:import java.io.*;class digit{public static void main(String s[]) throws IOException{int n;DataInputStream stdin=new DataInputStream(System.in);System.out.println("Enter Any positive single digit number :");n=Integer.parseInt(stdin.readLine());switch(n){case 0:System.out.println("Zero");break;case 1:System.out.println("One");break;case 2:System.out.println("Two");break;case 3:System.out.println("Three");break;case 4:System.out.println("Four");break;case 5:System.out.println("Five");break;30
  31. 31. case 6:System.out.println("Six");break;case 7:System.out.println("Seven");break;case 8:System.out.println("Eight");break;case 9:System.out.println("Nine");break;default:System.out.println("Invalid Number");break;}}}4. OUTPUT:Enter any positive single digit number: 6SixEnter any positive single digit number: 5Five31
  32. 32. 4. Experiment no .4 : Program To Find The Factorial Of A Number1. AIM:Write a java program to find the given factorial numbers.2. Algorithm:1. Start the program. Import the packages.2. Read a string with inputstreamReader(System.in).3. convert the string into Integer.parseInt(stdin.readLine());4. By using for loop rotating the integer value.5. Repeat enter the value until end of loop.6. End of class and main method.7. stop the program.3. PROGRAM:import java.io.*; //importing io packageimport java.lang.*; //importing lang packageclass Factorial{public static void main(String args[]) throws IOException{int i,n,f=1;System.out.println("Enter the numbert you want to calculate the factorial");BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));n=Integer.parseInt(stdin.readLine());for(i=1;i<=n;i++){f=f*i;}System.out.println("The factorial of " + n + " is " + f);} //End of main} //End of class Factorial4. OUTPUTEnter the number for which you want the factorial 4The factorial of 4 is 24Enter the number for which you want the factorial 3The factorial of 3 is 6Enter the number for which you want the factorial 6The factorial of 6 is 12032
  33. 33. 5. Experiment no. 5: Program to check whether the first number is amultiple of second number.1. AIM:To check whether the first number is a multiple of second number.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with data types.3. Read a string with inputstreamReader(System.in).4. convert the string into Integer.parseInt(stdin.readLine());5. By using if…else loop rotating the string.6. Print the concatenation of arrays.7. Stop the program.3. PROGRAM:import java.io.*; //Importing io packageclass Multiple{public static void main(String args[]) throws IOException{int m,n;BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter the first number" );m=Integer.parseInt(stdin.readLine());System.out.println("Enter the second number ");n=Integer.parseInt(stdin.readLine());if ( m%n==0){System.out.println("The first number is the multiple of second number" );}else{System.out.println("The first number is not the multiple of second number" );}} //End of main} //End of class Multiple4. OUTPUTEnter the first number 10Enter the second number 5The first number is the multiple of second numberEnter the first number 2Enter the second number 3The first number is not the multiple of second number33
  34. 34. 6. Experiment no. 6: Program to check the given array is sorting order1. AIM:Write a java program to check given numbers in a sorting order.2. Algorithm:1. Start the program.2. Create a class and variables with data types.3. Read a string with DatainputstreamReader(System.in).4. convert the string into Integer.parseInt(stdin.readLine());5. By using for loop rotating the array.6. Print the concatenation of arrays.7. Stop the program.3. PROGRAM:import java.io.*;class sorting{public static void main(String s[]) throws IOException{int a[]=new int[10];int i,j;DataInputStream stdin=new DataInputStream(System.in);System.out.println("Enter 10 Elements into Array");for(i=0;i<10;i++)a[i]=Integer.parseInt(stdin.readLine());for(i=0;i<9;i++)for(j=0;j<9-i;j++){if (a[j+1]<a[j]){int temp=a[j+1];a[j+1]=a[j];a[j]=temp;}}System.out.println("Required Order is ");for(i=0;i<10;i++)System.out.println(a[i]);}}4. OUTPUT:Enter 10 elements into Array:10 9 8 7 6 5 4 3 2 1Required order is:1 2 3 4 5 6 7 8 9 1034
  35. 35. 7. Experiment no. 7: Program To generate the ARMSTRONG number1. AIM:Write a java program to generate the Armstrong number.2. Algorithm:1. Start the program.2. Read a string with DatainputstreamReader(System.in).3. convert the string into Integer.parseInt(stdin.readLine());4. sum=sum+r*r*r formula.5. Using if else statement.6. Stop the program.3. PROGRAM:import java.io.*;class armstrong{public static void main(String s[]) throws IOException{int n,r,temp,sum;DataInputStream stdin=new DataInputStream(System.in);System.out.println("Enter any Positive Integer Number :");n=Integer.parseInt(stdin.readLine());temp=n;sum=0;while(temp>0){r=temp % 10;sum=sum+r*r*r;temp=temp/10;}if (n==sum)System.out.println("Given Number is Armstrong Number");elseSystem.out.println("Given Number is not Armstrong Number");}}4. OUTPUT:Enter any positive Integer number: 153Given number is Armstrong number.Enter any positive Integer number: 146Given number is not Armstrong number.35
  36. 36. 8. Experiment no. 8: Program To generate the Quadratic equation1. AIM:Write a java program to generate the quadratic equation.2. Algorithm:1. Start the program. Import the packages.2. Create a class and variables with data types.3. Declaration of the main class.4. Read a string with inputstreamReader(System.in).5. convert the string into Integer.parseInt(stdin.readLine());6. By using if(d==0) “Roots are Equalent” loop rotating the integer value.7. if(d>0) “Roots are Real” otherwise ("Roots are Imaginary");8. Repeats enter the value until end of loop.9. End of class and main method.10. Stop the program.3. PROGRAM:import java.io.*;import java.math.*;class quadratic{public static void main(String s[]) throws IOException{int a,b,c,d;double r1,r2;BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter value of a:");a=Integer.parseInt(stdin.readLine());System.out.println("Enter value of b:");b=Integer.parseInt(stdin.readLine());System.out.println("Enter value of c:");c=Integer.parseInt(stdin.readLine());d=b*b-4*a*c;if(d==0){System.out.println("Roots are Equalent");r1=-b/(2*a);r2=-b/(2*a);System.out.println("Root1 = "+r1);System.out.println("Root2 = "+r2);}else if (d>0)36
  37. 37. {System.out.println("Roots are Real");r1=(-b+Math.sqrt(d))/(2*a);r2=(-b-Math.sqrt(d))/(2*a);System.out.println("Root1 = "+r1);System.out.println("Root2 = "+r2);}elseSystem.out.println("Roots are Imaginary");}4. OUTPUT:Enter value of a:1Enter value of b:2Enter value of c:1Roots are EqualentEnter value of a:2Enter value of b:3Enter value of c:2Roots are Imaginary37
  38. 38. 9. Experiment no. 9: Program to Find The Primary Numbers1. AIM:Write a java program to find the given primary numbers.2. Algorithm:1. Start the program. Import the packages.2. Read a string with inputstreamReader(System.in).3. convert the string into Integer.parseInt(stdin.readLine());4. By using Nested for() loop rotating the integer value.5. Repeat enters the value until end of loop.6. End of class and main method.7. stop the program.3. PROGRAM:import java.io.*;class prime{public static void main(String s[]) throws IOException{int i,j,c,n;BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter Positive value :");n=Integer.parseInt(stdin.readLine());for (i=1;i<=n;i++){for(j=1,c=0;j<=i;j++){if (i%j==0)c=c+1;}if(c==2)System.out.println(i);}}}4. OUTPUT:Enter positive value:101235738
  39. 39. 10. Experiment no. 10: Program to generate the Fibonacci series1. AIM:Write a java program to generate the Fibonacci series, given numberof n values.2. Algorithm:1. Start the program. Import the packages.2. Create a class and variables with data types.3. Declaration of the main class.4. Read a string with inputstreamReader(System.in).5. convert the string into Integer.parseInt(stdin.readLine());6. By using for loop rotating the integer value.7. Repeats enter the value until end of loop.8. End of class and main method.9. Stop the program.3. PROGRAM:import java.io.*; //importing io packageimport java.lang.*; //importing Lang packageclass A{int a,b,c;A( int f1,int f2 ){a=f1;b=f2;} //End of constructor Avoid Feb(){c=a+b;System.out.print("t" + c);a=b;b=c;} //End of method Feb} //End of class Aclass Febinocci{public static void main(String args[]) throws IOException{int n,f3, i;A a=new A(0,1);39
  40. 40. System.out.println("Enter how many numbers you want in febinoci series");BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));n=Integer.parseInt(stdin.readLine());System.out.println("The febinocci series is as follows");System.out.print("t" + 0);System.out.print("t" + 1);for(i=0;i<(n-2);i++){a.Feb();} //End of for loop} //End of main} //End of class Febinocci4. OUTPUTEnter how many numbers you want in febinoci series 3The febinocci series is as follows 0 1 1Enter how many numbers you want in febinoci series 6The febinocci series is as follows 0 1 1 2 3 5Enter how many numbers you want in febinoci series 10The febinocci series is as follows 0 1 1 2 3 5 8 13 21 3440
  41. 41. 11. Experiment no. 11: Program to generate the sorting order of array1. AIM:Write a java program to generate the sorting order of a given number of n values.2. Algorithm:1. Start the program. Import the packages.2. Create a class and variables with data types.3. Declaration of the main class.4. Read a string with inputstreamReader(System.in).5. convert the string into Integer.parseInt(stdin.readLine());6. By using for loop rotating the integer value.7. Swapping the values into a temp=a[i];8. Repeats enter the value until end of loop.9. End of class and main method.10.Stop the program.3. PROGRAM:import java.io.*;class sorting{public static void main(String s[]) throws IOException{int a[]=new int[20];int i,j,temp;BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter 10 integers into array");for(i=0;i<10;i++)a[i]=Integer.parseInt(stdin.readLine());for(i=0;i<10-1;i++){for(j=0;j<10-i-1;j++){if (a[j]>a[j+1]){temp=a[j];a[j]=a[j+1];a[j+1]=temp;}}}System.out.println("Required Order is ");for(i=0;i<10;i++)System.out.println(a[i]);41
  42. 42. }}4. OUTPUT:Enter 10 integers in to array:9 8 7 6 5 4 3 2 1 0Required order is: 0 1 2 3 4 5 6 7 8 942
  43. 43. 12. Experiment no. 12: Program to find the 2 largest numbers of a given array1. AIM:To find the largest number of given numbers, by using arrays.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with data types.3. Read a string with inputstreamReader(System.in).4. convert the string into Integer.parseInt(stdin.readLine());5. By using for loop rotating the single dimensional arrays value.6. Repeats enter the value until end of loop.7. Print the concatenation of string.8. Stop the program.3. PROGRAM:import java.io.*; //Importing io packageimport java.lang.*; //Importing lang packageclass Largest{public static void main(String args[]) throws IOException{int a[]= new int[10];int i,j,k;System.out.println("Enter the numbers of the array");BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));for(i=0;i<10;i++){a[i]=Integer.parseInt(stdin.readLine());}for(i=0;i<10;i++){for(j=(i+1);j<10;j++){if(a[i]>a[j]){k=a[i];a[i]=a[j];a[j]=k;} //End of if} //End of inner for loop} //End of outer for loopSystem.out.println("The first largest number in the array is " + a[9]);43
  44. 44. System.out.println("The second largest number in the array is " + a[8]);} //End of main} //End of class Largest4. OUTPUTEnter the numbers of the array 1 2 6 3 78 7 8 45 32 23The first largest number in the array is 78The second largest number in the array is 45Enter the numbers of the array 12 23 34 45 56 67 68 78 89 100The first largest number in the array is 100The second largest number in the array is 89Enter the numbers of the array 11 12 13 14 15 16 17 18 19 20The first largest number in the array is 20The second largest number in the array is 1944
  45. 45. 13. Experiment no. 13: Program to find product, sum and difference of 2matices1. AIM:Write a java program to find the sum of the matrices, product of thematrices and differences of matrices, by using two dimensional arrays.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with two dimensional arrays.3. Read a string with inputstreamReader(System.in).4. convert the string into Integer.parseInt(stdin.readLine());5. By using for loop rotating the two dimensional arrays value.6. Column is i, rows is j declare in two dimensional matrices.7. Repeats enter the value until end of loop.8. Print the concatenation of arrays.9. Stop the program.3. PROGRAM:import java.io.*; //Importing io packageclass Matrix{public static void main(String args[]) throws IOException{int a[][]=new int[3][3];int b[][]=new int[3][3];int s[][]=new int[3][3];int d[][]=new int[3][3];int p[][]=new int[3][3];int i,j;BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter the elements of 1st matrix");for( i=0;i<3;i++) //Reading the elements of first matrix{for(j=0;j<3;j++){a[i][j]=Integer.parseInt(stdin.readLine());}}System.out.println("Enter the elements of the 2nd matrix");for(i=0;i<3;i++) //Reading the elements of second matrix{for(j=0;j<3;j++)45
  46. 46. {b[i][j]=Integer.parseInt(stdin.readLine());}}for(i=0;i<3;i++) //Calculating additon and substraction{for(j=0;j<3;j++){s[i][j]=a[i][j]+b[i][j];d[i][j]=a[i][j]-b[i][j];}}System.out.println("The sum of the matrices is");for(i=0;i<3;i++) //Calculating product{for(j=0;j<3;j++){System.out.print(" "+s[i][j]);}System.out.println();}System.out.println("The productof the matrices is");for(i=0;i<3;i++){for(j=0;j<3;j++){p[i][j]=0;for(int k=0;k<3;k++){p[i][j]=p[i][j]+a[i][k]*b[k][j];}System.out.print(" "+p[i][j]);}System.out.println();}System.out.println("The difference of the matrices is");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(" "+d[i][j]);}System.out.println();}}}46
  47. 47. 4. OUTPUTEnter the elements of 1st matrix 1 2 3 4 1 2 3 4 1Enter the elements of 2nd matrix 2 3 4 5 6 1 2 3 4The sum of the matrices is3 5 79 7 35 7 5The productof the matrices is18 24 1817 24 2528 36 20The difference of the matrices is-1 -1 -1-1 -5 11 1 -347
  48. 48. 14. Experiment no. 14: Program To implement abstract keyword1. AIM:Write a java program to implement the abstract keyword and methodoverriding.2. Algorithm:1. Start the program.2. Create a classes and variables with data types.3. Assigns the values of rectangle and triangle.4. Create a object of relevant class, to call the procedure.5. Given a formula of area.6. Print the concatenation of string.7. Stop the program.3. PROGRAM:abstract class Figure{double dim1,dim2;Figure(double a,double b){dim1=a;dim2=b;}abstract double area();}class Rectangle extends Figure{Rectangle(double a,double b){super(a,b);}double area(){return(dim1*dim2);}}class Triangle extends Figure{Triangle(double a,double b){super(a,b);}48
  49. 49. double area(){return((dim1*dim2)/2);}}class Abstract{public static void main(String args[]){Rectangle r=new Rectangle(5,5);double ar=r.area();Triangle t=new Triangle(5,5);double at=r.area();System.out.println("area of rectangle " + ar);System.out.println("area of triangle " + at );}}4. OUTPUT:area of rectangle 25area of triangle 12.5*/49
  50. 50. 15. Experiment no. 15: Program to implement constructor OverLoading1. AIM:Write a java program to implement the constructor and overloadingmethod program.2. Algorithm:1. Start the program.2. Create a class and variables with data types.3. Declare the methods in same name with different parameters.4. Create a object to call the procedure.5. Print the concatenation of values.6. Stop the program.3. PROGRAM:class A{int a=2,b=3,c=4;A(int c1){a=c1;}A(int c1,int c2){a=c1;b=c2;}A(int c1,int c2,int c3){a=c1;b=c2;c=c3;;}void show(){System.out.println("The value of a is " + a);System.out.println("The value of b is " + b);System.out.println("The value of c is " + c);}}class Consover{public static void main(String args[])50
  51. 51. {A a=new A(6);A a2=new A(7,8);A a1=new A(9,10,11);a.show();a1.show();a2.show();}}4. OUTPUT:The value of a is 6The value of a is 7The value of b is 8The value of a is 9The value of b is 10The value of c is 1151
  52. 52. 16. Experiment no. 16: Program To Implement Dynamic(super class)method dispatch1. AIM:Write a java program to implement the super class and sub class method.2. Algorithm:1. Start the program.2. Create a classes and variables with data types.3. Create a methods void show ().4. Create an object of relevant class, to call the procedure.5. Print the concatenation of string.6. Stop the program.3. PROGRAM:import java.io.*;import java.lang.*;class A{void show(){System.out.println("You are in superclass");}}class B extends A{void show(){System.out.println("You are in subclass");}}class Dmd{public static void main(String args[]){A a; //Creating reference variableB b=new B(); //creating object for class Bb.show();a=b; //Assigning object b to a;a.show();}}4. OUTPUT:You are in superclassYou are in subclass52
  53. 53. 17. Experiment no. 17: Declaring and implementing an interface1. AIM:Write a java program to implement the Interface command onmultiple class.2. Algorithm:1. Start the program.2. Create a classes and variables with data types.3. Create a command of interface( ).4. Create an object of relevant class, to call the procedure.5. Calculate the formula in a program.6. Print the concatenation of string.7. Stop the program.3. Program:interface Pet{void speak();void legs(int x);String move(String how);double weight(double x);}public class interfaceDemo implements Pet{public void speak(){System.out.println("Dog braks");}public void legs(int x){System.out.println("Dog has got" +x+"legs");}public String move(String how_to_ move){System.out.println("Dog moves on"+how_to_move+"on land);return"";}public double weight(double x){return x;}public static void main(string args[]){double wt;InterfaceDemo id= new InterfaceDemo();id.speak();id.legs(4);id.move("four legs");53
  54. 54. wt=id.weight(24.58);System.out.println("Dog weights" +wt + "kgs");}}4. OUTPUT:Dog barksDog has got 4 legsdog moves on four legs on landDog weights 24.58 kgs54
  55. 55. 18. Experiment no. 18: Program To Implement "Inheritance"1. AIM:Write a java program to implement the Inheritance program.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with data types.3. Declare the methods in different names in Arithmetic operations.4. Arguments give a throws IOExceptions.5. Read a string with inputstreamReader(System.in).6. convert the string into Integer.parseInt(stdin.readLine());7. Create a object to call the procedure.8. Print the concatenation of string.9. Stop the program.3. PROGRAM:import java.io.*;import java.lang.*;class Add{int c;void add(int a,int b){c=a+b;System.out.println("Result of adding is "+ c);}}class Sub extends Add{void sub(int a,int b){c=a-b;System.out.println("Result of subtracting is "+ c);}}class Mul extends Sub{void mul(int a,int b){c=a*b;System.out.println("Result of multiplying is "+ c);55
  56. 56. }}class Inherit{public static void main(String args[]) throws IOException{BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter 2 numbers to perform add,sub and mul");int i=Integer.parseInt(stdin.readLine());int j=Integer.parseInt(stdin.readLine());Mul m=new Mul();m.mul(i,j);m.add(i,j);m.sub(i,j);}}4. OUTPUTEnter 2 numbers to perform add,sub and mul10 20Result of multiplying is 300Result of adding is 30Result of subtracting is -10Enter 2 numbers to perform add,sub and mul5 10Result of multiplying is 50Result of adding is 15Result of subtracting is -5Enter 2 numbers to perform add,sub and mul2 1Result of multiplying is 2Result of adding is 3Result of subtracting is 156
  57. 57. 19. Experiment no. 19: Program to show the Use of This Keyword andConstructor Overloading1. AIM:Write a java program to show the use of This Keyword And ConstructorOverloading.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with data types.3. Declare the methods in same name with different parameters.4. Arguments give a throws IoExceptions.5. Read a string with inputstreamReader(System.in).6. convert the string into Integer.parseInt(stdin.readLine());7. Create a object to call the procedure.8. Print the concatenation of string.9. Stop the program.3. PROGRAM:import java.io.*; //importing io packageimport java.lang.*; //importing Lang packageclass A{int Square( int x ){int s=x*x;return(s);} //End of constructor Square with int as return typefloat Square( float x ){float s=x*x;return(s);} //End of constructor Square with float as return typedouble Square( double x ){double s=x*x;return(s);} //End of constructor Square with double as return type} //End of class A57
  58. 58. class Methover{public static void main(String args[]) throws IOException{System.out.println("Enter the integer number you want to calculate square");BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));int n=Integer.parseInt(stdin.readLine());System.out.println("Enter the floating point number you want to calculatesquare");float m=Float.parseFloat(stdin.readLine());System.out.println("Enter the double data type number uou want to calculatesquare");double p=Double.parseDouble(stdin.readLine());A a=new A();int sq1=a.Square(n);System.out.println("The square of integer number is " + sq1);A a1=new A();float sq2=a1.Square(m);System.out.println("The square of float number is " + sq2);A a2=new A();double sq3=a2.Square(p);System.out.println("The square of double number is " + sq2);}}4. OUTPUT:Enter the integer number you want to calculate square 5Enter the floating point number you want to calculate square 2.5Enter the double data type number uou want to calculate square 3.44The square of integer number is 25The square of float number is 6.25The square of double number is 11.5658
  59. 59. 20. Experiment no. 20: Program to invoke constructors using "Super" Keyword1. AIM:Write a java program to Invoke constructors using "Super" Keyword.2. Algorithm:1. Start the program.2. Create a class and variables with data types.3. Declare the method of void show ();4. Print the concatenation of values.5. Stop the program.3. PROGRAM:class A{int a,b,c;A(int d1,int d2) //Constructor of class A{a=d1;b=d2;}void show(){System.out.println("The value of a is " + a);System.out.println("The value of b is " + b);}} //End of class Aclass B extends A{B(int d1,int d2,int d3) //Constructor of class B{super(d1,d2); //super calls constructor Ac=d3;}void show(){System.out.println("The value of a is " + a);System.out.println("The value of b is " + b);System.out.println("The value of c is " + c);}} //End of class Bclass Super159
  60. 60. {public static void main(String args[]){A a=new A(10,20); //Creating object for class Aa.show();B b=new B(10,20,30); //Creating object for class Bb.show();} //End of main} //End of class super14. OUTPUT:The value of a is 10The value of b is 20The value of a is 10The value of b is 20The value of c is 30*/60
  61. 61. 21. Experiment no. 21: Program to show The Separate Window multiplication1. AIM:Write a java program to show the separate window of multiplicationof three numbers.2. Algorithm:1. Start the program, import the packages.2. Create a class and variables with data types.3. Declare the string() values.4. JOptionPane.showInputDialog command is a window.5. JOptionPane.showMessageDialog dialog box.6. Print the windows of out put.7. Stop the program.3. PROGRAM:import java.io.*;import javax.swing.JOptionPane;public class Product{public static void main( String args[] ){int x; // first numberint y; // second numberint z; // third numberint result; // product of numbersString xVal; // first string input by userString yVal; // second string input by userString zVal; // third string input by userxVal = JOptionPane.showInputDialog( "Enter first integer:" );yVal = JOptionPane.showInputDialog( "Enter second integer:" );zVal = JOptionPane.showInputDialog( "Enter third integer:" );x = Integer.parseInt( xVal );y = Integer.parseInt( yVal );z = Integer.parseInt( zVal );result = x * y * z;JOptionPane.showMessageDialog( null, "The product is " + result );System.exit( 0 );} // end method main} // end class Product61
  62. 62. 4. OUTPUT:62
  63. 63. 22. Experiment no. 22: Program To show The MULTITHREADING1. AIM:Write a java program to show the multithreading using try and catch() methods.2. Algorithm:1. Start the program.2. Create a class and variables User Thread ().3. Using try catch () methods.4. For loop executions.5. Print the try statements and catch () statements.6. Print the concatenation of string.7. Stop the program.3. PROGRAM:class UserThread extends Thread{UserThread(){super("UserThread");System.out.println("it is a UserThread");start();}public void main(){try{for(int i=10;i>0;i--){System.out.println("Uservalue"+i);Thread.sleep(500);}}catch(InterruptedException ie){System.out.println("User thread Exception");}System.out.println("User thread completed");}}public class ThreadDemo{public static void main(String args[])63
  64. 64. {int i;UserThread ut=new UserThread();try{for(i=1;i==2;i++){System.out.println("main Thread value is" +i);Thread.sleep(100);}}catch(InterruptedException ie){System.out.println("main thread interreupted");}System.out.println("main thread completed");}}4. OUTPUT:It is UserThreadMain thread completed64
  65. 65. 23. Experiment no. 23: Program to implement Packages1. AIM:Write a java program to implement Arithmetic operations the packages.2. Algorithm:1. Start the program.2. Import the Mathc packages.3. Create a classes and variables with data types.4. Create an object of relevant class, to call the procedure.5. Create an object to call the packages.6. Return arithmetic operations.7. Print the concatenation of string.8. Stop the program.3. PROGRAM:package Mathc;public class Arithmetic{public int a,b;public Arithmetic(int p,int q){a=p;b=q;}public int add(){return(a+b);}public int sub(){return(a-b);}public int mul(){return(a*b);}public int div(){return(a/b);}}65
  66. 66. import java.io.*;import Mypack.*;class Usepack{public static void main(String args[]) throws IOException{BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter 2 numbers to perform add,sub and mul");int i=Integer.parseInt(stdin.readLine());int j=Integer.parseInt(stdin.readLine());Mul m=new Mul();Addsub a=new Addsub();a.add(i,j);m.mul(i,j);m.add(i,j);m.sub(i,j);}}4. OUTPUT:Enter 2 numbers to perform add,sub and mul10 20Result of multiplying is 300Result of adding is 30Result of subtracting is -10Enter 2 numbers to perform add,sub and mul5 10Result of multiplying is 50Result of adding is 15Result of subtracting is -5Enter 2 numbers to perform add,sub and mul2 1Result of multiplying is 2Result of adding is 3Result of subtracting is 166
  67. 67. 24. Experiment no. 24 : Program which imports the package Mathc1. AIM:Write a java program to implement Arithmetic operations thepackages.2. Algorithm:1. Start the program.2. Import the Mathc packages.3. Create a classes and variables with data types.4. Create an object of relevant class, to call the procedure.5. Create an object to call the packages.6. Return arithmetic operations.7. Print the concatenation of string.8. Stop the program.3. PROGRAM:import Mathc.*;public class PackDemo{public static void main(String args[]){Arithmetic a=new Arithmetic(10,30);System.out.println(a.add());System.out.println(a.sub());System.out.println(a.mul());System.out.println(a.div());}}4. OUTPUT:40-20300067
  68. 68. 25. Experiment no. 25 : Program to print JAVA IS SIMPLE in differentstyles and fonts1. AIM:Write a java program to implement the APPLET PACKAGESprograms.2. Algorithm:1. Start the program.2. Import the packages of applet,awt.3. Create a classes public void paint(Graphics g).4. Assume the values of string, color and font.5. g.drawString() application of GUI.6. Printing in the separated Applet viewer window.7. Stop the program.3. PROGRAM:import java.awt.*;import java.applet.*;import javax.swing.*;/*<applet code="JavaDemo" width=350 height=200></applet>*/public class JavaDemo extends JApplet{public void paint(Graphics g){Font f1=new Font("TimesNewRoman",Font.BOLD|Font.ITALIC,20);g.setFont(f1);String str="JAVA IS SIMPLE";g.drawString(str,10,20);Font f2=new Font("Helvetica",Font.BOLD,30);g.setFont(f2);g.setColor(Color.RED);g.drawString(str,10,60);Font f3=new Font("TimesNewRoman",Font.PLAIN,40);g.setFont(f3);g.setColor(Color.GREEN);g.drawString(str,10,100);}}68
  69. 69. 4. OUTPUT*/69
  70. 70. 26. Experiment no. 26: Program to draw Lines, Rectangles, RoundedRectangles, filled Polygons and Ovals1. AIM:Write a java program to implement the APPLET PACKAGES, drawLines, Rectangles, Rounded Rectangles, filled Polygons programs.2. Algorithm:1. Start the program.2. Import the packages of applet,awt,awt.event.3. Create a classes: public void paint(Graphics g).4. Assume the values of string, color and font.5. g.drawString() application of Graphical User Interface.6. Printing in the separated Applet viewer window.7. Stop the program.3. PROGRAM:import java.awt.*;import java.applet.*;import java.awt.event.*;/*<applet code="ShapeDemo" width=300 height=300></applet*/public class ShapeDemo extends Applet{public void paint(Graphics g){setLayout(new FlowLayout());g.drawLine(10,20,50,20);g.drawRect(20,30,30,30);g.setColor(Color.RED);g.fillRect(20,30,30,30);g.drawRoundRect(20,70,50,70,15,15);g.setColor(Color.GREEN);g.fillRoundRect(20,70,50,70,15,15);g.drawOval(20,150,50,50);g.setColor(Color.BLUE);g.fillOval(20,150,50,50);}}70
  71. 71. 4. OUTPUT:71
  72. 72. 27. Experiment no. 27: Program to implement Action Event thatperforms Arithmetic Operations1. AIM:Write a java program to implement the APPLET PACKAGES, drawevent handlers programs.2. Algorithm:1. Start the program.2. Import the packages of applet, awt, awt.event.3. Create a classes, methods.4. Assume the values of string Integer.parseInt.5. while using if loops rotating values.6. The event arguments execution.7. Printing in the separated Applet viewer window.8. Stop the program.3. PROGRAM:import java.awt.*;import java.awt.event.*;import javax.swing.*;public class EventDemo extends JFrame implements ActionListener{public JLabel l1,l2,l3;public JTextField t1,t2;public JButton b1,b2,b3;EventDemo( ){Container c = getContentPane( );c. setLayout(new FlowLayout());l1=new JLabel("NUM 1");l2 = new JLabel("NUM 2");l3 = new JLabel( );t1 = new JTextField(6);t2 = new JTextField(6);b1 = new JButton("ADD");b2 = new JButton("SUB");b3 = new JButton("MUL");c.add(l1);72
  73. 73. c.add(t1);c.add(l2);c.add(t2);c.add(b1);c.add(b2);c.add(b3);c.add(l3);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);setSize(200,200);setVisible(true);}public void actionPerformed(ActionEvent ae){int n1,n2,n3=0;n1 = Integer.parseInt(t1.getText( ).trim());n2 = Integer.parseInt(t2.getText( ).trim());String str = "The result is ";if(ae.getSource( ) == b1)n3=n1 + n2;if(ae.getSource( ) == b2)n3= n1-n2;if(ae.getSource( ) == b3)n3=n1*n2;l3.setText(str+" " +n3);}public static void main(String args[ ] ){EventDemo e = new EventDemo( );}}4. OUTPUT73
  74. 74. 28. Experiment no. 28: Program to implement Mouse Listener(Mouse Events)1. AIM:Write a java program to implement the APPLET PACKAGES, drawMouse event handler programs.2. Algorithm:1. Start the program.2. Import the packages of applet, awt, awt.event.3. Create a classes, methods.4. Mouse moments, mouse Clicked, mouse Pressed, mouse Released,mouse Entered, mouse Exited, mouse Dragged events args.5. g.drawString() application of Graphical User Interface.6. While rotating mouse event args.7. The mouse event arguments execution.8. Printing in the separated Applet viewer window.9. Stop the program.3. PROGRAM:import java.awt.*;import java.applet.*;import java.awt.event.*;/*<applet code="MouseDemo" width=300 height=300></applet>*/public class MouseDemo extends Applet implementsMouseListener,MouseMotionListener{int mx=0;int my=0;String msg="";public void init(){addMouseListener(this);addMouseMotionListener(this);}public void mouseClicked(MouseEvent me){mx=20;my=40;msg="Mouse Clicked";repaint();74
  75. 75. }public void mousePressed(MouseEvent me){mx=30;my=60;msg="Mouse Pressed";repaint();}public void mouseReleased(MouseEvent me){mx=30;my=60;msg="Mouse Released";repaint();}public void mouseEntered(MouseEvent me){mx=40;my=80;msg="Mouse Entered";repaint();}public void mouseExited(MouseEvent me){mx=40;my=80;msg="Mouse Exited";repaint();}public void mouseDragged(MouseEvent me){mx=me.getX();my=me.getY();showStatus("Currently mouse dragged"+mx+" "+my);repaint();}public void mouseMoved(MouseEvent me){mx=me.getX();my=me.getY();showStatus("Currently mouse is at"+mx+" "+my);repaint();}public void paint(Graphics g){g.drawString("Handling Mouse Events",30,20);75
  76. 76. g.drawString(msg,60,40);}}4. OUTPUT76
  77. 77. 29. Experiment no. 29: Program to implement KeyListener (Key Events)1. AIM:Write a java program to implement the APPLET PACKAGES, drawKey event Listeners programs.2. Algorithm:1. Start the program.2. Import the packages of applet, awt, awt.event.3. Create a classes, methods.4. Key moments, key Clicked, key Pressed, key Released, key Entered,key Exited, key Dragged events args.5. g.drawString() application of Graphical User Interface.6. while rotating key event args.7. Printing in the separated Applet viewer window.8. Stop the program.3. PROGRAM:import java.awt.*;import java.applet.*;import java.awt.event.*;/*<applet code="KeyDemo" width=300 height=300></applet>*/public class KeyDemo extends Applet implements KeyListener{String msg="";int x=10;int y=20;public void init(){addKeyListener(this);requestFocus();}public void keyPressed(KeyEvent ke){showStatus("key pressed");int key=ke.getKeyCode();77
  78. 78. switch(key){case KeyEvent.VK_UP:msg=msg+"<up>";break;case KeyEvent.VK_SHIFT:msg=msg+"<shift>";break;case KeyEvent.VK_F1:msg+="<F1>";break;}repaint();}public void keyReleased(KeyEvent ke){showStatus("Key Released");}public void keyTyped(KeyEvent ke){char ch=ke.getKeyChar();msg=msg+ch;showStatus("Key Typed");}public void paint(Graphics g){g.drawString(msg,40,40);}}4. OUTPUT78
  79. 79. 30. Experiment no. 30: Program to implement BorderLayout1. AIM:Write a java program to implement the APPLET PACKAGES, CreateBorder layout of window.2. Algorithm:1. Start the program.2. Import the packages of applet, awt, awt.event.3. Create classes and methods.4. Declare the Border Layout directions.5. Application of Graphical User Interface.6. Printing in the separated Applet viewer window.7. Stop the program.3. PROGRAM:import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code = "BorderDemo" width=300 height=300></applet> */public class BorderDemo extends Applet{public void init( ){setLayout(new BorderLayout( ));add(new Button("CSE students"),BorderLayout.NORTH);add(new Label("studying well"),BorderLayout.SOUTH);add(new Button("right"),BorderLayout.EAST);add(new Button("left"),BorderLayout.WEST);String msg = "This is the Demo for BorderLayout"+"done by Cse-1 students";add(new TextArea(msg),BorderLayout.CENTER);}}79
  80. 80. 4. OUTPUT80
  81. 81. 31. Experiment no. 31: Program to implement Radio Listener1. AIM:Write a java program to implement the APPLET PACKAGES, CreateRadio buttons in a window.2. Algorithm:1. Start the program.2. Import the packages of applet, awt, awt.event.3. Create classes, methods.4. Declare the Radio buttons and give values.5. Application of Graphical User Interface.6. Printing in the separated Applet viewer window.7. Stop the program.3. PROGRAM:import java.awt.*;import java.awt.event.*;import javax.swing.*;public class RadDemo extends JFrame implements ActionListener{public JLabel l1;public JRadioButton r1,r2,r3;RadDemo(){Container c = getContentPane( );c.setLayout(new FlowLayout( ));l1=new JLabel();r1 = new JRadioButton("CSE");r2 = new JRadioButton("ECE");r3 = new JRadioButton("EEE");ButtonGroup bg = new ButtonGroup( );bg.add(r1);bg.add(r2);bg.add(r3);c.add(r1);c.add(r2);c.add(r3);c.add(l1);r1.addActionListener(this);r2.addActionListener(this);r3.addActionListener(this);setSize(200,200);setVisible(true);81
  82. 82. }public void actionPerformed(ActionEvent ae){if(ae.getActionCommand()=="CSE"){l1.setText("You selected CSE");}if(ae.getActionCommand()=="ECE"){l1.setText("You selected ECE");}if(ae.getActionCommand()=="EEE"){l1.setText("You selected EEE");}}public static void main(String args[]){RadDemo rd=new RadDemo();}}4. OUTPUT82
  83. 83. References:1. The complete reference Java, J2SE 5thedition, Herbert Schild, TMH publishing Companylimited, New Delhi.2. Big Java 2ndedition, Cay Horstmann, John Wiley and Sons.3. Java how to programme, sixth edition, H.M.Dietel and P.J. Deitel.4. Core java 2,Vol2, Advanced Fundamentals Cay, S. Horshmann and Gary ComellSeventh edition Person edition.83

×