You are on page 1of 15

Topic : Evolution of Java, Java architecture, Language Basics, Flow control 1 Write a program to print "Hello World" on Console.

2 wap to accept 2 Strings Wipro Bangalore as command line arguments and print the output Wipro Technologies Bangalore If the command line is ABC Mumbai, then it should print ABC Technologies Mumbai . 3 write a program to find whether a number is Prime or not[Hint: To convert a command line argument to integer you have to use int i=Integer.parseInt(args[0])] 4 wap to accept a String from the command prompt and display wheth the string is a palindrome or not. [Hint :You have to extract each character from the beginning and end of the String and compare it with each other. String x=Malayalam; char c= x.charAt(i) where i is the index] 5 Write a program that will accept a 4 digit number(assume that the user enters only 4 digit nos.) and print the sum of all the 4 digits. For ex : If the number passed is 3629, the program should print The sum of all the digits entered is 20 1 Write a program to find input is positive or negative. 2 Write a program to print month in words, based on input month in numbers.(using switch case) 3 Write a program to print factorial of N ( using dowhile loop) 4 Write a program to print * in Floyds format (using for and while loop) 5Try to execute java program by defining main i) Without public modifierii) Without static modifieriii) Without argument iv) with integer argumentv) interchange public static keyword Topic : Arrays,Class, Method, Constructor Fundamentals, this operator 1 Write a program to find greatest number in an array 2 Write a program to sort a numeric array element in ascending order 3 Write a program to create a class Book with the following - attributes:-isbn, title, author, price - methods : i. Initialize the data members through parameterized constructor ii. displaydetails() to display the details of the book iii. discountedprice() : pass the discount%, cal the discnt on price and find the amt to be paid after discnt - task :

Create an object book, initialize the book and display the details along with the discounted price 4 Implement a class Employee with appropriate state and behavior. Write Demo java program to test Employee object behavior 5 Write a program to create a class Student with the following :- attributes :StudentId, Name, contactNo, course,fees.- methods : i. constructor to populate the objects ii. display function to display the details of the students iii. return the coursefees - task : Create 5 students and perform the following : i. display the student details coursewise ii. display the total fees of all the students 1 Write a program to display number matrix as follows using Two Dimensional Rectangular Array. 1234 5678 9 10 11 12 2 Write a program to create a class Student with the following : - attributes :StudentId, Name, contactNo, course,fees.- methods : i. constructor to populate the objectsPage 5 of 25 ii. display function to display the details of the students iii. return the coursefees - task : Create 5 students and perform the following : i. display the student details coursewise ii. display the total fees of all the students 3 Write a program to create a class Vehicle with the following - attributes :Regno, brand, price, mileage- methods : i. constructor to initialize the vehicles

