cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/java_lab_m…  · web viewlab name: java...

78
Lab Name: Java Programming Lab Code: PCCS7303 Branch: CSE Semester: 5 th 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.

Upload: hathuan

Post on 31-Jan-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Lab Name: Java ProgrammingLab Code: PCCS7303Branch: CSESemester: 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 MappingContribution of Courses to Program Outcomes: (mapping)

Page 2: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Program OutcomesTYPE Modules COURSE NUMBER & TITLE a b c d e f g h i j kLAB

Number of courses contributing strongly to each program outcome

Type: LAB - - Strong contribution

- Average contribution

- Some contribution

- No contribution

List of Experiment

1. Experiment 11.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 22.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 33.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 44.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 55.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

Page 3: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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 66.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 77.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 88.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 99.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.

Page 4: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

List of Experiment Beyound Syllabus (At least 2)

1. Experiment 11.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 22.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 33.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();

Page 5: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

br.readLine();

Java Console classThe 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 classLet's see the commonly used methods of Console class.

Method Description1) 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 ConsoleSystem 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 classThere 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

Page 6: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

There is a list of commonly used Scanner class methods:

Method Descriptionpublic 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.

Page 7: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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 packageStep-2: Define a classStep-3: Write the main() method and throw the IOExceptionStep-4: Create BufferedReader objectStep-5: Read data from the keybaordStep-6: Display the data

Input:

1. Valid Input1.1. What will be the output if I type

Regn. No.: 9999999999Name: Narendra ModiBranch: CSECity: GujratPhone No.: 9438054623

output:

1.2. What will be the output if I typeRegn. No.: 7777777777Name: Pranab MukherjeeBranch: CSECity: KolkataPhone No.: 9434025623

output:

2. Invalid Input2.1. What will be the output if I type

Regn. No.: RajibName: 5555555555City: 8586895758Phone No.: Kolkata

Page 8: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

output:

2.2. What will be the output if I typeRegn. No.: SanjayName: 4444444444City: 2222222222Phone 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 packageStep-2: Define a classStep-3: Write the main() method Step-4: Declare three variables and assign the value using command line argumentStep-5: Calculate the sumStep-6: Display the sum

Input:

1. Valid Input1.1. What will be the output if I type

java FileName 45 56 67output:

1.2. What will be the output if I typejava FileName 154 578 658

output:

2. Invalid Input2.1. What will be the output if I type

java FileName ten twenty thirty

output:

Page 9: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

2.2. What will be the output if I typejava 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?

Page 10: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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

Page 11: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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.

A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

21. What if the main() method is declared as private?

Ans: The program compiles properly but at runtime it will give "main() method not public." message.

22. What if the static modifier is removed from the signature of the main() method?

Ans: Program compiles. But at runtime throws an error "NoSuchMethodError".

23. What if I write static public void instead of public static void?

Ans: Program compiles and runs properly.

24. What if I do not provide the String array as the argument to the method?

Ans: Program compiles but throws a runtime error "NoSuchMethodError".

25. What is the first argument of the String array in main() method?

Ans: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

26. If I do not provide any arguments on the command line, then the String array of main() method will be empty or null?

Ans: It is empty. But not null.

27. How can one prove that the array is not null but empty using one line of code?

Ans: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

28. What is difference between Path and Classpath?

Ans: Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

Experiment - 2

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

Page 12: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

the grade.

Theory

There are two types of decision making statements in Java. They are:

if statements

switch statements

The if Statement:An if statement consists of a Boolean expression followed by one or more statements.

Syntax:The syntax of an if statement is:

if(Boolean_expression){ //Statements will execute if the Boolean expression is true}

If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

The if...else Statement:An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:The syntax of an if...else is:

if(Boolean_expression){ //Executes when the Boolean expression is true}else{ //Executes when the Boolean expression is false}

The if...else if...else Statement:An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

When using if , else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Page 13: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Syntax:The syntax of an if...else is:

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}

Nested if...else Statement:It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

Syntax:The syntax for a nested if...else is as follows:

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }}

