Lab Name: Java Programming

Lab Code: PCCS7303

Branch: CSE

Semester: 5th

Syllabus As per BPUT:

  1. Introduction, Compiling & executing a java program.
  2. data types & variables, decision control structures: if, nested if etc.
  3. loop control structures: do, while, for etc.
  4. classes and objects.
  5. data abstraction & data hiding, inheritance, polymorphism.
  6. threads, exception handlings and applet programs
  7. interfaces and inner classes, wrapper classes, generics

Lab Objective

At the end of the course students should

  • be familiar with the main features of the Java language;
  • be able to write a Java program to solve a well specified problem;
  • understand a Java program written by someone else;
  • be able to debug and test Java programs;
  • be familiar with major parts of Java 7 SE libraries;
  • understand how to read Javadoc library documentation and reuse library code.

Lab Outcome

1. To be able to apply an object oriented approach to programming and identify potential benefits of object oriented programming over other approaches.

2. To be able to reuse the code and write the classes which work like built in types.

3. To be able to design applications which are easier to debug, maintain and extend.

4. To be able to apply object - oriented concepts in real world applications

5. To be able to develop applications using multi-threading.

6. To be able to handle exceptions in any application.

7. To be able to develop GUI applications using AWT and Swing.

Lab Mapping

Contribution of Courses to Program Outcomes: (mapping)

Program Outcomes
TYPE / Modules / COURSE NUMBER & TITLE / a / b / c / d / e / f / g / h / i / j / k
LAB
Number of courses contributing strongly to each program outcome

Type:

LAB - - Strong contribution

- Average contribution

- Some contribution

- No contribution

List of Experiment

1. Experiment 1

1.1. Write a program to read regno, name, branch, address, phno from the keyboard and display.

1.2. Write a program to read 3 numbers from command line arguments. Calculate the sum and average and display.

2. Experiment 2

2.1. Write a program to read the marks in 6 subjects. Calculate the percentage and display the grade.

2.2. Write a program to read the ages of three students and display the younger one.

2.3. As per Gregorian calendar it is monday as on 01-01-0001. If any year number is entered then find the day of 1st January of that year.

3. Experiment 3

3.1. Write a program to read a number and check whether it is prime or not.

3.2. Write a program to read an upper bound of the range and display the fibonacci Series upto that range.

4. Experiment 4

4.1. Create a class Rectangle having data members length and breadth. Define 2 methods, one to read the length and breadth of the rectangle and another to calculate and display the area and perimeter of the rectangle. Test this class by creating two objects.

4.2. Create a class Student having data members registration number, name, branch and marks in 6 subjects. Define two methods, one for reading the data of the student and another to calculate and display the aggregate and percentage of marks. Test this by creating an array of 10 students.

5. Experiment 5

5.1. Assume that a bank maintains two kinds of accounts for customers, one called as savings account and the other as current account. The savings account provides compound interest and withdrawl facilities but no cheque book facility. The current account provides cheque book facility but no interest. Current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed.

Create a class account that stored customer name, account number and type of account. From this derive the classes cur_acct, sav_acct to make them more specific to their requirements. Include necessary member function in order to achieve the following tasks:

i) Accept deposit from a customer and update the balance

ii) Display the balance

iii) Compute the deposit interest

iv) Permit withdrawl and update the balance

v) Check for the minimum balance, impose penalty, necessary, and update the balance.

5.2. Create a class Bicycle that stores cadence, gear and speed. Define a constructor to initialize the data members. It contains 4 methods setCadence(), setGear(), applyBrake() and speedUp().

From this class derive a class MountainBike that adds a new member seatHeight. Define a constructor to initialize the data members. It contains one method setHeight(). Create the main class to test this program.

6. Experiment 6

6.1. Write a program to overload a method calculateArea() to calculate the area of circle and rectangle.

6.2. Create a class Bank having a method getRateOfInterest(). The rate of interest varies from bank to bank. Inherit this class to the classes SBI, ICICI, AXIS. Write a program for these banks to return their rate of interest.

7. Experiment 7

7.1. Write a program to read two numbers into m and n. Display the division m/n. Handle the exception in the program.

7.2. Write a program to initialize two arrays accno and balance of 10 persons. Create a user exception class to display the data and generate exception when the balance amount is less than 1000.00