ii. display function to display the details of the vehicles iii. return only the price of the vehicle - task : Create 2 vehicles, enter the details. Display the vehicle with lowest price and display the vehicle with best mileage 4 Create an Account class with the following structure.Create objects of the account class and test that all the functionalities are implemented properly. 5 Create classes as shown in the diagram and test the classesPage 6 of 25 Topic : OOP concepts and implementation in Java 1 Represent this hierarchy of administration of an organization through inheritance. Assume data member and method as per requirement. 2 Give the definition of a class named Doctor whose objects are records for a clinics doctors. This class will be a derived class of the class SalariedEmployee Base class.A Doctor record has the doctors specialty (such as "Pediatrician","Obstetrician", "General Practitioner", and so forth; so use the type String) and office visit fee (use type double). Be sure your class has a reasonable complement of constructors, accessor and mutator methods, and suitably defined equals and Page 7 of 25toString methods. Write a program to test all your methods. 3 Define a class named Document that contains a member variable of type String named text that stores any textual content for the document. Create a method named toString that returns the text field and also include a method to set this value. 4 Next, define a class for Email that is derived from Document and includes member variables for the sender, recipient, and title of an email message. Implement appropriate accessor and mutator methods. [An accessor is a member function that accesses the contents of an object but does not modify that object; eg: int getX(return x;)A mutator is a member function that can modify an object void setX(int x){this.x=x;} ]The body of the email message should be stored in the inherited variable text. Redefine the toString method to concatenate all text fields. 5 Given a java class EmployeeMain, which accepts four parameters from the command line. Employee Name, dept, designation and basic salary. These inputs are passed to the object of a class called Employee through its constructor and these details are stored within instance variables of the class. There is a method called employeeDetails within Employee class, which prints the Name, dept and designation of the employee. Employee class is extended by two classes Manager and Clerk. Manager class contains a method called calculateSalary, where salary is calculated as 10 times basic. Similarly Clerk class contains a method called calculateSalary which calculates the salary as 3 times of basic. class EmployeeMain { public static void main(String [] args) { String name = args[0]; String dept = args[1]; String desig = args[2];String basic = Integer.parseInt(args[3]); if(dept.equals("Mgr"))

Manager x1 = new Manager(name,dept,desig,basic); else Clerk x1 = new Clerk(name,dept,desig,basic); x1.employeeDetails(); x1.calculateSalary();} } 1 Create a class named Movie that can be used with your video rental business. The Movie class should track the Motion Picture Association of America (MPAA) rating (e.g., Rated G, PG-13, R), ID Number, and movie title with appropriate accessor and mutator methods. Also create an equals() method that overrides Objects equals() method, where two movies are equal if their ID number is identical. Next, create three additional classes named Action, Comedy, and Drama that are derived from Movie.Each of these movies will have a method named calcLateFees that takes as input the number of days a movie is late and returns the late fee for that movie. The default late fee is $2/day. Action movies have a late fee of $3/day, comedies are $2.50/day, and dramas are $2/day. Test your classes from a main method. 2 Write a program to create a class Book with the following data members: isbn, title and price. Inherit the class Book to two derived classes : Magazine and Novel with the following data members: Magazine: type Novel : author

Populate the details using constructors.Create a magazine and Novel and display the details. 3 Write a program to create a class AccountHolder with the following attributes: AcNo, Name, contactNo. Inherit the class AccountHolder to AccountDetails with the following attributes:AcNo,AcType (SB,FD,CR), bal.Create two account Holders : a1 and a2. Populate the details and display the details in a neat format. 4 Write a program to create an Employee class with the following attributes:Empno, ename, address, contactNo.Inherit the class Employee to Manager class with the following attributes:Dept,Number-ofreporteesCreate 5 employees and 2 managers. Display all the details of employees and managers. 5 Write a program to create a class Company with the following attributes:CompId, name, HO, CEO. Inherit the class Company to BranchOffices with the following details:BrId, location,deptCreate 5 branches of the company and display the details. Topic : Method Overriding,Runtime Polymorphism,Abstract class,instanceof,Garbage collection 1 Create a class Car which contains members speed, noOfGear. The class has a method drive() which is responsible to provide starting speed and noOfGears to a Car. Implement display() method which will display all attributes of Car class.The class SportCar is derived from the class Car which adds new features AirBallonType. When this method is invoked, initial speed and gear status must be displayed on console. Override the display method which display all attribute of the SportCar. Make use of super class display() method. 2 Define a class named Payment that contains a member variable of type double that stores the amount of the payment and appropriate accessor and mutator methods. Also create a method named paymentDetails that outputs an English sentence to describe the amount of the payment.Next, define a