You can nest else if...else in the similar way as we have nested if statement.

The switch Statement:A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:The syntax of enhanced for loop is:

switch(expression){ case value : //Statements break; //optional case value : //Statements break; //optional //You can have any number of case statements. default : //Optional //Statements}

The following rules apply to a switch statement:

Page 14: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

The variable used in a switch statement can only be a byte, short, int, or char.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Pseudo Code / Algorithm/ Flow Chart

Step1: Import the java.io and java.lang packageStep2: Define a classStep3: Define the main() method and throw the IOEexception Step4: Create the BufferedReader objectStep5: Read the marksStep6: Calculate the percentage and display the grade using if-else-if-else statement.

Input:

1. Valid Input1.1. What will be the output if I typeMarks in 6 subjects: 45 65 48 57 95 68

output:

1.2. What will be the output if I typeMarks in 6 subjects: 95 95 76 49 98 87

output:

2. Invalid Input2.1. What will be the output if I typeMarks in 6 subjects: 45.75 95.36 85.17 25.36 42.56 84.35

output:

Page 15: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

2.2. What will be the output if I typeMarks in 6 subjects: five seven six four two eight

output:

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

Pseudo Code / Algorithm/ Flow Chart

Step1: Import the java.io and java.lang packageStep2: Define a classStep3: Define the main() method and throw the IOEexception Step4: Create the BufferedReader objectStep5: Read the ages of three studentsStep6: Write if-else-if-else statement to check the ages to find the younger one.

Input:

1. Valid Input1.1. What will be the output if I typeAges of 3 Students: 18 21 19

output:

1.2. What will be the output if I typeAges of 3 Students: 22 17 20

output:

2. Invalid Input2.1. What will be the output if I typeAges of 3 Students: 18.5 15.7 21.6

output:

2.2. What will be the output if I typeAges of 3 Students: five seven six

output:

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.

Pseudo Code / Algorithm/ Flow Chart

Step1: Import the java.io and java.lang package

Page 16: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step2: Define a classStep3: Define the main() method and throw the IOEexception Step4: Create the BufferedReader objectStep5: Read the year from the keyboardStep6: Calculate the total no of days upto that yearStep7: Find the leap days and add it to the total no of daysStep8: Divide the total no of days by 7 to find the remainderStep9: Write a switch case to display Monday if it is1, Tuesday if it is 2 like this.

Input:

1. Valid Input1.1. What will be the output if I typeYear : 2015

output:

1.2. What will be the output if I typeYear : 1996

output:

2. Invalid Input2.1. What will be the output if I typeYear : 15-08-2015

output:

2.2. What will be the output if I typeYear : twozeroonefive

output:

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

1: According to Java Operator precedence, which operator is considered to be with highest precedence?

Ans: Postfix operators i.e () [] . is at the highest precedence.

2: Variables used in a switch statement can be used with which datatypes?

Ans: Variables used in a switch statement can only be a byte, short, int, or char.

3: Which Java operator is right associative?

Ans: The = operator is right associative.

Page 17: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

4: List primitive Java types?

Ans: The eight primitive types are byte, char, short, int, long, float, double, and boolean.

5: What is the difference between the >> and >>> operators?

Ans: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

6: What are order of precedence and associativity and how are they used?

Ans: Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to-right or right-to-left.

7. What is the % operator?

Ans: It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

8. What restrictions are placed on the values of each case of a switch statement?

Ans: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

9. What is the difference between an if statement and a switch statement?

Ans: The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

10. What is the limitation of switch?

Ans: The only limitation of switch is that we cant have a case which looks like “case i<10”.

11. Can we write a if statement likeif(1)

System.out.println(“Hello”);

Ans: This is supported in C/C++ but not in java because java supports a boolean data type which is having the value true or false.

Experiment - 3

Theory

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.

Page 18: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Java has very flexible three looping mechanisms. You can use one of the following three loops:

while Loop

do...while Loop

for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:The syntax of a while loop is:

while(Boolean_expression){ //Statements}

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

The do...while Loop:A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:The syntax of a do...while loop is:

do{ //Statements}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

The for Loop:A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Page 19: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

A for loop is useful when you know how many times a task is to be repeated.

Syntax:The syntax of a for loop is:

for(initialization; Boolean_expression; update){ //Statements}

Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Java for-each loop:As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:The syntax of enhanced for loop is:

for(declaration : expression){ //Statements}

Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

The break Keyword:The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.

Page 20: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:The syntax of a break is a single statement inside any loop:

break;

The continue Keyword:The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:The syntax of a continue is a single statement inside any loop:

continue;

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

Algorithm

Step1: Import the necessary packagesStep2: Define a classStep3: Define the main() method and throw the exceptionsStep4: Create the BufferedReader objectStep5: Read a number from the keyboardStep6: Initialize flag=1Step7: Initialize divisor=2Step8: Repead while divisor<=n/2

If n%divisor = = 0 Set flag=0 break

Step9: If flag==1 Print “It is prime”Else Print “It is composite”

Input:

1. Valid Input1.1. What will be the output if I typeEnter a number: 35

output:

Page 21: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

1.2. What will be the output if I typeEnter a number: 71

output:

2. Invalid Input2.1. What will be the output if I typeEnter a number: fifty five

output:

2.2. What will be the output if I typeEnter a number: 45.53

output:

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

Algorithm:Step1: Import the packagesStep2: Write a classStep3: Define the main() method and throw the exceptionStep4: Create the BufferedReader objectStep5: Read the number n upto which you want to print the fibonacci seriesSetp6: Declare three variable and initialize them as

a=0, b=1, c=0Step7: Repeat through step-9 while c<=nStep8: Print cStep9: Update the three variables

a = b, b = c, c = a+b

Input:

1. Valid Input1.1. What will be the output if I typeEnter a number upto which you want to print the fibonacci series: 150

output:

1.2. What will be the output if I typeEnter a number upto which you want to print the fibonacci series: 255

output:

Page 22: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

2. Invalid Input2.1. What will be the output if I typeEnter a number upto which you want to print the fibonacci series: -25

output:

2.2. What will be the output if I typeEnter a number upto which you want to print the fibonacci series: fifteen

output:

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

1. What is the difference between a while statement and a do while statement?

Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do whilestatement will always execute the body of a loop at least once.

2. What is the difference between a break statement and a continue statement?

Ans: A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

3. Can we write a for loop likefor( ; ; ){ }

Ans: Yes, it is allowed to write a for loop without its initialization, test and increment/decrement counter.

4. Can we write a while loop likewhile( ){ }

Ans. No, it is not allowed.

5. What is the difference between for and for-each loop

Ans: The for loop can be used for any type of variable as well as for array where as the for-each loop is used for a collection object like array.

Experiment - 4

Theory

Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented

Page 23: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:

Object Class Inheritance Polymorphism Abstraction Encapsulation

ObjectAny entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

ClassCollection of objects is called class. It is a logical entity.

InheritanceWhen one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

PolymorphismWhen one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

AbstractionHiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Page 24: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

EncapsulationBinding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Advantage of OOPs over Procedure-oriented programming language

1)OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.

What is difference between object-oriented programming language and object-based programming language?

Object based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object based programming languages.

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.

Algorithm

Step1: Import the packagesStep2: Create a class RectangleStep3: Declare variables for length and breadthStep4: Define a method to read the data Step5: Define a method to calculate and display the area and perimeterStep6: Define another classStep7: Define the main() method and throw the exceptionStep8: Create the object of the Rectangle class

Page 25: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step9: Call the methods of the Rectangle class

Input:

1. Valid Input1.1. What will be the output if I typeEnter the length and breadth: 2.56 4.57

output:

1.2. What will be the output if I typeEnter the length and breadth: 5.42 6.13

output:

2. Invalid Input2.1. What will be the output if I typeEnter the length and breadth: hello hi

output:

2.2. What will be the output if I typeEnter the length and breadth: five seven

output:

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.

Algorithm

Step1: Import the packagesStep2: Create a class StudentStep3: Declare variables for registration number, name, branch and an array for marksStep4: Define a method to read the data Step5: Define another method to calculate the aggregate and percentage and display the details of

studentStep6: Define another classStep7: Define the main() method and throw the exceptionStep8: Create the object of the Student classStep9: Call the methods of the Student class

Input:

1. Valid Input

Page 26: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

1.1. What will be the output if I typeEnter the regn. no: 2222222222Enter name: Ramesh DasEnter branch: CSEEnter marks in 6 subjects: 75 65 78 89 85 95

output:

1.2. What will be the output if I typeEnter the regn. no: 5555555555Enter name: Sanjay KumarEnter branch: CSEEnter marks in 6 subjects: 87 57 84 98 68 57

output:

2. Invalid Input2.1. What will be the output if I typeEnter the regn. no: my numberEnter name: 9865425365Enter branch: 456Enter marks in 6 subjects: one two three four five

output:

2.2. What will be the output if I typeEnter the regn. no: 4.55Enter name: My NameEnter branch: 855Enter marks in 6 subjects: 52.6 35.6 65.4 51.2 23.4 12.5

output:

Page 27: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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

1. Can a class declared as private be accessed outside it's package?

Ans: Not possible.

2. Can a class be declared as protected?

Ans: The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

3. When will you define a method as static?

Ans: When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

4. What are the restriction imposed on a static method or a static block of code?

Ans: A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

5. I want to print "Hello" even before main() is executed. How will you acheive that?

Ans: Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

6. What is the importance of static variable?

Ans: static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

7. Can we declare a static variable inside a method?

Ans: Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile.

Page 28: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

8. What is the difference between a constructor and a method?

Ans: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.

A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

9. What is the purpose of garbage collection in Java, and when is it used?

Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.

A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

10. What is the default value of an object reference declared as an instance variable?

Ans: The default value will be null unless we define it explicitly.

11. Can a top level class be private or protected?

Ans: No. A top level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.

If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

12. What type of parameter passing does Java support?

Ans: In Java the arguments are always passed by value.

13. Primitive data types are passed by reference or pass by value?

Ans: Primitive data types are passed by value.

14. Objects are passed by value or by reference?

Ans: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

15. What are the different types of method?

Ans: a) Instance Method b) Static Method c) Factory Method

Experiment - 5

Theory

Page 29: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Inheritance in JavaInheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Syntax of Java Inheritance

1. class Subclass-name extends Superclass-name 2. {3. //methods and fields4. }

The extends keyword indicates that you are making a new class that derives from an existing class.

In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Page 30: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

Page 31: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Aggregation in JavaIf a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

class Employee{ int id; String name; Address address;//Address is a class ... }

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?

For Code Reusability.

Simple Example of Aggregation

When use Aggregation?

Code reuse is also best achieved by aggregation when there is no is-a relationship. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime

of the objects involved; otherwise, aggregation is the best choice.

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.

Page 32: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

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.

AlgorithmStep1: Import the packagesStep2: Create a class AccountStep3: Declare variables for customer_name, account_number and type_of_account Step4: Define method for reading data from keyboard.Step5: Define a method for accepting deposit from customer and update the balance.Step6: Define a method for withdrawl and update the balanceStep7: Define another method for displaying the balance.Step8: Derive a class Cur_Acct from AccountStep9: Define a method for check the minimum balance after withdrawl, impose penalty if the balace is less than minimum balance and the balanceStep10: Derive a class Sav_Acct from AccountStep11: Access the super class method to perform various operationStep12: Create another class Step13: Define the main() method and test the program.

Input:

1. Valid Input1.1. What will be the output if I typeEnter the customer name: Rajib ShuklaEnter the account number: 100001Enter the type of account: saving

Enter the account number: 100001Enter the amount to be deposited: 5000

Enter the account number: 100001Enter the withdrawl amount: 2000

Enter the customer name: Deepak HudaEnter the account number: 200001Enter the type of account: currrent

Enter the account number: 200001Enter the amount to be deposited: 50000

Enter the account number: 200001

Page 33: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Enter the withdrawl amount: 47000

output:

1.2. What will be the output if I typeEnter the customer name: Sanjay DasEnter the account number: 100001Enter the type of account: saving

Enter the account number: 100001Enter the amount to be deposited: 15000

Enter the account number: 100001Enter the withdrawl amount: 8000

Enter the customer name: Rounak DasEnter the account number: 200001Enter the type of account: currrent

Enter the account number: 200001Enter the amount to be deposited: 40000

Enter the account number: 200001Enter the withdrawl amount: 25000

output:

2. Invalid Input2.1. What will be the output if I typeEnter the customer name: 120212Enter the account number: SanjibEnter the type of account: my account

Enter the account number: 100001Enter the amount to be deposited: 15000

Enter the account number: 100001Enter the withdrawl amount: 8000

Enter the customer name: 546546Enter the account number: PrateekEnter the type of account: your account

Page 34: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Enter the account number: 200001Enter the amount to be deposited: 40000

Enter the account number: 200001Enter the withdrawl amount: 25000

output:

2.2. What will be the output if I typeEnter the customer name: 100110Enter the account number: BharatEnter the type of account: my account

Enter the account number: 100001Enter the amount to be deposited: 5000

Enter the account number: rameshEnter the withdrawl amount: 3000

Enter the customer name: 789879Enter the account number: SarojEnter the type of account: your account

Enter the account number: deepakEnter the amount to be deposited: -5645

Enter the account number: preetamEnter the withdrawl amount: 152535

output:

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.

AlgorithmStep1: Import the necessary packagesStep2: Create a class Bicycle

Page 35: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step3: Declare variable for cadence, gear and speedStep4: Define a constructor the initialize the data membersStep5: Define a parameterized methods setCadence to set the value of cadence with the value passed through parameterStep6: Define a parameterized methods setGear to set the value of gear with the value passed through parameterStep7: Define a parameterized methods applyBrake to set the value of speed as

speed = speed – givenvalueStep8: Define a parameterized methods speedUp to set the value of speed as

speed = speed + givenvalueStep9: Derive a class MountainBicycle from class BicycleStep10: Declare a variable seatHeightStep11: Define a constructor to initialize the seatHeightStep12: Define a method setHeight to set the seatHeight as

seatHeight = newHeightStep13: Define a new classStep14: Define the main() methodStep15: Create the object of the sub class and test the program.

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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

1: Define Inheritance?

Ans: It is the process where one object acquires the properties of another. With the use of

Page 36: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

inheritance the information is made manageable in a hierarchical order.

2: When super keyword is used?

Ans: If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field

3. What does it mean that a method or class is abstract?

Ans: An abstract class cannot be instantiated. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or it also should be declared abstract.

4. Does a class inherit the constructors of its superclass?

Ans: A class does not inherit constructors from any of its superclasses.

5. What is constructor chaining and how is it achieved in Java ?

Ans: A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.

6. What is an abstract class?

Ans: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie. you may not call its constructor), abstract class may contain static data.

Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

7. What is the difference between an Interface and an Abstract class?

Ans: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.

An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Experiment - 6

Theory

Page 37: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Method Overloading in JavaIf a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Note: In java, Methood Overloading is not possible by changing the return type of the method.

Polymorphism in Java

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in JavaRuntime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Page 38: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

class A{}class B extends A{}

A a=new B();//upcasting

Difference between method overloading and method overriding in javaThere are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of the program.

Method overriding is used to provide the specific implementation of the method that is already provided by its super class.

2) Method overloading is performed within class.Method overriding occurs in two classes that have IS-A (inheritance) relationship.

3) In case of method overloading, parameter must be different.