8. Experiment 8

8.1. Create a class BookTicket which will have a thread to book a ticket. Create a class CancelTicket which will have a thread to cancel a ticket. There will be two objects train and compartment. Both the Thread will work on both the objects. Write a program to manage the threads without deadlock.

8.2. Write a program to create a digital clock using applet.

9. Experiment 9

9.1. Create an interface Car having two methods braking() and steering(). Create two classes Maruti and Hyundai and implement the class Car. Create a main class to manage the program.

9.2. Create a class BankAcct with data member account number and balance. Create an inner class Interest with data members rate of interest. Define a constructor to initialize the data members of BankAcct class and a method to pass the rate of interest to Interest class to calculate the interest amount on the available balance.

List of Experiment Beyound Syllabus (At least 2)

1. Experiment 1

1.1. Write a program to create a frame and display your name and photograph.

1.2. Write a program to create a frame. Create two text boxes and a button. The user will enter two numbers into two text boxes and when the button will be clicked it will display the sum of the two number on a label.

2. Experiment 2

2.1. Write a program to connect to database and to display the details of employee.

2.2. Write a program to connect to database and insert a record into the database.

3. Experiment 3

3.1. Write a program to connect to database and increment the salary by 5000 of the employee having empno 7688.

3.2. Write a program to connect to database and delete the records from dept table where deptno=40.

Experiment 1

1.1. Write a program to read regno, name, branch, address, phno from the keyboard and display.

Theory:

Reading data from keyboard:

There are many ways to read data from the keyboard. For example:

  • InputStreamReader
  • Console
  • Scanner
  • DataInputStream etc.

InputStreamReader class:

InputStreamReader class can be used to read data from keyboard.It performs two tasks:

  • connects to input stream of keyboard
  • converts the byte-oriented stream into character-oriented stream

Syntax:

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader class:

BufferedReader class can be used to read data line by line by readLine() method and character by character by read() method.

Syntax:

BufferedReader br = new BufferedReader(isr);

br.read();

br.readLine();

Java Console class

The Java Console class is be used to get input from console. It provides methods to read text and password.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.

Let's see a simple example to read text from console.

  1. String text=System.console().readLine();
  2. System.out.println("Text is : "+text);

Methods of Console class

Let's see the commonly used methods of Console class.

Method / Description
1) public String readLine() / is used to read a single line of text from the console.
2) public String readLine(String fmt,Object... args) / it provides a formatted prompt then reads the single line of text from the console.
3) public char[] readPassword() / is used to read password that is not being displayed on the console.
4) public char[] readPassword(String fmt,Object... args) / it provides a formatted prompt then reads the password that is not being displayed on the console.

How to get the object of Console

System class provides a static method console() that returns the unique instance of Console class.

public static Console console(){}

Let's see the code to get the instance of Console class.

Console c = System.console();

To read the data from keyboard

String str = c.readLine();

Java Scanner class

There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and primitive types using regular expression.

Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class

There is a list of commonly used Scanner class methods:

Method / Description
public String next() / it returns the next token from the scanner.
public String nextLine() / it moves the scanner position to the next line and returns the value as a string.
public byte nextByte() / it scans the next token as a byte.
public short nextShort() / it scans the next token as a short value.
public int nextInt() / it scans the next token as an int value.
public long nextLong() / it scans the next token as a long value.
public float nextFloat() / it scans the next token as a float value.
public double nextDouble() / it scans the next token as a double value.

Syntax:

Scanner sc = new Scanner(System.in);

int x = sc.nextInt();

java.io.PrintStream class:

The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException.

Commonly used methods of PrintStream class:

There are many methods in PrintStream class. Let's see commonly used methods of PrintStream class:

  • public void print(boolean b): it prints the specified boolean value.
  • public void print(char c): it prints the specified char value.
  • public void print(char[] c): it prints the specified character array values.
  • public void print(int i): it prints the specified int value.
  • public void print(long l): it prints the specified long value.
  • public void print(float f): it prints the specified float value.
  • public void print(double d): it prints the specified double value.
  • public void print(String s): it prints the specified string value.
  • public void print(Object obj): it prints the specified object value.
  • public void println(boolean b): it prints the specified boolean value and terminates the line.
  • public void println(char c): it prints the specified char value and terminates the line.
  • public void println(char[] c): it prints the specified character array values and terminates the line.
  • public void println(int i): it prints the specified int value and terminates the line.
  • public void println(long l): it prints the specified long value and terminates the line.
  • public void println(float f): it prints the specified float value and terminates the line.
  • public void println(double d): it prints the specified double value and terminates the line.
  • public void println(String s): it prints the specified string value and terminates the line./li>
  • public void println(Object obj): it prints the specified object value and terminates the line.
  • public void println(): it terminates the line only.
  • public void printf(Object format, Object... args): it writes the formatted string to the current stream.
  • public void printf(Locale l, Object format, Object... args): it writes the formatted string to the current stream.
  • public void format(Object format, Object... args): it writes the formatted string to the current stream using specified format.
  • public void format(Locale l, Object format, Object... args): it writes the formatted string to the current stream using specified format.

Pseudo Code / Algorithm/ Flow Chart

Step-1: Import the java.io and java.lang package

Step-2: Define a class

Step-3: Write the main() method and throw the IOException

Step-4: Create BufferedReader object

Step-5: Read data from the keybaord

Step-6: Display the data

Input:

1. Valid Input

1.1. What will be the output if I type

Regn. No.: 9999999999

Name: Narendra Modi

Branch: CSE

City: Gujrat

Phone No.: 9438054623

output:

1.2. What will be the output if I type

Regn. No.: 7777777777

Name: Pranab Mukherjee

Branch: CSE

City: Kolkata

Phone No.: 9434025623

output:

2. Invalid Input

2.1. What will be the output if I type

Regn. No.: Rajib

Name: 5555555555

City: 8586895758

Phone No.: Kolkata

output:

2.2. What will be the output if I type

Regn. No.: Sanjay

Name: 4444444444

City: 2222222222

Phone No.: Deepak

output:

1.2. Write a program to read 3 numbers from command line arguments. Calculate the sum and average and display.

Pseudo Code / Algorithm/ Flow Chart

Step-1: Import the java.lang package

Step-2: Define a class

Step-3: Write the main() method

Step-4: Declare three variables and assign the value using command line argument

Step-5: Calculate the sum

Step-6: Display the sum

Input:

1. Valid Input

1.1. What will be the output if I type

java FileName 45 56 67

output:

1.2. What will be the output if I type

java FileName 154 578 658

output:

2. Invalid Input

2.1. What will be the output if I type

java FileName ten twenty thirty

output:

2.2. What will be the output if I type

java FileName rajib ramesh deepak

output:

Viva-Voce Question(At least 5 fundamental question related to experiments)

1. What is the most important feature of Java?

Ans: Java is a platform independent language.

2. What do you mean by platform independence?

Ans: Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

3. What is a JVM?

Ans: JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

4. Are JVM's platform independent?

Ans: JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

5. What is the difference between a JDK and a JVM?

Ans: JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

6. What is a pointer and does Java support pointers?

Ans: Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

7. What is the base class of all classes?

Ans:java.lang.Object

8. Can an application have multiple classes having main() method?

Ans: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned.

Hence there is not conflict amongst the multiple classes having main() method.

9. Can I have multiple main() methods in the same class?

Ans: No the program fails to compile. The compiler says that the main() method is already defined in the class.

10. Do I need to import java.lang package any time? Why ?

Ans: No. It is by default loaded internally by the JVM.

11. Can I import same package/class twice? Will the JVM load the package twice at runtime?

Ans: One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

12. Should a main() method be compulsorily declared in all java classes?

Ans: No not required. main() method should be defined only if the source class is a java application.

13. What is the return type of the main() method?

Ans: Main() method doesn't return anything hence declared void.

14. Why is the main() method declared static?

Ans: main() method is called by the JVM even before the instantiation of the class hence it is declared as static.

15. What is the arguement of main() method?

Ans: main() method accepts an array of String object as arguement.

16. Can a main() method be overloaded?

Ans: Yes. You can have any number of main() methods with different method signature and implementation in the class.

17. Does the order of public and static declaration matter in main() method?

Ans: No. It doesn't matter but void should always come before main().

18. What is a package?

Ans: Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

19. Which package is imported by default?

Ans: java.lang package is imported by default even without a package declaration.

20. What is static in java?

Ans: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.