class named CashPayment that is derived from Payment. This class should redefine the paymentDetails method to indicate that the payment is in cash. Include appropriate constructor(s).Define a class named CreditCardPayment that is derived from Payment. This class should contain member variables for the name on the card, expiration date, and credit card number. Include appropriate constructor(s). Finally, redefine the paymentDetails method to include all credit card information in the printout.Create a main method that creates at least two CashPayment and twoCreditCardPayment objects with different values and calls paymentDetails for each.Page 10 of 25 3Create classes as shown in the UML diagram given above and test your classes 4 There is an animal class which has the common characteristics of all animals. Dog, Horse, Cat are animals(sub-class). Each can shout, but each shout is different. Use polymorphism to create objects of same and using an animal variable, make each of the animals shout. 5 Write a program to calculate the number of objects created at a given point using user defined class 1 Create an abstract class Instrument which is having the abstract function play. Create three more sub classes from Instrument which is Piano, Flute, Guitar.Override the play method inside all three classes printing a message Piano is playing tan tan tan tan for Piano class.Flute is playing toot toot toot toot for Flute class.Guitar is playing tin tin tin for Guitar class .You must not allow the user to declare an object of Instrument class.Create an array of 10 Instruments.Assign different type of instrument to Instrument reference.Check for the polymorphic behavior of play method.Use the instanceof operator to print that which object stored at which index of instrument array. 2 Create an abstract class Compartment to represent a rail coach. Provide an abstract function notice in this class. Derive FirstClass, Ladies, General, Luggage classes from the compartment class. Override the notice function in each of them to print notice suitable to the type of the compartment.Create a class TestCompartment . Write main function to do the following:Declare an array of Compartment of size 10.Create a compartment of a type as decided by a randomly generated integer in the range 1 to4.Check the polymorphic behavior of the notice method. 3 Define an abstract base class Shape that includes protected data members for the (x, y) position of a shape, a public method to move a shape, and a public abstract method show() to output a shape. Derive subclasses for lines, circles, and rectangles. Also, define the class PolyLine that you saw in this chapter with Shape as its base class. You can represent a line as two points, a circle as a center and a radius, and a rectangle as two points on diagonally opposite corners. Implement the toString() method for each class. Test the classes by selecting ten random objects of the derived classes, and then invoking the show() method for each. Use the toString() methods in the derived classes. 4 Develop a java class that has finalize method which displays Finalize method called. Create another class which creates objects of the previous class and it uses the same object reference for creating these objects. For example, if A1 is the class name, then the objects are created as below : A1 a = new A1(); a = new A1(); a = new A1();

When the statement Runtime.getRuntime().gc() is invoked, how many times the finalize method is called? Topic : Interfaces and Packages

1 Write an interface called Playable, with a method play();Let this interface be placed in a package called music.Write a class called Veena which implements Playable interface. Let this class be placed in a package music.stringWrite a class called Saxophone which implements Playable interface. Let this class be placed in a package music.windWrite another class Test in a package called live. Then, a. Create an instance of Veena and call play() method b. Create an instance of Saxophone and call play() method c. Place the above instances in a variable of type Playable and then call play() 2 Write program to calculate Area and volume depending upon type of figure by implementing interfaces for CalcArea and CalcVolumeFigure Area Perimeter Surface Area Volume _____________________________________________________________ Circle pi*r*r 2*pi*r,Square a*a 4*a ,Sphere pi*r*r 2*pi*r 4*pi*r*r (4/3)pi*r*r*r Cuboid a*a 4*a 6*a*a a*a*a 3 Create a package called test package;Define a class called foundation inside the test package; Inside the class, you need to define 4 integer variables; Var1 as private; Var2 as default; Var3 as protected; Var4 as public; Import this class and packages in another class. Try to access all 4 variables of the foundation class and see what variables are accessible and what are not accessible. 4 Create a package called Automobile. Define an abstract class called Vehicle. Vehicle class has the following abstract methods: public String modelName()public String registrationNumber()public String ownerName()Create TwoWheeler subpackage under Automobile packageHero class extends Automobile.vehicle class public int speed() Returns the current speed of the vehicle.public void radio() provides facility to control the radio device Honda class extends Automobile.vehicle class public int speed() Returns the current speed of the vehicle. public int cdplayer() provides facility to control the cd player device which is available in the car. Create a test class to test the methods available in all these child class. 5 Add the following ideas to the previous exercise: Create FourWheeler subpackage under Automobile packageLogan class extends Automobile.vehicle class public int speed() Returns the current speed of the vehicle. public int gps() provides facility to control the gps device Ford class extends Automobile.vehicle class public int speed() Returns the current speed of the vehicle. public int tempControl() provides facility to control the air conditioning device which is available in the car 1 Create classes and interfaces as shown in the diagram below and test your code.