In case of method overriding, parameter must be same.

4) Method overloading is the example of compile time polymorphism.

Method overriding is the example of run time polymorphism.

5)

In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.

Return type must be same or covariant in method overriding.

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

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packagesStep2: Create a class ShapeStep3: Define a method CalculateArea() with two arguments as length and breadth of a rectangle to calculate the area of a rectangle.Step4: Define another method CalculateArea() with one arguments as radious of a circle to calculate the area of a circle.

Page 39: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step5: Create another classStep6: Define the main() methodStep7: Create the object of the Shape classStep8: Call the methods by passing one and two argument to calculate the area of circle and rectangle.

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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.

Pseudo Code / Algorithm/ Flow ChartStep1: import the packagesStep2: Create a class BankStep3: Define a method getRateOfInterest() that does nothingStep4: Derive a class SBI from class BankStep5: Override the getRateOfInterest to return the rate of interest of SBIStep6: Derive a class ICICI from class BankStep7: Override the getRateOfInterest to return the rate of interest of ICICIStep8: Derive a class AXIS from class BankStep9: Override the getRateOfInterest to return the rate of interest of AXISStep10: Create another classStep11: Define the main() method Step12: Create object of the derived classes and call the method.

Page 40: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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

1: What is Polymorphism?

Ans: Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

