Oop I
Oop I
Study Materials
Sr.
Content Page No.
No
1. Syllabus Copy
2. List of Practical
3. List of Assignment
5. Question bank
7. Reference Book
Syllabus Copy
GUJARAT TECHNOLOGICAL UNIVERSITY
Bachelor of Engineering
Subject Code: 3140705
Semester – IV
Subject Name: Object Oriented Programming -I
Type of course: core course
Prerequisite: None
Rationale: Object oriented Programming has become a fundamental part of software development. OOP
facilitates Reuse of code, flexibility, effective problem solving. It provides a modular structure for programs
and implementation details are hidden. Reuse of code lowers the cost of development.
Content:
w.e.f. AY 2018-19
GUJARAT TECHNOLOGICAL UNIVERSITY
Bachelor of Engineering
Subject Code: 3140705
objects and classes, scope of variable and the this reference.
Page 2 of 5
w.e.f. AY 2018-19
GUJARAT TECHNOLOGICAL UNIVERSITY
Bachelor of Engineering
Subject Code: 3140705
Note: This specification table shall be treated as a general guideline for students and teachers. The actual
distribution of marks in the question paper may vary slightly from above table.
Reference Books:
2) Object oriented programming with Java , Rajkumar Buyya,S Thamarai Selvi, Xingchen Chu,
McGrawHill
Course Outcomes:
CO-1 Use various Java constructs, features and libraries for simple problems. 20
CO-2 Demonstrate how to define and use classes, interfaces, create objects and 20
methods, how to override and overload methods, compile and execute
programs.
CO-4 Write a program using Files, binary I/O, collection Frameworks for a 30
given problem.
CO-5 Design and develop GUI based applications in a group using modern 10
tools and frameworks.
List of Experiments:
(1) Write a Program that displays Welcome to Java, Learning Java Now and Programming is fun.
Page 3 of 5
w.e.f. AY 2018-19
GUJARAT TECHNOLOGICAL UNIVERSITY
Bachelor of Engineering
Subject Code: 3140705
Write a program that solves the following equation and displays the value x and y:
(2) 1) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9 (Assume Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )
(3) Write a program that reads a number in meters, converts it to feet, and displays the result.
Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your
(4) weight in kilograms and dividing by the square of your height in meters. Write a program that
prompts the user to enter a weight in pounds and height in inches and displays the BMI.
Note:- 1 pound=.45359237 Kg and 1 inch=.0254 meters.
(5) Write a program that prompts the user to enter three integers and display the integers in decreasing
order.
(6) Write a program that prompts the user to enter a letter and check whether a letter is a vowel or
constant.
(7) Assume a vehicle plate number consists of three uppercase letters followed by four digits. Write a
program to generate a plate number.
(8) Write a program that reads an integer and displays all its smallest factors in increasing order. For
example if input number is 120, the output should be as follows:2,2,2,3,5.
Write a method with following method header.
(9)
public static int gcd(int num1, int num2)
Write a program that prompts the user to enter two integers and compute the gcd of two integers.
(10) Write a test program that prompts the user to enter ten numbers, invoke a method to reverse the
numbers, display the numbers.
(11) Write a program that generate 6*6 two-dimensional matrix, filled with 0’s and 1’s , display the
matrix, check every raw and column have an odd number’s of 1’s.
(12) Write a program that creates a Random object with seed 1000 and displays the first 100 random
integers between 1 and 49 using the NextInt (49) method.
Write a program for calculator to accept an expression as a string in which the operands and
(13)
operator are separated by zero or more spaces.
For ex: 3+4 and 3 + 4 are acceptable expressions.
Write a program that creates an Array List and adds a Loan object , a Date object , a string, and a
(14)
Circle object to the list, and use a loop to display all elements in the list by invoking the object’s to
String() method.
Write the bin2Dec (string binary String) method to convert a binary string into a decimal number.
(15)
Implement the bin2Dec method to throw a NumberFormatException if the string is not a binary
string.
Write a program that prompts the user to enter a decimal number and displays the number in a
(16) fraction.
Hint: Read the decimal number as a string, extract the integer part and fractional part from the
string.
(17) Write a program that displays a tic-tac-toe board. A cell may be X, O, or empty. What to display at
each cell is randomly decided. The X and O are images in the files X.gif and O.gif.
(18) Write a program that moves a circle up, down, left or right using arrow keys.
(19) Write a program that displays the color of a circle as red when the mouse button is pressed and as
blue when the mouse button is released.
Page 4 of 5
w.e.f. AY 2018-19
GUJARAT TECHNOLOGICAL UNIVERSITY
Bachelor of Engineering
Subject Code: 3140705
(20) Write a GUI program that use button to move the message to the left and right and use the radio
button to change the color for the message displayed.
Write a program to create a file name 123.txt, if it does not exist. Append a new data to it if it
(21)
already exist. write 150 integers created randomly into the file using Text I/O. Integers are
separated by space.
(22) Write a recursive method that returns the smallest integer in an array. Write a test program that
prompts the user to enter an integer and display its product.
(23) Write a generic method that returns the minimum elements in a two dimensional array.
(24) Define MYPriorityQueue class that extends Priority Queue to implement the Cloneable interface
and implement the clone() method to clone a priority queue.
(25) Write a program that reads words from a text file and displays all the nonduplicate words in
descending order.The text file is passed as a command-line argument.
Major Equipment:
Computer, Laptop
https://www.tutorialspoint.com/java/
https://www.javatpoint.com/java-programs
Page 5 of 5
w.e.f. AY 2018-19
List of Practical
S. S. AGRAWAL INSTITUTE OF ENGINEERING & TECHNOLOGY, NAVSARI
Sr.
Name of Experiment Remark
No.
1) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9
(Assume Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )
1.3 Write a program that reads a number in meters, converts it to feet, and
displays the result.
1.5 (Sum the digits in an integer) Write a program that reads an integer
between 0 and 1000 and adds all the digits in the integer. For example, if
an integer is 932, the sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to
remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
bmi>30 "Obese"
2.2 Write a program that prompts the user to enter three integers and
display the integers in non-decreasing order.
2.4 Write a program that prompts the user to enter a string and displays the
number of the uppercase letters in the string.
3.1 (Vowel or consonant?) Write a program that prompts the user to enter a
letter and check whether the letter is a vowel or consonant.
3.2 (Process a string) Write a program that prompts the user to enter a string
and displays its length and its first character.
3.4 Write a program that reads an integer and displays all its smallest factors
in increasing order. For example if input number is 120, the output should
be as follows:2,2,2,3,5.
3.5 (Computing gcd) Write a method that returns the gcd of an unspecified
number of integers. The method header is specified as follows:
Write a test program that prompts the user to enter five numbers, invokes
the method to find the gcd of these numbers, and displays the gcd.
3.6 Write a test program that prompts the user to enter ten numbers, invoke
a method to reverse the numbers, display the numbers.
3.7 Write a program that generate 6*6 two-dimensional matrix, filled with
0’s and 1’s , display the matrix, check every raw and column have an odd
number’s of 1’s.
4.1 Write a method with following method header. public static int gcd(int
num1, int num2)
Write a program that prompts the user to enter two integers and compute
the gcd of two integers.
4.2 Write a program that creates three methods. The first finds the maximum
integer, the second finds the maximum double, and the third finds the
maximum among three double values. All three methods are named max.
(Method Overloading)
4.3 (Count the letters in a string) Write a method that counts the number of
letters in a string using the following header:
Write a test program that prompts the user to enter a string and displays the
number of letters in the string.
4.4 (The MyTriangle class) Create a class named MyTriangle that contains
the following two methods:
/** Return true if the sum of any two sides is greater than the third side.
*/
public static double area( double side1, double side2, double side3)
Write a test program that reads three sides for a triangle and computes the
area if the input is valid. Otherwise, it displays that the input is invalid.
4.5 (Use the Random class) Write a program that creates a Random object
with seed 1000 and displays the first 100 random integers between 1 and
49 using the NextInt (49) method.
Draw the UML diagram for the class and then implement the class. Write a
test program that creates one Loan object.
5.3 Design a class named shape that extends three classes Rectangle, Circle
and Triangle. Call the overridden method named draw() through the
reference variable of a superclass. [ Runtime polymorphism or Dynamic
Method Dispatch)
5.4 Write a program that creates an Array List and adds a Loan object , a Date
object , a string, and a Circle object to the list, and use a loop to display all
elements in the list by invoking the object’s to String() method.
7.1 (The Triangle class) Design a class named Triangle that extends
GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default values
1.0 to denote three sides of the triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and
side3.
■ The accessor methods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this
triangle.
■ A method named toString() that returns a string description for the
triangle.
7.3 Write an abstract class named Person and its two subclasses named
Student and Employee.
A person has a name, address, phone number, and email address. A student
has enrollment, course. An employee has an office, salary, and designation.
Define constructors and methods for input and display for both classes.
Write a main program to give demonstration of all.
7.4 (Convert decimals to fractions) Write a program that prompts the user to
enter a decimal number and displays the number in a fraction.
Hint: read the decimal number as a string, extract the integer part and
fractional part from the string, and use the BigInteger implementation of the
Rational class in Programming
8. Write a Java program using JAVAFX basics and Event-driven
programming and animations.
8.1 Write a program that displays a tic-tac-toe board. A cell may be X, O, or
empty. What to display at each cell is randomly decided. The X and O are
images in the files X.gif and O.gif.
8.2 Write a program that moves a circle up, down, left or right using arrow
keys.
8.3 Write a program that displays the color of a circle as red when the mouse
button is pressed and as blue when the mouse button is released.
9. Write a Java program using JAVAFX UI controls and multimedia.
9.1 Write a GUI program that use button to move the message to the left and
right and use the radio button to change the color for the message displayed.
10. Write a Java program using Binary I/O ,Recursion and Generic Class.
10.1 Write a program to create a file name 123.txt, if it does not exist. Append
a new data to it if it already exist. write 150 integers created randomly into
the file using Text I/O. Integers are separated by space.
10.2 Write a recursive method that returns the smallest integer in an array.
Write a test program that prompts the user to enter an integer and display
its product.
10.3 Write a generic method that returns the minimum elements in a two
dimensional array.
11. Write a Java Program using Collections
11.1 Write a program that reads words from a text file and displays all the
nonduplicate words in descending order.The text file is passed as a
command-line argument.
12. Write Java program using Threads
Assignment No: 1
Unit 1 to 4
Date:
Sub
3140705 Title of Subject Object Oriented Programming - I
Code
2. What are syntax errors (compile errors), runtime errors, and logic errors?
9 i) A a = new A();
ii) A a = new B();
iii) B b = new A();
iv) B b = new B();
Page1
S. S. A GRAWAL I NSTITUTE OF E NGINEERING & T ECHNOLOG Y , N AVS ARI
COMPUTER DEPARTMENT
10
Explain static keyword with example.
Date of Submission
Sign of Faculty
Page2
S. S. A GRAWAL I NSTITUTE OF E NGINEERING & T ECHNOLOG Y , N AVS ARI
COMPUTER DEPARTMENT
Assignment No: 2
Unit 5 and 6
Date:
Sub
3140705 Title of Subject Object Oriented Programming - I
Code
Describe abstract class called Shape, which has three subclasses say Triangle, Rectangle,
and Circle. Define one method area() in the abstract class and override this area() in
2.
these three subclasses to calculate for specific object i.e. area() of Triangle subclass
should calculate area of triangle likewise for Rectangle and Circle
3. Explain the words super, static, final and this with the help of an example.
List out different methods available for String class in java and explain any two with
5
proper example
6 What is Dynamic binding? Show with an example how dynamic binding works.
Write a method for computing xy doing repetitive multiplication. X and y are of type
7 integer and are to be given as command line arguments. Raise and handle exception(s)
for invalid values of x and y.
Date of Submission
Sign of Faculty
Page1
S. S. A GRAWAL I NSTITUTE OF E NGINEERING & T ECHNOLOG Y , N AVS ARI
COMPUTER DEPARTMENT
Assignment No: 3
Unit 7 to 12
Date:
Sub
3140705 Title of Subject Object Oriented Programming - I
Code
Write a program to add input elements in ArrayList collection class, then sort the
7 inserted elements in descending order and display the sorted output.
hint: use Collections.reverseOrder()
9
Explain the thread state, thread properties and thread synchronization
10 Explain Thread life cycle in detail. Write a program to create a child thread to print
integer numbers 1 to 10.
Date of Submission
Sign of Faculty
Page1
Last Five-Year Question
Papers
Seat No.: ________ Enrolment No.___________
GUJARAT TECHNOLOGICAL UNIVERSITY
BE - SEMESTER– IV EXAMINATION – SUMMER 2020
Subject Code: 3140705 Date:26/10/2020
Subject Name: Object Oriented Programming -I
Time: 10:30 AM TO 01:00 PM Total Marks: 70
Instructions:
1. Attempt all questions.
2. Make suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
MARKS
Q.1 (a) Explain JRE, JDK and JIT. 03
(b) Explain static keyword with example. 04
(c) Explain inheritance with its types and give suitable example. 07
1
Seat No.: ________ Enrolment No.___________
MARKS
Q.1 (a) Define object oriented concepts. 03
(b) What is the difference between the StringBuffer and StringBuilder 04
classes?
(c) Define constructor. How objects are constructed? Explain constructor 07
overloading with an example.
Q.2 (a) Explain about arrays, Type of arrays and arrays methods. 03
(b) Explain about Encapsulation, Abstraction. 04
(c) State the design hints for class and inheritance. 07
Also discuss the working and meaning of the “static” modifier with
suitable examples.
OR
(c) Explain in detail how inheritance and polymorphism are supported in 07
java with necessary examples.
Q.3 (a) Explain about different types of string methods. 03
(b) Write short notes on access specifiers and modifiers in java. 04
(c) What is an Exception? Explain the exception hierarchy. Explain how 07
to throw, catch and handle Exceptions.
OR
Q.3 (a) Explain about Final class, Fields, Methods. 03
(b) What is a Package? What are the benefits of using packages? Write 04
down the steps in creating a package and using it in a java program
with an example.
(c) Explain the concept of inner classes and explain the types of inner 07
classes with an example program.
Q.4 (a) What is Dynamic binding? Show with an example how dynamic 03
binding works.
(b) Write short notes about I/O stream classes. 04
(c) Explain the thread state, thread properties and thread synchronization. 07
OR
Q.4 (a) Explain the concept of finalization. 03
(b) What is reflection and how does it help to manipulate java code. 04
(c) Write a java program to implement the multiple inheritance concepts 07
for calculating area of circle and square.
Q.5 (a) Explain about callback 03
(b) Explain the interface with an example program. 04
(c) What is Generic programming and why is it needed? Explain with 07
example. List the limitations and restrictions of generic programming
1
OR
Q.5 (a) Explain about Proxy class, Interface and Methods. 03
(b) Explain about adapter classes and mouse events with an example. 04
(c) With a neat diagram explain the Model view controller design pattern 07
and list out the advantages and disadvantages of using it in designing
an application.
*************
2
Seat No.: ________ Enrolment No.___________
*************
2
Seat No.: ________ Enrolment No.___________
Q.1 (a) What is the difference between oop and procedural oriented language? 03
(b) Explain type-conversion in java. 04
(c) Explain class and object with respect to java. 07
*************
1
Seat No.: ________ Enrolment No.___________
MARKS
Q.1 (a) What are syntax errors (compile errors), runtime errors, and logic 03
errors?
(b) What is Type Casting? Explain widening and narrowing type 04
casting.
(c) Explain Data Types in detail with example. 07
1
Q.5 (a) Compare List and Set. 03
(b) Explain static variable and static method with example. 04
(c) Explain Thread Synchronization with example. 07
*************
2
Seat No.: ________ Enrolment No.___________
Q.3 (a) What is the final class? Why they are used? 03
(b) Write exception handling mechanisms in JAVA. 04
(c) Explain Overloading and Overriding with example. 07
OR
Q.3 (a) How can you create packages in Java? 03
(b) What is Inheritance? List out the different forms of Inheritance and 04
explain any one with example.
(c) Explain the words super, static, final and this with the help of an 07
example.
5 What are the data-types and operators available in Java? WINTER 2020 07
What are syntax errors (compile errors), runtime errors, and WINTER 2021 03
7
logic errors?
What is Type Casting? Explain widening and narrowing type WINTER 2021 04
8
casting.
10 List out features of Java. Explain any two features. SUMMER 2022 03
List OOP characteristics and describe inheritance with examples. WINTER 2022 07
2 Explain about arrays, Type of arrays and arrays methods SUMMER 2021 03
2 WINTER 2020 07
Explain class and object with respect to java.
3 WINTER 2020 04
What is constructor overloading?
4 List and explain available type of constructors in java with WINTER 2020 04
example
5 How to access object via reference variable? Explain with WINTER 2020 04
example.
6 Define constructor. How objects are constructed? Explain SUMMER 2021 07
constructor overloading with an example.
What is a Package? What are the benefits of using packages? SUMMER 2021
7
Write down the steps in creating a package and using it in a
java program with an example.
Explain access modifiers with Example. WINTER 2020 03
8 OR
Write short notes on access specifiers and modifiers in java. SUMMER 2021 04
9 WINTER 2021
Explain visibility modifiers. 03
10 WINTER 2021 04
What is constructor? Explain constructor overloading
SUMMER 2022
Consider class A as the parent of class B. Explain among the 04
following which statement will show the compilation error.
11 i) A a = new A();
ii) A a = new B();
iii) B b = new A();
iv) B b = new B();
SUMMER 2022
Explain the following constructors using appropriate 04
example:
12
i) Default constructor and Parameterised constructor
ii) Shallow copy and Deep copy constructor
13 WINTER 2022
Explain constructor with the help of an example 03
WINTER 2022
14 Explain all access modifiers and their visibility as class 07
members.
State the design hints for class and inheritance. SUMMER 2021 07
12 Also discuss the working and meaning of the “static” modifier
with suitable examples.
Explain about different types of string methods. SUMMER 2021 07
OR
13 WINTER 2022 04
List out different methods available for String class in java
and explain any two with proper example
Explain about Final class, Fields, Methods SUMMER 2021 03
14 OR
WINTER 2022 03
What is the final class? Why they are used?
What is Dynamic binding? Show with an example how SUMMER 2021 03
15
dynamic binding works.
16 Explain the concept of finalization. SUMMER 2021 03
1 Define Interface and explain how it differs from the class SUMMER2020 04
07
11 Explain File class with its methods.
Write a JAVA program to read student.txt file and display the SUMMER2020 04
12
content
Write a program that counts the number of words in a text WINTER 2021 07
14 file. The file name is passed as a command line argument. The
words in the file are separated by white space characters.
Write a program that illustrates interface inheritance. WINTER 2021 07
Interface P is extended by P1 and P2. Interface P12 inherits
15 from both P1 and P2. Each interface declares one constant
and one method. class Q implements P12. Instantiate Q and
invoke each of its methods. Each method displays one of the
constants.
What is an Exception? Explain try, catch and finally with WINTER 2021 07
16
example.
What is the keyword “throw” used for? What is the keyword WINTER 2021 03
17
“throws” used for?
Write a java program that evaluates a math expression given SUMMER 2022 07
18 in string
form from command line arguments.
Explain file io using byte stream with appropriate example. SUMMER 2022 07
19
hint: use FileInputStream, FileOutputStream
Explain file io using character stream with appropriate SUMMER 2022 04
20 example.
hint: use FileReader, FileWriter
Explain following Java keywords using appropriate examples: SUMMER 2022 03
21
i) throw, ii) throws, iii) finally
WINTER 2022 04
22 Write exception handling mechanisms in JAVA.
Create a class called Student. Write a student manager program to WINTER 2022 07
23 manipulate the student information from files by using
FileInputStream and FileOutputStream.
Enlist various layout panes and explain any two in detail. SUMMER2020 07
2 OR WINTER 2021 07
List out various layout panes in JavaFX. WINTER 2022 03
3 Write importance of JAVAFX compare to AWT and Swing. SUMMER2020 04
How do you create a Scene object? How do you set a scene SUMMER2020 07
in a stage?
4
Is it possible to create multiple scenes? Write a program to
place a circle in the scene and fill circle with red color.
5 WINTER 2020 03
Explain mouse and key event handler in JavaFX
WINTER 2021 07
4 What is thread? Describe the complete life cycle of thread.
WINTER 2021 07
5 Explain Thread Synchronization with example.
WINTER 2022
SUMMER 2022 04
6 Explain multithreading using Thread class
SUMMER 2022
7 Explain multithreading using Runnable interface
In multi-threading using Thread class, explain with an SUMMER 2022 04
8 example how a start() method call invokes the run method
of the class extending Thread class.
In multi-threads using the Runnable interface, explain with SUMMER 2022 04
9 an example how a start() method calls the run() method of
a class implementing a runnable interface.
Date of Submission
Sign of Faculty
SUMMER2020 03
5 Write difference between String class and StringBuffer class. SUMMER 2021 04
WINTER 2021 03
Explain following keywords WINTER 2020 04
1) Static 2) Super WINTER2022 07
6 OR
Explain the words super, static, final and this with the help of
an example.
Explain abstract class with example. WINTER 2020 03
7 OR
Explain abstract class with example. WINTER 2021 03
Explain about different types of string methods. SUMMER 2021 07
8
OR
WINTER 2022 04
Answers:
Adding new data and functions is not easy. Adding new data and function is easy.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
2) Write a program, which shows an example of function overloading. Also, differentiate between
function overloading and overriding
In method overloading, methods must have In method overriding, methods must have the
the same name and different signatures. same name and same signature.
Static binding is being used for overloaded Dynamic binding is being used for overriding
methods. methods.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
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
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
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.
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
3) Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
2) String is slow and consumes more StringBuffer is fast and consumes less memory
memory when we concatenate too many when we concatenate t strings.
strings because every time it creates new
instance.
3) String class overrides the equals() StringBuffer class doesn't override the equals()
method of Object class. So you can method of Object class.
compare the contents of two strings by
equals() method.
4) String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
6) Explain the words super, static and final with the help of an example.
Static Keyword
It can be applied to nested static class, variables, methods and block.
Example
class GFG {
Final Keyword
It is a keyword.
It is used to apply restrictions on classes, methods and variables.
It can’t be inherited.
It can’t be overridden.
Final methods can’t be inherited by any class.
It is needed to initialize the final variable when it is being declared.
Its value, once declared, can’t be changed or re-initialized.
Example
// Class 1
// Super-class
class P {
// Method 1
// To declare first name
public void firstName()
{
// Method 2
// To declare last name
public final void surName()
{
System.out.println("Trivedi");
}
}
class C extends P {
Super
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
Example
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.
A method which is declared as abstract and does not have implementation is known as an
abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
8) List out different methods available for String class in java and explain any two with
proper example
The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on String
objects such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.
Let's use some important methods of String class.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter
Example
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
9) What is an Exception? Explain the exception hierarchy. Explain how to throw, catch and
handle Exceptions
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
11) Enlist various layout panes and explain any two in detail.
Layouts are the top level container classes that define the UI styles for scene graph objects.
Layout can be seen as the parent node to all the other nodes. JavaFX provides various layout
panes that support different styles of layouts.
In JavaFX, Layout defines the way in which the components are to be seen on the stage. It
basically organizes the scene-graph nodes. We have several built-in layout panes in JavaFX
that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is
represented by a separate class which needs to be instantiated in order to implement that
particular layout pane.
All these classes belong to javafx.scene.layout package. javafx.scene.layout.Pane class
is the base class for all the built-in layout classes in JavaFX.
Layout Classes
javafx.scene.layout Package provides various classes that represents the layouts. The
classes are described in the table below.
Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.
FlowPane Organizes the nodes in the horizontal rows according to the available horizontal
spaces. Wraps the nodes to the next line if the horizontal space is less than the total
width of the nodes
StackPane Organizes nodes in the form of a stack i.e. one onto another
JavaFX BorderPane
BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen. It is
represented by javafx.scene.layout.BorderPane class. This class provides various
methods like setRight(), setLeft(), setCenter(), setBottom() and setTop() which are
used to set the position for the specified nodes. We need to instantiate BorderPane class to
create the BorderPane layout.
The properties of BorderPane class along with their setter methods are given in the table
below.
Node Bottom setBottom() Add the node to the bottom of the screen
Node Centre setCentre() Add the node to the centre of the screen
Node Left setLeft() Add the node to the left of the screen
Node Right setRight() Add the node to the right of the screen
Node Top setTop() Add the node to the top of the screen
Example:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
JavaFX HBox
Example:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
I. Mutual Exclusive
Synchronized method.
Synchronized block.
II. Static synchronization.
Cooperation (Inter-thread communication in java)
Mutual Exclusive
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
TestSynchronization2.java
}
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}