Topic : Exception Handling 1 Write a program to accept name and age of a person from the command prompt(passed as arguments when you execute the class) and ensure that the age entered is >=18 and < 60. Display proper error messages. The program must exit gracefully after displaying the error message in case the arguments passed are not proper. (Hint : Create a user defined exception class for handling errors.) 2 Write a program to accept 5 integers passed as arguments while executing the class. Find the average of these 5 nos. Use ArrayIndexOutofBounds exception to handle situation where the user might have entered less than 5 integers. 3 Write a Program to take care of Number Format Exception if user enters values other that integer for calculating average marks of 2 students. The name of the students and marks in 3 subjects are passed as arguments while executing the program. 4 In the same Program write your own Exception classes to take care of Negative values and values out of range (i.e. other than in the range of 0-100) 5 Write a class MathOperation which accepts integers from command line. Create an array using these parameters. Loop through the array and obtain the sum and average of all the elements. Display the result. Check for various exceptions that may arise like ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, and so on. For example: The class would be invoked as follows: C:>java MathOperation 1900, 4560, 0, 32500 1 Create a Rectangle class with attributes length and breadth. The Rectangle class should have methods for computing the perimeter and area. The Rectangle class should be written to handle the exceptions that might occur while executing the program. A sample output is shown below: Enter the length: WhatPage 15 of 25 Something went wrong!!! Enter the height: 44.68 Rectangle Characteristics Length: 0.00 Height: 44.68 Perimeter: 89.36 Area: 0.00 2 Write a Division class with 2 data members x and y. The class has a method called divide which returns x/y value. If the value of y is 0 then the user should get a message that The division operation cannot

be done as the divisor is 0. Create a user defined InvalidDivisor exception which will be thrown when the divisor value is 0. Topic : Introduction to Multithreading,Java's Multithreading Model,Creating Multiple Threads,Thread Control Mechanism 1 Write a program to assign the current thread to t1. Change the name of the thread to MyThread. Display the changed name of the thread. Also it should display the current time. Put the thread to sleep for 10 seconds and display the time again. 2 In the previous program remove the try{}catch(){} block surrounding the sleep method and try to execute the code. What is your observation? 3 Write a program to create a class DemoThread1 implementing Runnable interface. In the constructor, create a new thread and start the thread. In run() display a message "running child Thread in loop : " display the value of the counter ranging from 1 to 10. Within the loop put the thread to sleep for 2 seconds. In main create 3 objects of the DemoTread1 and execute the program. 4 Rewrite the earlier program so that, now the class DemoThread1 instead of implementing from Runnable interface, will now extend from Thread class. 5 Write a program to create a class Number which implements Runnable. Run method displays the multiples of a number accepted as a parameter. In main create three objects - first object should display the multiples of 2, second should display the multiples of 5 and third should display the multiples of 8. Display appropriate message at the beginning and ending of thread. The main thread should wait for the first object to complete. Display the status of threads before the multiples are displayed and after completing the multiples.Page 16 of 25 Topic : Thread Priorities, Thread Synchronization, Inter thread communication 1 Write a Java Program which will print the current time on the console every 2 seconds. After doing this activity for 20 seconds the program quits. 2 Write a Java Program, where one thread prints a number ( Generate a random number using Math.random) and another thread prints the factorial of that given number. Both the outputs should alternate each other. Eg: Number : 2 Factorial of 2 : 2 Number : 5 Factorial of 5 : 120 The program can quit after executing 5 times. 3 /* The code given below should print "Wipro Technologies Bangalore". But inspite of print being

TestSynchronized, it gives us jumbled output. Find out the reason and make the necessary corrections, so as the code prints the desired output. */ class Helper { synchronized void print(String arg){ int l=arg.length(); for(int i=0; i<l; i++) { System.out.print(arg.charAt(i)); try{ Thread.sleep(1000); } catch (InterruptedException e){ System.out.println("Interrupted"); }} System.out.print(" "); }} class SynchroThread implements Runnable{ String arg;Page 17 of 25 Helper obj1; Thread t; public SynchroThread(String arg){ obj1=new Helper(); this.arg = arg; t = new Thread(this); t.start();} public void run(){ obj1.print(arg); }}