2: What is overloading?

Ans: If a class has multiple functions by same name but different parameters, it is known as Method Overloading.

3. What is Overriding?

Ans: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.

When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

4: Difference between Overloading and Overriding?

Page 41: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Ans: Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class parameter must be different in case of overloading, parameter must be same in case of overriding.

5. What restrictions are placed on method overriding?

Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

6. Can we overload main() method?

Ans: Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:

Experiment - 7

Theory

Exception Handling in JavaThe exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

In this page, we will learn about java exception, its type and the difference between checked and unchecked exceptions.

What is exceptionDictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:

1. statement 1; 2. statement 2; 3. statement 3; 4. statement 4; 5. statement 5;//exception occurs

Page 42: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

6. statement 6; 7. statement 7; 8. statement 8; 9. statement 9; 10. statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling in java.

Types of ExceptionThere are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception 2. Unchecked Exception 3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. Int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

1. String s=null;

Page 43: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

2. System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.

1. String s="abc"; 2. int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5]; 2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling KeywordsThere are 5 keywords used in java exception handling.

1. try 2. catch 3. finally 4. throw 5. throws

Synatactical Support (if any)

....

try { statement 1; statement 2; } catch(Exception e) { } ....

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

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packages

Page 44: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step2: Create a class ExStep3: Define the main() method Step4: Read the value of two numbers m and n from command line argumentsStep5: Define the try blockStep6: Perform the division operation within the try blockStep7: Write a catch block with the argument ArithmeticException to handle the exception if it occcursStep8: Write the finally block

Input:

1. Valid Input1.1. What will be the output if I typejava Ex 8 3output:

1.2. What will be the output if I typejava Ex 15 0output:

2. Invalid Input2.1. What will be the output if I typejava Ex 5.3 2.5

output:

2.2. What will be the output if I typejava Ex fifteen ten

output:

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

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packagesStep2: Create a class that inherits the Exception classStep3: Declare an array of accno and an array of balanceStep4: Define a method to display the dataStep5: Define a try block inside the method to process the dataStep6: Check the balance before display it.

If bal<1000.00then throw the exception object

Step7: Define a catch block to handle this exception and display the appropriate messageStep8: Create anothe class Step9: Define the main() method

Page 45: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Step10: Create an object of the user exception class and call the methods

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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

1: What is an Exception?

Ans: An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

2: What do you mean by Checked Exceptions?

Ans: It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

3: Explain Runtime Exceptions?

Ans: It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

4: Which are the two subclasses under Exception class?

Ans: The Exception class has two main subclasses : IOException class and RuntimeException Class.

Page 46: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

5: When throws keyword is used?

Ans: If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature.

6: When throw keyword is used?

Ans: An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.

7: What is Polymorphism?

Ans: Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

8: How finally used under Exception Handling?

Ans: The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

9: What things should be kept in mind while creating your own exceptions in Java?