class TestSynchro{ public static void main(String args[]){ Helper obj1=new Helper(); SynchroThread x1 = new SynchroThread("Wipro"); SynchroThread x2 = new SynchroThread("Technologies"); SynchroThread x3 = new SynchroThread("Bangalore"); try{ x1.t.join(); x2.t.join(); x3.t.join();} catch (InterruptedException e){ System.out.println("Interrupted"); }}} Topic : Collection 1 Create an Employee class with the related attributes and behaviours. Create one more class EmployeeDB which has the following methods. a. boolean addEmployee(Employee e) b. boolean deleteEmployee(int eCode) c. String showPaySlip(int eCode)Page 18 of 25 d. Employee[] listAll() Use an ArrayList which will be used to store the emplyees and use enumeration/iterator to process the employees.Write a Test Program to test that all functionalities are operational. 2 Create an ArrayList which will be able to store only Strings. Create a printAll method which will print all the elements using an Iterator. 3 Create an ArrayList which will be able to store only numbers like int,float,double,etc, but not any other data type. 4 Create Collection called TreeSet which is capable of storing String objects. The Collection should have the following capabilities a)Reverse the elements of the Collection b)Iterate the elements of the TreeSet c) Checked if a particular element exists or not

5 Create a Collection called HashMap which is capable of storing String objects. The program should have the following abilities a) Check if a particular key exists or not b) Check if a particular value exists or not c) Use Iterator to loop through the map key set 1 Write a program that will have a Vector which is capable of storing emp objects. Use an Iterator and enumeration to list all the elements of the Vector. 2 Write a program that will have a Properties class which is capable of storing some States of India and their Capital. Use an Iterator to list all the elements of the Properties. 3 Create an ArrayList of Employee( id,name,address,sal) objects and search for particular Employee object based on id number and name. 4 Write a program creates a HashMap to store name and pone number (Telephone book). When name is give, we can get back the corresponding phone number. 5 wap to store a group of employee names into a HashSet, retrieve the elements one by one using an Iterator. Topic : Wrapper class , I/O Streams, Annotations 1 Write a Program to display the contents of a file Line by line. 2 Write a program to Write 1) Date object 2) a Double object and 3) A Long object to file and again reading it back from file. 3 Create a class called Person with data members name and age and a member function called display() which displays the name and age.Create a class called Student which inherits Person, with data members university and degree. The Student class should override the display() function to display all the details of the Student.Use @Override annotation to make sure that the class overrides the display function of the Person class only.Identify the usage of @Override function and note it down. 4 Create an annotation for the following code snippet@Copyright("2012 Wipro Technologies")public class PRP { ... } 5 Create an annotation for the following code snippet@RequestForEnhancement(id = 2868724, synopsis = "Enable time-travel",engineer = "Mr. Ram",date = "9/5/2012") public static void travelThroughTime(Date destination) { ... } 1 Create a class-level run-time annotation called @DBParams that will enable you to specify the name of the database, the user ID, and the password. Write a class that uses this annotation. 2 Write a program to create a sequential file that could store details about the six products. Details include product id, cost & number of items available & are provided through the keyboard. Perform following operations on it a. Compute and print the total value of all six products. b. Add new products c. Display alternate products stored in the file.

3 Create a file named the Numbers and populate it with 30 random numbers in the range 1 to 30 including the end points. Place 1 number per line. Open the file and print the numbers 10 per line Find and print the following .1. Average of the numbers2. Sum of the numbers 4 Write a program which copies the content of one file to a new file by removing unnecessarily spaces between words. 5 In the code that is given below, make changes so that the code gets compiled without any warnings. import java.util.*; class eg {public static void main(String args[]) {Date date = new Date(); int year = date.getYear(); }} Topic : Applets 1 Create an Applet which can accept a name as parameter, display the name on the applet in the reverse order. 2 Design an applet which loads an image passed as parameter to the applet. 3 Create an Applet which will change the background color from red to blue and from blue to green. This color change shall occur after every 2 seconds. 4 Create an applet and draw a randomly moving circle which fills up with random colors. 5 Create an applet that displays the current time. The applet should updated on change of time. 1 Create an applet that will act as an Ad-Rotator. Take 3 images of equal dimensions and 3 respective ad captions. Display each image and its ad caption at intervals of 5 seconds. 2 Write a Java program to accept marks in percentage of 3 subjects for 3 students from the console. 1. Find the average marks in percentage 2. Display the result of 3 students with their marks for each subject and their average through a bar chart in an applet. Hint: Use fillRect() for drawing bar chart Topic : AWT 1 Create an AWT Frame which contains a Label, a TextField, a Choice and a Button.Arrange them in FlowLayout 1. Arrange them in GridLayout 2. Arrange them in BorderLayout 2 Create an AWT application with a username and password field, so that relevant information can be entered. The password entered must be masked by * character.