Ans: While creating your own exception:

a) All exceptions must be a child of Throwable.

b) If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

c)You want to write a runtime exception, you need to extend the RuntimeException class.

10. What are runtime exceptions?

Ans: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

11. What is the difference between error and an exception?

Ans: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.

These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. Example: FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference.

In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

12. How to create custom exceptions?

Ans: Your class should extend class Exception, or some more specific type thereof.

Page 47: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

13. If I want an object of my class to be thrown as an exception object, what should I do?

Ans: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

14. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

Ans: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

15. How does an exception permeate through the code?

Ans: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method.

Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

16. What are the different ways to handle exceptions?

Ans: There are two ways to handle exceptions,

a) By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and

b) List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

17. Is it necessary that each try block must be followed by a catch block?

Ans: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

18. If I write return at the end of the try block, will the finally block still execute?

Ans: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

Experiment - 8

Theory

Page 48: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Multithreading in JavaMultithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:

Process-based Multitasking(Multiprocessing) Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)

Each process have its own address in memory i.e. each process allocates separate memory area.

Process is heavyweight. Cost of communication between the process is high. Switching from one process to another require some time for saving and loading registers,

memory maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)

Threads share the same address space. Thread is lightweight. Cost of communication between the thread is low.

Note: At least one process is required for each thread.What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Page 49: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

Life cycle of a Thread (Thread States)A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3) Running

Page 50: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class 2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

Thread() Thread(String name)

Page 51: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Thread(Runnable r) Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread. 2. public void start(): starts the execution of the thread.JVM calls the run() method on the

thread. 3. public void sleep(long miliseconds): Causes the currently executing thread to sleep

(temporarily cease execution) for the specified number of milliseconds. 4. public void join(): waits for a thread to die. 5. public void join(long miliseconds): waits for a thread to die for the specified

miliseconds. 6. public int getPriority(): returns the priority of the thread. 7. public int setPriority(int priority): changes the priority of the thread. 8. public String getName(): returns the name of the thread. 9. public void setName(String name): changes the name of the thread. 10. public Thread currentThread(): returns the reference of currently executing

thread. 11. public int getId(): returns the id of the thread. 12. public Thread.State getState(): returns the state of the thread. 13. public boolean isAlive(): tests if the thread is alive. 14. public void yield(): causes the currently executing thread object to temporarily

pause and allow other threads to execute. 15. public void suspend(): is used to suspend the thread(depricated). 16. public void resume(): is used to resume the suspended thread(depricated). 17. public void stop(): is used to stop the thread(depricated). 18. public boolean isDaemon(): tests if the thread is a daemon thread. 19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 20. public void interrupt(): interrupts the thread. 21. public boolean isInterrupted(): tests if the thread has been interrupted. 22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:

A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.

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

Page 52: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

threads without deadlock.

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packagesStep2: Create a class BookTicketStep3: Create two objects train and compartment of Object classStep4: Define the public void run() methodStep5: Synchronize the train object and then synchronize the compartment objectStep6: Create a class CancelTicketStep7: Create two objects train and compartment of Object classStep8: Define the public void run() methodStep9: Synchronize the train object and then synchronize the compartment objectStep10: Create another classStep11: Define the main() methodStep12: Create the object of BookTicket and CancelTicketStep13: Create two Thread class object and attach the BookTicket object with one and the CancelTicket object with another.Step14: Run the two threads

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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

Pseudo Code / Algorithm/ Flow Chart

Step1: Import the packagesStep2: Create a class, extend the Applet class and implemets the Runnable interfaceStep3: Declare a Thread variable, three int variable for storing hour, min and sec and a string

Page 53: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

variableStep4: Redefine the init() of Applet class to set the back ground colorStep5: Redefine the start() of Applet class to create a thread object and run the thread.Step6: Implement the public void run() of Runnable interface and do step7 to step11 within run() Step7: Define the try blockStep8: Write a indefinite loopStep9: Create an object of Calendar class Step10: Extract the hour, min and sec from the Calendar class Step11: Convet it again into date format and display it using repaint()Step12: Define the catch block to handle the excpetionStep13: Define the paint() methodStep14: Create the applet code to run the program

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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

1. Describe synchronization in respect to multithreading.

Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.

Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

2. Explain different way of using thread?

Page 54: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Ans: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance, the only interface can help.