3 Write a java program to accept the number of rows and number of columns from console. Based on the number of rows and columns generate an array of buttons with a label AWT in each grid cell. 4 Create a choice box and fill it up with all the prime numbers from 1 to 50. 5 Use Canvas class to load an image 1 1. Create an AWT application that will look like an Arithmetic Calculator:Note: This design will help you solve assignment in Event Handling 2 Create an applet which contains a non editable textarea. The filename passed as Page 22 of 25parameter to the applet is read and its contents are displayed in the text area. In labels below, display the total number of lines, words and characters in the file. Topic : Event Handling 1 Design an Arithmetic Calculator which looks like this: i. There must be text field that accepts only numbers. ii. The calculator must have numerical buttons 0 to 9 iii. It must have the arithmetic operator buttons +, -, *, / and = (for result) iv. There must be a clear button C, which when pressed, clears the textfield values and displays 0 The calculator must perform the arithmetic operations on the values supplied in the text field and the result must be displayed on the text field 2 Create a Hover Button which is displayed on an applet. A hover button is a button which changes color when mouse is taken over that or when it is pressed. a. Draw an AWT Button with initial background color as color1 and the text CLICK displayed as its label b. When mouse is taken over it change the background color to color2 c. When button is pressed then change the background color to color3 d. It returns to its initial color1 state when released Note: Choose the 3 colors of your choice Hint: Use MouseListener or MouseAdapter 1 Take the above calculator which you have designed and enhance it with some additional functionalities of scientific calculator. Add the square(x*x), trigonometric (sin, cos, tan, sec, cosec and cot) and logarithmic (log to the base 10) functionalities with relevant buttons. 2 Create a Date Chooser. Take 3 choice boxes one for date, one for month and one for year. Put 3 labels adjacent to each choice. Fill up the choice box with numbers for date, month and year (from 1980 to 2030). a. If a month is chosen, for example June, the no of days in date choice will be 1 to 30, again on July it will be 1 to 31 b. If year is leap year then February will have 29 days

Hint: Use ItemListener to trap the choices made Topic : Swing 1 Create an application which will run a progressbar from 1 to 100 and also display the progress percentage in an adjascent label. The progressbar value should increment by 10 in 500 millisecond. Once the progressbar has reached 100% a message dialog window pops up displaying WELCOME TO SWING. 2 Design a GUI for a Java application that converts miles to kilometers. Write the class that performs the conversions.The Design Layout is as follows:Guidance: A JLabel displays a short string of text or an image. It can serve as a prompt. Input: A JTextField allows editing of a single line of text. It can get the users input. Output: A JTextArea allows editing of multiple lines of text. Well use it to display results. Control: A JButton is an action control. By implementing the ActionListener interface we will handle the user's action events. 1 Create a JApplet with a JButton which when pressed will open a color chooser. The color which is chosen is set as the background of the JApplet. Expected Output: Initial State When the button is clicked After the color is chosen and color chooser closed 2 Create an Application that will behave like a Notepad Application a. The application must contain a menubar and a text area, the design just like notepad b. There will be 2 menus 1. File (First menu on the menu bar) 1. New will open a new file with blank textarea contents 2. Open will open a Open Filedialog box from where a file can be chosen for reading and the contents of the file is added into the textarea 3. Save saves the textarea contents into the pre-existing file which was opened for reading 4. Save As saves the textarea contents into a new file, which can be prompt: JTextArea for displaying file JTextField JButton Convert JFrame JLabel

Containment Hierarchy JFrame Prompt JLabel Display JTextArea Conv ert JButton Input JTextField JApplet JColorChooser JButtonPage 25 of 25 set in the Save Filedialog 5. Exit closes the application. Make sure that a prompt appears for saving the contents of the textarea. If pressed OK it will save in the same file, if NO then exit without saving textarea contents in the file 2. Edit (Second menu on the menu bar) 1. Cut will copy the selected portion into the clipboard and remove it from the textarea 2. Copy will copy the selected portion into the clipboard but will retain the text in the textarea 3. Paste will paste the copied portion from the clipboard to the selected area or where the cursor is currently pointing 3 Write a JDBC program to fetch data from the SCOTT.EMP table and display in a JTable. (Try this when you learn JDBC)

You might also like