3. What is an object's lock and which object's have locks?

Ans: An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

4. What are synchronized methods and synchronized statements?

Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class.

Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

5: What do you mean by Multithreaded program?

Ans: A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

6: What are the two ways in which Thread can be created?

Ans: Thread can be created by: implementing Runnable interface, extending the Thread class.

7: What are the ways in which a thread can enter the waiting state?

Ans: A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

8: How does multi-threading take place on a computer with a single CPU?

Ans: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

9: What invokes a thread's run() method?

Ans: After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Experiment - 9

Theory

Page 55: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

Abstract class in JavaA class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%) 2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

abstract class A{}

Abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

abstract void printStatus();//no body and abstract

Interface in JavaAn interface in java is a blueprint of a class. It has static constants and abstract methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

Page 56: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

It cannot be instantiated just like abstract class.

Why use Java interface?There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction. By interface, we can support the

functionality of multiple inheritance. It can be used to achieve loose coupling.

Note : The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.

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.

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packagesStep2: Create an interface CarStep3: Declare the methods braking() and streering() in the interfaceStep4: Create a class Maruti and implement the interface CarStep5: Define the two methods of CarStep6: Create a class Hyundai and implement the interface CarStep7: Define the two method of CarStep8: Create another class Step9: Define the main() methodStep10: Create the object of Maruti class and Hyundai class and call the methods

Input:

1. Valid Input1.1. What will be the output if I type

output:

Page 57: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

output:

2.2. What will be the output if I type

output:

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 the pass the rate of interest to Interest class to calculate the interest amount on the available balance.

Pseudo Code / Algorithm/ Flow ChartStep1: Import the packagesStep2: Create a class BankAcctStep3: Declare variable for account_number and balanceStep4: Define a constructor to the data members of BankAcct class Step5: Define a method to pass the rate of interest to the inner class, get the interest amount and display it.Step6: Create the inner class InterestStep7: Declare a variable for rate of interest Step8: Define a method to calculate the interest amount on the balanceStep9: Create another class Step10: Define the main()Step11: Create the object of the BankAcct class and call the method.

Input:

1. Valid Input1.1. What will be the output if I type

output:

1.2. What will be the output if I type

output:

2. Invalid Input2.1. What will be the output if I type

Page 58: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

output:

2.2. What will be the output if I type

output:

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

1. What is an Abstract Class and what is it's purpose?

Ans: A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

2. Can a abstract class be declared final?

Ans: Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

3. What is use of a abstract variable?

Ans: Variables can't be declared as abstract. only classes and methods can be declared as abstract.

4. Can you create an object of an abstract class?

Ans: Not possible. Abstract classes can't be instantiated.

5. Can an abstract class be defined without any abstract methods?

Ans: Yes it's possible. This is basically to avoid instance creation of the class.

6. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?

Ans: No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

7. Can a method inside a Interface be declared as final?

Ans: No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

8. Can an Interface implement another Interface?

Ans: Intefaces doesn't provide implementation hence a interface cannot implement another

Page 59: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT:

interface.

9. Can an Interface extend another Interface?

Ans: Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

10. Can a Class extend more than one Class?

Ans: Not possible. A Class can extend only one class but can implement any number of Interfaces.

11. Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?

Ans: Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

12. Can an Interface be final?

Ans: Not possible. Doing so so will result in compilation error.

13. Can a class be defined inside an Interface?

Ans: Yes it's possible.

14. Can an Interface be defined inside a class?

Ans: Yes it's possible.

15. What is a Marker Interface?

Ans: An Interface which doesn't have any declaration inside but still enforces a mechanism.

16. Can we define private and protected modifiers for variables in interfaces?

Ans: No.

17. What modifiers are allowed for methods in an Interface?

Ans: Only public and abstract modifiers are allowed for methods in interfaces.

Page 60: cse.gec.edu.incse.gec.edu.in/wp-content/uploads/2017/03/Java_lab_m…  · Web viewLab Name: Java Programming. Lab Code: PCCS7303. Branch: CSE. Semester: 5th . Syllabus As per BPUT: