KEMBAR78
Unit 1 Notes | PDF | Java Virtual Machine | Method (Computer Programming)
0% found this document useful (0 votes)
29 views95 pages

Unit 1 Notes

The document outlines the syllabus for the Object Oriented Programming course (CS3391) at Dhanalakshmi College of Engineering, covering key topics such as OOP principles, Java programming, inheritance, exception handling, multithreading, and JavaFX. It includes detailed units on various programming paradigms, features of OOP, and comparisons between C, C++, and Java. Additionally, it provides references for textbooks and additional reading materials relevant to the course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views95 pages

Unit 1 Notes

The document outlines the syllabus for the Object Oriented Programming course (CS3391) at Dhanalakshmi College of Engineering, covering key topics such as OOP principles, Java programming, inheritance, exception handling, multithreading, and JavaFX. It includes detailed units on various programming paradigms, features of OOP, and comparisons between C, C++, and Java. Additionally, it provides references for textbooks and additional reading materials relevant to the course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 95

II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

DHANALAKSHMI COLLEGE OF ENGINEERING


CHENNAI
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Subject Name : OBJECT ORIENTED PROGRAMMING


Subject code : CS3391
Regulation : 2021
Year / Branch : II / CSE
Semester : III
SYLLABUS
UNIT I INTRODUCTION TO OOP AND JAVA 9
Overview of OOP – Object oriented programming paradigms – Features of Object Oriented
Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators –
Control Statements – Programming Structures in Java – Defining classes in Java – Constructors-
Methods -Access specifiers - Static members- Java Doc comments
UNIT II INHERITANCE, PACKAGES AND INTERFACES 9
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner Classes.
Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method
Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages and
Member Access –Importing Packages – Interfaces.
UNIT III EXCEPTION HANDLING AND MULTITHREADING 9
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in Exceptions
– User defined Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and
Multiple Threads – Priorities – Synchronization – Inter Thread Communication- Suspending –
Resuming, and Stopping Threads –Multithreading. Wrappers – Auto boxing.
UNIT IV I/O, GENERICS, STRING HANDLING 9
I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic
Programming – Generic classes – Generic Methods – Bounded Types – Restrictions and Limitations.
Strings: Basic String class, methods and String Buffer Class.

Page | 1
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

UNIT V JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS 9


JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls: Checkbox,
ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls – ScrollPane.
Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics – Menu –
Menu bars – MenuItem.
TOTAL: 45 PERIODS
TEXT BOOKS:
T1. Herbert Schildt, “Java: The Complete Reference”, 11 th Edition, McGraw Hill Education, New
Delhi, 2019
T2. Herbert Schildt, “Introducing JavaFX 8 Programming”, 1 st Edition, McGraw Hill Education,
New Delhi, 2015

REFERENCE BOOK:
R1. Cay S. Horstmann, “Core Java Fundamentals”, Volume 1, 11 th Edition, Prentice Hall, 2018.

ADDITIONAL REFERENCE BOOK:


AD1: Anuradha A. Puntambekar “Object Oriented Programming”, 3rd Edition

Page | 2
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

UNIT – I - NOTES
INTRODUCTION TO OOP AND JAVA
Overview of OOP – Object oriented programming paradigms – Features of Object
Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables and
Arrays – Operators – Control Statements – Programming Structures in Java – Defining
classes in Java – Constructors-Methods -Access specifiers - Static members- Java Doc
comments.

OVERVIEW OF OOP
 Object oriented programming is a programming approach in which there is collection of objects.
A. Object-oriented programming aims to implement real-world entities like Object, Class,
Data Abstraction, Data Encapsulation, Inheritance & Polymorphism.
OBJECT ORIENTED PROGRAMMING PARADIGMS
 The word paradigm derives from Greek and Latin word pattern, model or a set of rules that
defines a standard.
 The term paradigm means set of design principles that define a program structure.
1. Procedure oriented Approach - C language
 Represent everything in the form of set of functions.
2. Object oriented Approach - C++ and Java language
 Represent everything in the form of objects.

PROGRAMMING PARADIGM
 The programming paradigm is defined as a set of principles, ideas, design concepts and norms
that defines the manner in which the program code is written and organized.

Types of programming paradigms


1. Imperative paradigm
2. Declarative Paradigm

Page | 3
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

IMPERATIVE PARADIGM
 It is command driven programming.
 This paradigm directs the written code execution as sequence of statements executed one by
one.
 It consists of set of program statements, Each statement directs the computer to perform
specific task. In this style the programmer has to elaborate each statements in details.
 Each statement directs what is to be done and how it is to be done.
 Example: Java, C, C++
1. Structured Programming
 The structured programming intends to optimize the code by using the program control flow,
decision making (IF, IF THEN, ELSE) and the iteration (for, while loops), blocks and functions.
 The main intent of the structured programming is to improve the readability of the code.
 This facilitates the re-usability of the code by dividing the code into semi-independent modules.
 It is also called Modular Programming.

Page | 4
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

2. Procedure oriented Approach


 This paradigm consists of set of procedures which is referred as function, method or
subroutines. Each function performs specific operation.
 The function consists of group of computational steps that directs the computer to perform
specific operation.
 The function once defined can be called many times in the program to repeat the same
operation.

3. Object Oriented Approach


 OOP is type of structured programming that views the program components as object.
 An object binds the data and the associated methods together as single unit.
 The programmer can control the data access permissions by defining the access specifier.
 They robust security features.

Page | 5
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

2. DECLARATIVE PARADIGM
 This paradigm focus on the logic of program and the end result.
 The control flow is not the important element of the program.
 The main focus is achieving the end result. It is called straight forward paradigm.
 The declarative paradigm focuses on what is to be solved.
 Example: HTML, SQL, F#, Prolog, and Lisp.
1. Functional Programming
 As it name suggests, functional programming is mathematical functions.
 It attempts to solve the problem by composing mathematical functions as a program
components.
 The computer program is created with the application and composing the mathematical
functions.
 It is also known as Parallel processing approach.

2. Logic Programming
 This declarative programming paradigm that is based on the logic and control.

Page | 6
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 The term logic means essentially facts and rules. Whereas control means, an order of rules.
 The term algorithm is defined as logic plus control (Logic + Control).
 The logic defines what should be solved and the control defines how it should be solved.
Differentiate between OOP and POP. ND 2022
Procedural Oriented Programming Object-Oriented Programming
In procedural programming, the program is In object-oriented programming, the program is
divided into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-
approach. up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance. data hiding and inheritance is used.
In procedural programming, the function is more In object-oriented programming, data is more
important than the data. important than function.
Procedural programming is based on the unreal Object-oriented programming is based on the real
world. world.
Procedural programming is used for designing Object-oriented programming is used for
Medium-sized programs. Designing large and complex programs.
Procedural programming uses the concept of Object-oriented programming uses the concept of
procedure abstraction. data abstraction.
Code reusability absent in procedural Code reusability present in object-oriented
programming, programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Page | 7
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Difference between C, C++ and Java


C C++ Java
The C language needs to be The C++ is a language that needs The Java is a language that gets
compiled. to be compiled. interpreted and compiled.
The C is platform dependent. C++ is platform dependent. Java is a platform independent.
There is no concept of threading C++ does not support multi-
Java supports multi-threading.
in C. threading programming.
C++ does not have facility to Using Java, one can design very
Using C, the GUI applications
create and implement the interactive and user friendly
cannot be created.
graphical user interface. graphical user interface.
Java code can be embedded
C cannot be embedded in C++ code cannot be embedded in
within a scripting language by
scripting language. any scripting language.
means of Applet programming.
Java has exception handling
C does not have any exception C++ has exception handling
mechanism using try-catch and
handling mechanism. mechanism using try-catch block.
throw.
Java does not support multiple
There is no concept of C++ supports multiple
inheritance however it makes use
inheritance. inheritance.
of interface.
In Java there is no concept of
C uses pointers. In C++ we can use the pointers.
pointers.
Java does not support the
C does not support template. C++ supports templates.
concept of templates.
In C++ we can write a program In Java, there must be at least one
There is no class in C.
without a class. class present.
C++ is simple to use and
C is the most simple. Java is safe and more reliable.
implement.
C can be compiled on variety of C++ can be compiled with variety Java can be compiled using an
compilers. of compilers. unique compiler.

Page | 8
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

FEATURES OF OBJECT ORIENTED PROGRAMMING


OOP
 In object oriented programming approach there is a collection of objects. Each object
consists of data attributes and the methods. This is basically the bottom up approach.OOP has a
complete focus on data and not a procedure.
OOPs:
 Object oriented programming is a programming approach in which there is collection of objects.
 Object-oriented programming aims to implement real-world entities like
A. Object
B. Class
C. Data Abstraction
D. Data Encapsulation
E. Inheritance
F. Polymorphism
A. Objects
 Object is an instance of a class. Objects are basic run-time entities in object oriented
programming and the class variables are called objects.
 Using objects we can access the member variable and member function of a class.
 Object represents a person, place or any item that a program handles.
 A single class can create any number of objects.
 For example - If the class is country then the objects can be India, China, Japan, U.S.A and so on.

Declaring objects -
The syntax for declaring object is -
Class_Name Object_Name;
Example
Fruit fl; // For the class Fruit the object fl can be created.

Page | 9
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

B. Classes
 A class can be defined as an entity in which data and functions are put together.
 A class can be defined as a template/blueprint that describes the behavior/state that the object.
Syntax of class is as given below
class name_of_class
{
private:
Variables declarations;
Function declarations;
public:
Variable declarations;
Function declarations;
}
Example
class rectangle
{
private :
int len, br;
public :
void get_data ( ) ;
void area( );
void print_data( );
}
Class Object
Class is a collection of objects Object is an instance of a class

Class is a conceptual (it is a template) Object is real

Keyword: class Keyword: new


The class cannot be initialized with some property We can assign some property values to the
value. objects.
Various objects having different names can be
A class has unique name.
created for the same class.

Page | 10
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

C. Data Abstraction
 Data abstraction means representing only essential features by hiding all the implementation
details.
Example
class Student
{
int roll;
char name [10];
public;
void input ( );
void display ( );
}
In main function we can access the functionalities using object.
For instance
Student obj;
obj.input ( );
obi.display ( );
Thus only abstract representation can be presented, using class.

D. Encapsulation
 Encapsulation means binding of data and method together in a single entity called class.
 Encapsulation is defined as binding together the data and the functions that manipulate them.

Page | 11
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Data abstraction Data encapsulation


It hiding the code and data into single unit to
It hiding the unwanted data
protect from un authorized access
It solves the problem in design level It solves in implementation level
Data abstraction is represented by using Data encapsulation can be achieved by
abstract classes. inheritance.
E. Inheritance
 Inheritance is a property by which the new classes are created using the old classes.
 In other words the new classes can be developed using some of the properties of old classes.

Inheritance support hierarchical structure.


 The old classes are referred as base classes and the new classes are referred as derived classes.
 That means the derived classes inherit the properties (data and functions) of base class.
Reusability
 Inheritance provides the facility of reusability.
 Reusability means making use of existing class by adding the additional features and
capabilities within it. The existing class need not have to modify.

Page | 12
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

F. Polymorphism
 Polymorphism means many structures. Polymorphism is the ability to take more than one form.
 It exhibiting different behavior in different instances (situations).
Various types of polymorphism
1. Compile time polymorphism - Method overloading
2. Run time polymorphism - Method Overriding

1. Method Overloading
 In Java, it is possible to define two or more methods within the same class that share the same
name. It is also called as static Polymorphism.
 When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded.
Program
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{

Page | 13
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

System.out.println("a: " + a);


}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a * a;
}
}
public class Overload
{
public static void main(String[] args)
{
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
C:\Program Files\Java\jdk-19\bin>java Overload
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

Page | 14
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

/* Method with differing type signatures are overloaded - not overridden. */


class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show(String msg)
{
System.out.println(msg + k);
}
}
public class Overloaded
{
public static void main(String[] args)

Page | 15
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

{
B subOb = new B(1, 2, 3);
subOb.show("This is k: ");
subOb.show();
}
}
C:\Program Files\Java\jdk-19\bin>java Overloaded
This is k: 3
i and j: 1 2

Method Overriding
 It is also known as Dynamic Polymorphism.
 When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
 When an overridden method is called from within its subclass, it will always refer to the version
of that method defined by the subclass. The version of the method defined by the superclass
will be hidden.
 It is a process in which a function call to the overridden method is resolved at Runtime.
Program
/* Method overriding. */
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);

Page | 16
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
System.out.println("k: " + k);
}
}
public class Override
{
public static void main(String[] args) {
B subOb = new B(1, 2, 3);
subOb.show();}
}
C:\Program Files\Java\jdk-19\bin>java Override
k: 3
Inheritance Polymorphism
It is basically applied to classes. It is applied to functions or methods.
Inheritance in which a new class is created
Polymorphism is that which can be defined in
(derived class) that inherit the features from the
multiple forms.
already existing class (Base class)
Various types can be Various types of polymorphism are compile
Single inheritance, multiple inheritance, time (Overload) polymorphism and run time
multilevel inheritance and hybrid inheritance. (Override)

Page | 17
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Advantages OOP
 Using inheritance the redundant code can be eliminated and the existing classes can be used.
 Due to data hiding property, important data can be kept away from unauthorized access.
 It is possible to create multiple objects for a given class.
Disadvantages Of OOP
 The object oriented programming is complex to implement, because every entity in it is an
object.
 We can access the methods and attributes of particular class using the object of that class.
 If some of the members are declared as private then those members are not accessible by the
object of another class.
Applications Of OOP
 Business logic applications
 Real time systems
 Knowledge based and expert systems
 Web based applications
 Simulation and modeling
 Object oriented databases
 Office automation system
 Games programming
Needs of Object Oriented Programming
 Emphasis is on data rather than procedures.
 Programs can be divided into known objects.
 Data needs to be hidden from the outside functions.
 New data needs to be added frequently for maintaining the code.
 Objects need to communicate with each other.

Page | 18
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

JAVA BUZZ WORDS


Java Language is Platform Independent. Justify your Answer. ND 2022
INTRODUCTION
 Java is a general purpose, high-level programming language.
 Java was invented by James Gosling at Sun Microsystems, Inc. in 1991.
 It took 18 months to complete the first working version of Java.
 This language was initially called as Oak but was renamed as Java in 1995.
 Java is purely an object-oriented programming language it supports various features like
Classes, Objects, inheritance and polymorphism.
Java Buzzwords
1. Simple
2. Object oriented
3. Portable
4. Platform independent (Architecture Neutral)
5. Secure
6. Robust
7. Interpreted
8. High Performance
9. Multithreaded
10. Distributed
11. Dynamic
1. Java is simple and small programming language
 Java is very simple programming language. Java was designed to be easy for the professional
programmer to learn and use effectively.
2. Java is known as an object oriented programming language
 Java is a true object oriented language as everything in java is an object. In Java, all the code and
data lies within the classes and object.
3,4. Java is a platform independent and portable programming language
 Platform independence is the most exciting feature of Java program. That means programs in
Java can be executed on variety of platforms.
 This feature is based on the goal - write once, run anywhere, and at anytime forever.

Page | 19
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Java supports portability in 2 ways –


 Java compiler generates the byte code which can be further used to obtain the corresponding
machine code. Secondly the primitive data types used in Java are machine independent.
5,6. Java is robust and secure
Robust
 Java ensures the reliable code. The data types are strictly checked at the compile time as well as
run time in Java.
 Java has a garbage collector which will automatically clean up unused objects and memory.
 The exception handling feature of Java helps the programmer to handle the serious errors
delicately without crashing the overall system.
Secure
 Java program will be first compiled to byte code. This byte code will then be interpreted by Java
Virtual Machine (JVM).

7. Java can be compiled and interpreted


 Java is a highly interpreted language. At runtime java bytecode is interpreted(converted) into
machine code using java interpreter(part of JVM) in order to run the program.
 Java has the feature of just-in-time compilation(happens at runtime) which reduces the
interpretation time.
8. Java is known for its high performance, scalability, monitoring and manageability
 Due to the use of bytecode the Java has high performance. The use of multi-threading also helps
to improve the performance of the Java. The Just-In-Time (JIT) compiler is a component of the
runtime environment that improves the performance of Java™ applications by compiling
bytecodes to native machine code at run time.
 The J2SE(Java standard Edition) helps to increase the scalability in Java.

Page | 20
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 For monitoring and management Java has large number of Application Programming Interfaces
(API). There are tools available for monitoring and tracking the information at the application
level.
9. Java is a multithreaded and interactive language
 Java supports multi-threaded programming which allows a programmer to write such a
program that can perform many tasks simultaneously.
 This allows the programmer to develop the interactive systems.
10. Java is a designed for distributed systems
 This feature is very much useful in networking environment. In Java, two different objects on
different computers can communicate with each other.
 This can be achieved by Remote Method Invocation(RMI). This feature is very much useful in
Client-Server communication.
11. Java is a dynamic and extensible language
 This language is capable of dynamically linking new class libraries, methods and objects.
 Java also supports the functions written in C and C++.
 These functions are called native methods.
12. Java can be developed with ease
 There are various features of Java such as Generics, static import, annotations and so on which
help the Java programmer to create a error free reusable code.

OVER VIEW OF JAVA


THE JAVA ENVIRONMENT
 The Java environment made up of three things-development tools, classes and methods and
java runtime environment.
 The java development tools constitute Java Development Kit (JDK).
 The classes and methods are called Application Programming Interface (API) which forms a
library called Java Standard Library (JSL)
 The java runtime environment is supported by Java Virtual Machine (JVM).

Page | 21
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Byte code
 Bytecode is an intermediate form of Java programs. Bytecode consists of an optimized set of
instructions that are not specific to the processor. Java programs are compiled using the javac
compiler to get bytecode.
 The bytecode is executed using a Java runtime environment which is called a Java Virtual
Machine (JVM). Sometimes JVM is also called an interpreter for bytecode.
 The programs that are running on JVM must be compiled into a binary format which is denoted
by .class files.
 Sometime for ease of distribution multiple class files are packaged into one jar file.
 The JVM executes .class or .jar files, by either interpreting it or using a just-in-time compiler
(JIT) .
 The JIT is used for compiling and not for interpreting the file. It is used in most JVMs today to
achieve greater speed.
 The bytecode verifier verifies all the bytecode before it is executed. This verification helps to
prevent the crashing of the host machine.
Java Program Execution Process

1. Java Development Kit


 The Java Development Kit is nothing but a collection of tools that are used for development and
runtime programs.

Page | 22
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 The Java Development Kit (JDK) is a cross-platformed software development environment that
offers a collection of tools and libraries necessary for developing Java-based software
applications and applets.
 It is a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java
Runtime Environment).
Components Of JDK
1. javac - The Java compiler which translates the source code to the byte code form and stores it
in a separate class file.
2. java - The Java interpreter, which interprets the byte code stored in the class file and executes
the program to generate output.
3 .javadoc - For creating the HTML document for documentation from source code file.
4. javah - It produces header files for the use of native methods.
5. jdb- The Java debuggers which helps to find the errors in the program.
6. appletviewer- For executing the Java applet.
Following are the steps that illustrate execution process of the application program -
1. First, user creates the Java source code using any text editor like Notepad, Notepad++ etc.
2. Next, the source code is compiled using the javac compiler. The javac compiler converts the
source program into a class file which consists of the byte code.
3. The developer can use javadoc tool to create the HTML files that document the source program.
4. The developer may use javah tool for creating the header files.
5. Finally, the java tool is used to interpret the class file generated by javac tool in order to
produce an executable.

Page | 23
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

2. JVM (Java Virtual Machine)


 JVM is a very important component of Java programming language.
 When you run the Java program, the Java compiler first compiles your Java code to byte code.
 Then, the JVM translates byte code into native machine code.

3. JRE(Java Runtime Environment)


 The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other
components to run applets and applications written in the Java programming language.
 JRE doesn’t contain any development tools such as Java compiler, debugger, JShell, etc.

Page | 24
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

DATA TYPES
Outline the primitive data types in java. ND 2023

INTEGERS
byte
 This is in fact smallest integer type of data type.
 Its width is of 8-bits with the range -128 to 127.
 The variable can be declared as byte type as , byte i,j;
short
 This data type is also used for defining the signed numerical variables with a width of 16-bits
and having a range from -32,768 to 32,767.
 The variable can be declared as short as short a,b;

Page | 25
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

int
 This is the most commonly used data type for defining the numerical data.
 The width of this data type is 32-bit having a range 2,147,483,648 to 2,147,483,647.
 The declaration can be int p,q;
long
 Sometimes when int is not sufficient for declaring some data then long is used.
 The range of long is really very long and it is -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. The declaration can be long x, y;
Example:
public class Light
{
public static void main(String[] args)
{
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60;
distance = lightspeed * seconds;
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java Light
In 1000 days light will travel about 16070400000000 miles.

Page | 26
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

FLOAT
float
 To represent the real number (i.e. number that may have decimal point) float data type can be
used.
 The width is 32-bit and range of this data type is 1.4e - 045 to 3.4e+038.
Double
 To represent the real numbers of large range the double data type is used. Its width is 64-bit
having the range 4.9e-324 to 1.8e+308.
Example:
public class Area
{
public static void main(String[] args)
{
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java Area
Area of circle is 366.436224
CHARACTER
char
 This data type is used to represent the character type of data.
 The width of this data type is 16-bit and its range is 0 to 65,536.
Example:
public class CharDemo
{

Page | 27
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

public static void main(String[] args)


{
char ch1, ch2;

ch1 = 88;
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java CharDemo ch1 and ch2: X Y
BOOLEAN
boolean
 Boolean is a simple data type which denotes a value to be either true or false.
Example:
public class BoolTest
{
public static void main(String[] args)
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if (b)
System.out.println("This is executed.");
b = false;
if (b)
System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));

Page | 28
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

}
}
Output:
C:\Program Files\Java\jdk-19\bin>java BoolTest
b is false
b is true
This is executed.
10 > 9 is true

VARIABLES
 The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer.
 In addition, all variables have a scope, which defines their visibility, and a lifetime. The variables
must be declared before its use.
Declaring a variable
The syntax of variable declaration will be –
data_type name_of_variable [=initialization] [,=initialization] [,...];
Example
int a,b,c;
int a=5,b,c=8;
Following are some rules for variable declaration -
 The variable name should not with digits.
 No special character is allowed in identifier except underscore.
 There should not be any blank space with the identifier name.,
 The identifier name should not be a keyword.
 The identifier name should be meaningful.
Dynamic Initialization
 Java allows variables to be initialized dynamically, using any expression valid at the allows
variables to be initialized dynamically.

Page | 29
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Example:
public class DynInit
{
public static void main(String[] args)
{
double a = 3.0, b = 4.0;
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java DynInit
Hypotenuse is 5.0

ARRAYS
 Java array is an object which contains elements of a similar data type.
 Using array the elements that are having the same data type can be grouped together.
 Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
There are two types of arrays:
1. One dimensional array
2. Two dimensional array
1. One Dimensional Array
 It can store one row of values.

The syntax of declaring array is -


data_type var_name[ ];
Instantiating an Array in Java
var_name=new data_type[size];

Page | 30
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Example:
public class Array
{
public static void main(String[] args)
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[10] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java Array
April has 30 days.
2. Two Dimensional Arrays
 The two dimensional arrays are the arrays in which elements are stored in rows as well as in
columns.
The syntax of declaring array is -
data_type array_name[ ][ ];

Page | 31
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Instantiating an Array in Java


array_name=new data_type[row][col];
a=new int[3][3];
Example:
public class TwoDArray
{
public static void main(String[] args)
{
int twoD[][] = new int[4][5];
int i, j, k = 0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
twoD[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java TwoDArray

Page | 32
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

01234
56789
10 11 12 13 14
15 16 17 18 19
OPERATORS
Explain bitwise operator in java that can be applied to the integer type. ND 2023
Type Operator Meaning Example
+ Addition c=a+b
- Subtraction d= -a
Arithmetic * Multiplication c=a*b
/ Division c=a/b
% Mod c=a%b
< Less than a<4
> Greater than b>10
<= Less than equal to b<=10
Relational
>= Greater than equal to a>=5
== Equal to x==100
!= Not equal to m!=8
&& And operator 0&&1
Logical
|| Or operator 0 ||1
Assignment = is assigned to a=5
Increment & ++ Increment by one ++i or i++
Decrement -- Decrement by one -- k or k --
variable = Expression ? expression1 :
Conditional ? x=y?a:b
expression2
& bitwise AND a&a
Bitwise
^ bitwise exclusive XOR a^a
Operator
| bitwise inclusive OR a|a

Page | 33
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

1. ARITHMETIC OPERATOR
 The arithmetic operators are used to perform basic arithmetic operations.
 The operands used for these operators must be of numeric type.
Example:
public class BasicMath
{
public static void main(String[] args)
{
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - da;

Page | 34
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java BasicMath
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
2. RELATIONAL OPERATORS
 The relational operators typically used to denote some condition.
 These operators establish the relation among the operators.
 The <,>, <=,>= are the relational operators.
Example:
class RelationalOperatorsDemo
{
public static void main(String[] args)
{

Page | 35
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

int x = 10;
int y = 30;
System.out.println("x = " +x+ "y = " +y);
System.out.println("x is greater than y: " +(x > y));
System.out.println("x is less than y: " +(x < y));
System.out.println("y is greater than equal x: " +(y >= x));
System.out.println("x is less than equal to y: " +(x <= y));
System.out.println("x is equal to y: " +(x == y));
System.out.println("(x+20 < y+10): " +(x+20 < y+10));
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java RelationalOperatorsDemo
x = 10y = 30
x is greater than y: false
x is less than y: true
y is greater than equal x: true
x is less than equal to y: true
x is equal to y: false
(x+20 < y+10): true
3. LOGICAL OPERATOR
 The logical operators are used to combine two operators.
 These two operands are Boolean operators.
Program
public class LogicalANDExample
{
public static void main(String[] args)
{
int x = 10, y = 5;
boolean result1 = (x == 10 && y == 5);
System.out.println("Result1: " +result1);

Page | 36
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

boolean result2 = (x == 10 && y > x);


System.out.println("Result2: " +result2);
boolean result3 = (x < y && y > x);
System.out.println("Result3: " +result3);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java LogicalANDExample
Result1: true
Result2: false
Result3: false
4. ASSIGNMENT OPERATOR
 ‘=’ Assignment operator is used to assigning a value to any variable.
 It has a right to left associativity.
Example:
public class CompoundTest
{
public static void main(String[] args)
{
int x = 20, y = 30, z = 50;
x += y;
y -= x + z;
z *= x * y;
System.out.println("x = " +x );
System.out.println("y = " +y );
System.out.println("z = " +z );
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java CompoundTest
x = 50

Page | 37
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

y = -70
z = -175000

5. INCREMENT & DECREMENT


 The increment operator increases its operand by one. The decrement
 operator decreases its operand by one. For example, this statement:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
Similarly, this statement:
x = x - 1;
is equivalent to
x--;
Example:
public class IncDec
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

Page | 38
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Output:
C:\Program Files\Java\jdk-19\bin>java IncDec
a=2
b=3
c=4
d=1

6. CONDITIONAL OPERATOR
 The conditional operator is "?"
The syntax of conditional operator is
variable = exp1 ? exp2 : exp3;
Example:
public class Test
{
public static void main(String[] args)
{
int x = 20;
int y = 10;
int z = (x > y) ? x : y;
System.out.println("Greatest number: " +z);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java Test
Greatest number: 20

8. BITWISE OPERATOR
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
Example:
public class BitLogic

Page | 39
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

{
public static void main(String[] args)
{
String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000",
"1001", "1010","1011", "1100", "1101", "1110", "1111" };
int a = 3;
int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java BitLogic
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100

Page | 40
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

CONTROL STATEMENTS
Explain in detail about java iteration statement with an example. Apr 2023
Outline while and do-while statements in java with its general forms. ND 2023
 A programming language uses control statements to control the flow of execution of a program
based on certain conditions.

SELECTION STATEMENT
1. if statement
 If condition is true executes the process, if it is false then it exit the process.
Syntax

Page | 41
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

For example
class IfStatement
{
public static void main(String[] args)
{
int number = 10;
// checks if number is less than 0
if (number < 0)
{
System.out.println("The number is negative.");
}
System.out.println("Statement outside if block");
}
}
Output
Statement outside if block

2. if...else statement

Page | 42
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 If condition is true executes the process 1, if it is false then execute process 2.


Syntax

Example
class Main
{
public static void main(String[] args)
{
int number = 10;
if (number > 0)
{
System.out.println("The number is positive.");
}
else
{

Page | 43
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

System.out.println("The number is not positive.");


}
System.out.println("Statement outside if...else block");
}
}
Output
The number is positive.
Statement outside if...else block

3. Nested if
 Nested if statements mean an if statement inside an if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Write a java program to find the greatest of three numbers. ND 2022

Page | 44
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Program
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println( "i is smaller than 12 too");
}
else
{
System.out.println("i is greater than 15");
}
}
}
Output
i is smaller than 15
i is smaller than 12 too

4. if else if
 The if-else-if statement contains the if-statement followed by multiple else-if statements.
Syntax
if (condition)
statement;
else if (condition)
statement;

Page | 45
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

else
statement;

Program
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output
i is 20

5. Switch statement

Page | 46
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 The switch statement is a multiway branch statement.


Syntax:

Program
class Main
{
public static void main(String[] args)
{
int number = 44;
String Mark;
switch (number)
{
case 29:
Mark = "Low";
break;
case 44:
Mark = "Good";

Page | 47
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

break;
case 48:
Mark = "Excellent";
break;
default:
Mark = "Unknown";
break;
}
System.out.println("Mark: " + Mark);
}
}
Output:
Mark: Good

ITERATION / LOOPING STATEMENT


1. While statement
 Java while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition.
 Java do-while loop is an Entry control loop / Top tested loop.
The syntax is while (condition)

For example

Page | 48
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

class Main
{
public static void main(String[] args)
{
int i = 1, n = 5;
while(i <= n)
{
System.out.println(i);
i++;
}
}
}
Output
1 2 3 4 5

2. do... while statement


 use when we need to repeatedly execute a block of statements.
 Java do-while loop is an Exit control loop / Bottom tested loop.
Syntax

class Main

Page | 49
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

{
public static void main(String[] args)
{
int i = 1, n = 5;
do
{
System.out.println(i);
i++;
} while(i <= n);
}
}
Output
1 2 3 4 5
3. for loop
 When we need to repeatedly execute a block of statements.

 Java for loop provides a concise way of writing the loop structure.

Page | 50
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 The for statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
Program
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}
Output
1 2 3 4 5

For Each
 The Java for-each statement was introduced since Java 5.0 version.
 It provides an approach to traverse through an array or collection in Java.
 The for-each statement also known as enhanced for statement.
 The for-each statement executes the block of statements for each element of the given array or
collection.
 In for-each statement, we can not skip any element of given array or collection.

Page | 51
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Program
public class ForEachTest
{
public static void main(String[] args)
{
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for-each!");
}
}
Output
i=10
i=20
i=30
i=40
i=50
Statement after for-each!
JUMP STATEMENTS

Page | 52
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

BREAK STATEMENTS
 The break statement in java is used to terminate from the loop immediately.
 Whenever a break statement is encountered inside a loop, the control directly comes out of loop
and the loop gets terminated for rest of the iteration.
Syntax :
break;

Program
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
Output:
1234
CONTINUE STATEMENT

Page | 53
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 The continue statement in Java is used to skip the current iteration of a loop.
 The Java continue statement is used to continue the loop.
 It continues the current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.
Syntax:
continue;

public class ContinueExample


{
public static void main(String args[])
{
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.println(j+" ");
}
}
}

Page | 54
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Output
0 1 2 3 5 6.
Sl. No. BREAK CONTINUE

1. The break statement is used to terminate The continue statement is used to skip the
the loop immediately. current iteration of the loop.

2. Break keyword is used to indicate break Continue keyword is used to indicate continue
statements in java programming. statement in java programming.

3. We can use a break with the switch We cannot use a continue with the switch
statement. statement.

4. The break statement terminates the whole The continue statement brings the next iteration
loop early. early.

5.
It stops the execution of the loop. It does not stop the execution of the loop.

PROGRAMMING STRUCTURES IN JAVA


JAVA PROGRAM STRUCTURE

Page | 55
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Documentation section
 The documentation section provides the information about the source program.
 This section contains the information which is not compiled by the Java.
 Everything written in this section is written as comment.
Package section
 It consists of the name of the package by using the keyword package.
 When we use the classes from this package in out program then it is necessary to write the
package statement in the beginning of the program.
Import statement section
 All the required java API can be imported by the import statement.
 There are some core packages present in the java.
 These packages include the classes and method required for java programming.
 These packages can be imported in the program in order to use the classes and methods of the
program.
Class Definition Section
 The class definition section contains the definition of the class.
 This class normally contains the data and the methods manipulating the data.

Page | 56
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Main Method Class


 This is called the main method class because it contains the main() function.
 This class can access the methods defined in other classes.
WRITING JAVA PROGRAM
 Java program can be written using simple text editors like Notepad or WordPad.
 The file name should be same as the name of the class used in the corresponding Java program.
 Note that the name of the program is Firstprog and class name is Firstprog.
 The extension to the file name should be .java.
 Therefore we have saved our first program by the name Firstprog.java.

Java Program [Firstprog.java]

The output of this program can be generated on the command prompt using the commands
javac filename.java
java filename

Page | 57
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

The sample output is as shown below for the program Firstprog.java


D:/>javac Firstprog.java
D:/>java Firstprog
This is my First java program.

FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA


List the symbols used in separators in java and present an outline of the same. ND 2023
Java Tokens
 The smallest individual and logical units of the java statements are called tokens.
These tokens are -
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
1. RESERVED KEYWORDS
 Java has a set of keywords that are reserved words that cannot be used as variables, methods,
classes, or any other identifiers

2. IDENTIFIERS
 Identifiers are the kind of tokens defined by the programmer.
 They are used for naming the classes, methods, objects, variables, interfaces and packages in the
program.

Page | 58
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Following are the rules to be followed for the identifiers-


1. The identifiers can be written using alphabets, digits, underscore and dollar sign.
2. They should not contain any other special character within them
3. There should not be a space within them.
4. The identifier must not start with a digit; it should always start with alphabet.
5. The identifiers are case-sensitive.
6. The identifiers can be of any length.
3. LITERALS
 Literals are the kind of variables that store the sequence of characters for representing the
constant values.
Five types of literals are -
1. Integer literal
 integer literal is a numeric value(associated with numbers) without any fractional or
exponential part.
There are 4 types of integer literals in Java:
binary (base 2)
decimal (base 10)
octal (base 8)
hexadecimal (base 16)
For Example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
2. Floating point literal
 Floating-point literal is a numeric literal that has either a fractional form or an exponential
form.

Page | 59
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

For example:
double myDouble = 3.4
3. Boolean literal
 Boolean literals are used to initialize boolean data types.
 They can store two values: true and false. For example,
boolean flag1 = false;
boolean flag2 = true;
4. Character literal
 Character literals are unicode character enclosed inside single quotes.
For example,
char letter = 'a';
5. String literal
 A string literal is a sequence of characters enclosed inside double-quotes.
For example,
String str1 = "Java Programming";

4. OPERATORS
 Operators are the symbols used in the expression for evaluating them.
5. SEPARATORS
 For dividing the group of code and arranging them systematically certain symbols are used,
which are known as separators.
Following table describes various separators.

CLASSES IN JAVA
 A class is a basic building block. A class is declared by use of the class keyword.

Page | 60
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 Each class is a collection of data and the functions that manipulate the data.
 The data components of the class are called data fields.
 The function components of the class are called member functions or methods.
In general, class declaration includes the following in the order as it appears:
 Modifiers : A class can be public or has default access.
 class keyword : The class keyword is used to create a class.
 Class name : The name must begin with an initial letter (capitalized by convention).
 Superclass (if any) : The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
 Interfaces (if any) : A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than
one interface.
 Body : The class body surrounded by braces, { }.

Syntax for Class


<access specifier> class class_name
{
// member variables
// class methods
}
Syntax for Object
<ClassName> <objectName> = new <ClassName>( );
Example:
class Box
{
double width;
double height;
double depth;
}
public class BoxDemo

Page | 61
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

{
public static void main(String[] args)
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java BoxDemo
Volume is 3000.0
Methods Defined In Class
 Methods are nothing but the functions defined by the particular class.
Syntax:
type name(parameter-list)
{
// body of method
}
There are four parts of the method -
 Return type of the method
 Name of the method
 Parameter passed to the method
 Body of the method
Adding a Method to the Box Class
Example:
class Box
{

Page | 62
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

double width;
double height;
double depth;
void volume()
{
System.out.print("Volume is");
System.out.println(width*height*depth);
}
}
public class BoxDemo3
{
public static void main(String[] args)
{
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java BoxDemo3
Volume is3000.0
Volume is162.0

CONSTRUCTOR

Page | 63
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Explain constructor with an example. ND 2022 what is constructor? Explain with example. Apr
2023
Definition
 Constructor in Java is a special method that is used to initialize objects.
 The constructor is called when an object of a class is created.
 Name of the constructor is same as that of its class name.
 In other words, the name of the constructor and class name is same.
Rules for creating Java constructor
There are two rules defined for the constructor.
 Constructor name must be the same as its class name.
 A Constructor must have no explicit return type.
 A Java constructor cannot be abstract, static, final, and synchronized.
Types of Constructors in Java
1. Default / No-argument constructor: A constructor that has no parameter is known as the
default constructor.
2. Parameterized Constructor: A constructor that has parameters is known as parameterized
constructor.
Syntax
Class Test
{
Test
{
// Body of Constructor
}
}

Example:
class Box
{
double width;
double height;

Page | 64
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

double depth;
Box()
{
System.out.println("Constructiong Box");
width=10;
height=10;
depth=10;
}
double Volume()
{
return width*height*depth;
}
}
public class BoxDemo6
{
public static void main(String[] args)
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.Volume();
System.out.println("Volume is " + vol);
vol = mybox2.Volume();
System.out.println("Volume is " + vol);
}
}
Output
C:\Program Files\Java\jdk-19\bin>java BoxDemo6
Constructiong Box
Constructiong Box
Volume is 1000.0

Page | 65
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Volume is 1000.0
Parameterized Constructor
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}
double Volume()
{
return width*height*depth;
}
}
public class BoxDemo7
{
public static void main(String[] args)
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.Volume();
System.out.println("Volume is " + vol);

vol = mybox2.Volume();
System.out.println("Volume is " + vol);
}

Page | 66
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

}
Output:
C:\Program Files\Java\jdk-19\bin>java BoxDemo7
Volume is 3000.0
Volume is 162.0
Sl. No. Constructor Method
A constructor is used to initialize the state of A method is used to expose the behavior of an
1.
an object. object.
2. It does not having return type. A method must have a return type.
3. The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
The method is not provided by the compiler
4. constructor if you don't have any constructor
in any case.
in a class.
The constructor name must be same as the The method name may or may not be same as
5.
class name. the class name.
ACCESS SPECIFIERS / ACCESS MODIFIERS
 Access modifiers control access to data fields, methods, and classes.
 Access modifiers in Java helps to restrict the scope of a class, constructor, variable, method, or
data member
There are four types of access modifiers available in java
1. Private
2. Default – No keyword required
3. Protected
4. Public
Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
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.

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.

Page | 67
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

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.
outside package outside
Access Modifier within class within package
by subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class Test
{
int a;
public int b;
private int c;
void setc(int i)
{
c = i;
}
int getc()
{
return c;
}
}
public class AccessTest
{
public static void main(String[] args)
{
Test ob = new Test();
ob.a = 10;
ob.b = 20;
// ob.c = 100;
ob.setc(100);

Page | 68
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
Output:
C:\Program Files\Java\jdk-19\bin>java AccessTest
a, b, and c: 10 20 100

STATIC MEMBERS
 When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object.
 You can declare both methods and variables to be static.
 The most common example of a static member is main( ). main( ) is declared as static because it
must be called before any objects exist.

STATIC VARIABLE
 These are declared inside a class using the static keyword
 Static variables initialize themselves to their default value
 The static variable is created only once for the whole class, which does not depend upon the
objects.
The static variable can be declared in java program as follows:
Access_ modifier static variable_name;
Program
public class Student
{
static int id = 20;
public static void main(String[] args)
{
Student s = new Student();
int x = s.id; // Print on the console.
System.out.println(x);

Page | 69
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

System.out.println(Student.id); // Call static variable id using the class name.


}
}
Output:
20
20
STATIC METHOD
 Static functions are defined inside the class with the help of static keyword
 They can only access members of the same class
 They can be used by using the class names and dot operators.
The syntax to call a static method in Java is as follows:
className.methodName(); // Here, className is the name of a class.

Declaration of Static method in Java


Access_modifier static void methodName()
{
// Method body.
}

Page | 70
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

public class StaticTest


{
static int x = 20; // static variable
int y = 30; // instance variable
void display()
{
System.out.println(x);
System.out.println(y);
}
static void show()
{
System.out.println(x);
System.out.println(y); // compile time error because instance variable cannot access
}
public static void main(String[] args)
{
StaticTest st = new StaticTest();
st.display();
show();
}

Page | 71
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

}
Output:
20
30
20

COMMENTS IN JAVA / JAVADOC COMMENTS


 The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
In Java there are three types of comments
1. Single-line comments.
2. Multi-line comments.
3. Documentation comments.

1. Java Single Line Comment


 The single-line comment is used to comment only one line of the code.
 It is the widely used and easiest way of commenting the statements.
 Single line comments starts with two forward slashes (//)
Program
// Java program to show single line comments
class Scomment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}
2. Java Multi Line Comment
 The multi-line comment is used to comment multiple lines of code.
 Multi-line comments are placed between /* and */.

Page | 72
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

Program
//Java program to show multi line comments
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}

3. Java Documentation Comment


 Tags can be used at the end of each Javadoc comment to provide more structured information
about the code being described.
 For example, most Javadoc comments for methods include "@param" and "@return" tags
when applicable, to describe the method's parameters and return value.
 The "@param" tag should be followed by the parameter's name, and then a description of that
parameter.
 The "@return" tag is followed simply by a description of the return value. Examples of these
tags are given below.
Tag Syntax Description
To depict relative path to root directory of generated
{@docRoot} {@docRoot}
document from any page.
@author @author name - text To add the author of the class.
To show the text in code font without interpreting it as
@code {@code text}
html markup or nested javadoc tag.
@version version- To specify "Version" subheading and version-text when
@version
text -version option is used.

Page | 73
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

To add "Since" heading with since text to generated


@since @since release
documentation.
@param parameter- To add a parameter with given name and description to
@param
name description 'Parameters' section.
Required for every method that returns something
@return @return description
(except void)

Write a java program to display the grade of the students by using get() method to get marks
and compute() method to compute the average and display() method to display the grade of the
student. ND 2022
public class CodesCracker
{
public static void main(String[] args)
{
void get()
{
float[] marks = new float[8];
float sum=0, avg;
int i;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Marks Obtained in 8 Subjects: ");
}
for(i=0; i<8; i++)
marks[i] = scan.nextFloat();
for(i=0; i<8; i++)

Page | 74
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

void compute()
{
sum = sum + marks[i];
}
void display()
{
avg = sum/8;
System.out.print("\nGrade = ");
if(avg>=94)
System.out.println("A+");
else if(avg>=90 && avg<94)
System.out.println("A");
else if(avg>=87 && avg<90)
System.out.println("B+");
else if(avg>=83 && avg<87)
System.out.println("B");
else if(avg>=80 && avg<83)
System.out.println("B-");
else if(avg>=77 && avg<80)
System.out.println("C+");
else if(avg>=73 && avg<77)
System.out.println("C");
else if(avg>=70 && avg<73)
System.out.println("C-");
else if(avg>=67 && avg<70)
System.out.println("D+");
else if(avg>=63 && avg<67)
System.out.println("D");
else if(avg>=60 && avg<63)
System.out.println("D-");
else

Page | 75
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

System.out.println("F");
}
}
}
Output:
Enter Marks obtained in 8 subjects: 94
97
92
89
86
98
99
88 Grade = A

Write a java program that accept ‘n’ names, store it in an array, sort the names in alphabetical
order and display the result. Use classes and methods. ND 2023
import java.util.Scanner;
public class Alphabetical_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{

Page | 76
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Output:
$ javac Alphabetical_Order.java
$ java Alphabetical_Order

Enter number of names you want to enter:5


Enter all the names:
bryan
adam
rock

Page | 77
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

chris
scott
Names in Sorted Order:adam,bryan,chris,rock,scott

Write a java program to accept two square matrices, store them in an array, add the matrices
and display the result. Use classes and methods. ND 2023
// Java program to Add two square
// matrices.
import java.io.*;
class addmatrices{
static int N = 4;
static void add(int mat1[][],int mat2[][], int res[][])
{
int i, j, k;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
res[i][j] = 0;
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k]+mat2[k][j];
}
}
}
public static void main(String[] args)
{
int mat1[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
int mat2[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },

Page | 78
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };

int res[][] = new int[N][N];


int i, j;
add(mat1, mat2, res);

System.out.println("Result matrix" + " is ");


for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
System.out.print(res[i][j]+ " ");
System.out.println();
}
}
}
Output
Result matrix is
02 02 02 02
04 04 04 04
06 06 06 06
08 08 08 08

UNIT – I – TWO MARKS

INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object oriented programming paradigms – Features of Object
Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables
and Arrays – Operators – Control Statements – Programming Structures in Java –
Defining classes in Java – Constructors-Methods -Access specifiers - Static members-
Java Doc comments.

Page | 79
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

1. Define Programming Paradigm.


The programming paradigm is defined as a set of principles, ideas, design concepts and norms
that defines the manner in which the program code is written and organized.
Types of programming paradigms
1. Imperative paradigm
2. Declarative Paradigm
2. Define Imperative Paradigm
 They are said to be command driven. This paradigm directs the written code execution
as sequence of statements executed one by one.
 The imperative style program consists of set of program statements.
 Each statement directs the computer to perform specific task. In this style the
programmer has to elaborate each statements in details.
 Each statement directs what is to be done and how it is to be done.
3. Define Structured Programming.
 The structured programming intends to optimize the code by using the program control
flow constructs, decision making (IF, IF THEN, ELSE) constructs and the iteration
constructs (for, while loops), blocks and functions.
 The main intent of the structured programming is to improve the readability of the code.
 This facilitates the re-usability of the code by dividing the code into semi-independent
modules. It is also called Modular Programming.
4. Define Procedure oriented Approach.
 This paradigm consists of set of procedures which is referred as function, method or
subroutines.
 Each function performs specific operation.
 The function consists of group of computational steps that directs the computer to
perform specific operation.
 The function once defined can be called many times in the program to repeat the same
operation.
5. Define Object Oriented Approach.
 OOP is type of structured programming that views the program components as object.
 In OOP programming, all the program components are represented as objects.

Page | 80
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 An object binds the data and the associated methods together as single unit.
 The programmer can control the data access permissions by defining the access specifier.
 They robust security features.
6. Define Declarative Paradigm.
 This paradigm focus on the logic of program and the end result.
 The control flow is not the important element of the program.
 The main focus is achieving the end result. It is called straight forward paradigm.
 The declarative paradigm focuses on what is to be solved.
7. Define Functional Programming
 As it name suggests, functional programming is mathematical functions.
 It attempts to solve the problem by composing mathematical functions as a program
components.
 The computer program is created with the application and composing the mathematical
functions.
 It is also known as Parallel processing approach.
8. Define Logic Programming
 This declarative programming paradigm that is based on the logic and control.
 The term logic means essentially facts and rules. Whereas control means, an order of
rules.
 The term algorithm is defined as logic plus control (Logic + Control).
 The logic defines what should be solved and the control defines how it should be solved.
9. Compare POP and OOP.
Procedural Oriented Programming Object-Oriented Programming
In object-oriented programming, the
In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.
Procedural programming follows a top-down Object-oriented programming follows
approach. a bottom-up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Page | 81
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

10. Difference between C, C++ and Java.

C C++ Java

The C language needs to The C++ is a language that The Java is a language that
be compiled. needs to be compiled. gets interpreted and
The C is platform Java
compiled.is a platform
C++ is platform dependant.
dependant. independent.
There is no concept of C++ does not support multi- Java supports multi-
threading in C. threading programming. threading.
C does not support Java does not support the
C++ supports templates.
template. concept of templates.
In C++ we can write a program In Java, there must be at least
There is no class in C.
without a class. one class present.
11. What is Object Oriented Programming?
 In object oriented programming approach there is a collection of objects.
 Each object consists of data attributes and the methods.
 This is basically the bottom up approach.
 OOP has a complete focus on data and not a procedure.

12. What are the various characteristics of OOP?


 Object
 Class
 Data Abstraction
 Data Encapsulation
 Inheritance
 Polymorphism.
13. Define Objects. What are key characteristics of objects?
 Object is an instance of a class.
 Objects are basic run-time entities in object oriented programming and the class

Page | 82
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

variables are called objects.


 Using objects we can access the member variable and member function of a class.
 Object represents a person, place or any item that a program handles.
 A single class can create any number of objects.
The syntax for declaring object is - Class_Name Object_Name;
Example Fruit fl;
14. Define Class.
 A class can be defined as an entity in which data and functions are put together.
 The concept of class is similar to the concept of structure in C.
Keyword: Class
15. Difference between class and object.
Class Object
Class is a collection of objects Object is an instance of a class
Class is a conceptual (it is a template) Object is real
Keyword: class Keyword: new
The class cannot be initialized with some We can assign some property values to the
property value. objects.

16. Define Data Abstraction.


 Data abstraction means representing only essential features by hiding all the
implementation details.
Example
class Student
{
int roll;
char name [10];
public;
void input ( );

Page | 83
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

void display ( );
}
17. Define Encapsulation.
 Encapsulation means binding of data and method together in a single entity called class.
 Encapsulation is defined as binding together the data and the functions that manipulate
them.
18. What are the benefits of encapsulation? Should abstractions be user centric or developer-
centric?
 Due to encapsulation the corresponding data and the methods get bound, together by
means of class. The data inside the class is accessible by the function in the same class.
 It is normally not accessible from outside component. Thus the unwanted access to the
data can be protected.
 The abstraction should be user centric. While developing the system using the OOP
principles it is important to focus the user and not the developer.
19. Define Inheritance.
 Inheritance is a property by which the new classes are created using the old classes.
 In other words the new classes can be developed using some of the properties of old
classes.
20. Define Polymorphism.
 Polymorphism is the ability to take more than one form.
 It refers to an operation exhibiting different behavior in different instances (situations).
21. Define method overloading.
 In Java, it is possible to define two or more methods within the same class that share the
same name. It is also called as static Polymorphism.
 When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded.
22. Define method overriding.
 It is also known as Dynamic Polymorphism. When a method in a subclass has the same
name and type signature as a method in its superclass, then the method in the subclass is
said to override the method in the superclass.
 When an overridden method is called from within its subclass, it will always refer to the

Page | 84
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden.
 It is a process in which a function call to the overridden method is resolved at Runtime.
23. What are the Advantages of OOPs?
 Using inheritance the redundant code can be eliminated and the existing classes can be
used.
 Due to data hiding property, important data can be kept away from unauthorized access.
 It is possible to create multiple objects for a given class.
24. What are the Disadvantages of OOP?
 The object oriented programming is complex to implement, because every entity in it is
an object.
 We can access the methods and attributes of particular class using the object of that class.
 If some of the members are declared as private then those members are not accessible by
the object of another class.
25. List out the applications of OOPs.
 Business logic applications
 Real time systems
 Knowledge based and expert systems
 Web based applications
 Simulation and modeling
 Object oriented databases
26. What is the need for OOP?
 Emphasis is on data rather than procedures.
 Programs can be divided into known objects.
 Data needs to be hidden from the outside functions.
 New data needs to be added frequently for maintaining the code.
 Objects need to communicate with each other.
27. Define Java language.
 Java is a general purpose, high-level programming language.
 Java was invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridan at Sun Microsystems, Inc. in 1991.

Page | 85
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

 It took 18 months to complete the first working version of Java.


 This language was initially called as Oak but was renamed as Java in 1995.
 Java is purely an object oriented programming language it support various features like
Classes, Objects, inheritance and polymorphism.
28. What are the Buzzwords of Java?
1. Simple
2. Object oriented
3. Portable
4. Platform independent (Architecture Neutral)
5. Secure
6. Robust
7. Interpreted
8. High Performance
9. Multithreaded
10. Distributed
11. Dynamic
29. Discuss the Java Environment.
 The Java environment made up of three things-development tools, classes and methods
and java runtime environment.
 The java development tools constitute Java Development Kit (JDK).
 The classes and methods are called Application Programming Interface (API) which
forms a library called Java Standard Library (JSL)
 The java runtime environment is supported by Java Virtual Machine (JVM).
30. What is byte code? Apr 2023
 Bytecode in Java is a set of instructions for the Java Virtual Machine. Bytecode is a
platform-independent code. Bytecode is a code that lies between low-level language and
high-level language. After the Java code is compiled, the bytecode gets generated, which
can be executed on any machine using JVM.
31. What is Java Virtual Machine?
 JVM is a very important component of Java programming language.
 When you run the Java program, the Java compiler first compiles your Java code to byte

Page | 86
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

code. Then, the JVM translates byte code into native machine code.
32. Define Java Development Kit.
 The Java Development Kit is nothing but a collection of tools that are used for
development and runtime programs.
33. Define JRE.
 The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and
other components to run applets and applications written in the Java programming
language.
34. Define Data types and its types.
 Data type is used to know the type of variable / data.

35. Define Variables.


 A variable is an identifier that denotes the storage location.
 Variable is a fundamental unit of storage in Java.
 The variables are used in combination with identifiers, data types, operators and some
value for initialization.
 The variables must be declared before its use.
36. How dynamic initialization of variables is achieved in java? Nov 2012
 The variables in Java are allowed to get initialized at run time.
 Such type of initialization is called dynamic initialization.
For example double a=5.0; double b=20.0; double c=Math.sqrt((a+b));

Page | 87
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

37. Define static and non static variables? Nov 2010


 A static variable is shared among all instances of class.
 Whereas a non static variable (also called as instance variable) is specific to a single
instance of that class.
38. Define array. ND 2023
 Java array is an object which contains elements of a similar data type.
 Using array the elements that are having the same data type can be grouped together.
 Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
39. Define one Dimensional array.
 Array is a collection of similar type of elements.
 It can store one row of values.
The syntax of declaring array is -
data_type array_name[ ];
40. Define Two Dimensional Arrays. How Multidimensional arrays are implemented in java.
ND 2023
 The two dimensional arrays are the arrays in which elements are stored in rows as well
as in columns.
The syntax of declaring array is -
data_type array_name[ ][ ];
Instantiating an Array in Java
array_name=new data_type[Row][Col];
41. Define Operator.
 Operators are the symbols used in the expression for evaluating them.

Page | 88
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

42. Define Arithmetic Operator.


 The arithmetic operators are used to perform basic arithmetic operations.
 The operands used for these operators must be of numeric type.
 The Boolean operator cannot be used with arithmetic operators.
43. Define Relational Operators.
 The relational operators typically used to denote some condition.
 These operators establish the relation among the operators.
 The <,>, <=,>= are the relational operators.
44. Define control statements.
 A programming language uses control statements to control the flow of execution of a
program based on certain conditions.

45. Define Simple if statement with its syntax.


 If condition is true executes the process, if it is false then it exit the process.

Page | 89
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

46. Define else if statement with syntax.


 If condition is true executes the process 1, if it is false then execute process 2.

47. Define while statement with its syntax.


 Java while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. Java do-while loop is an Entry control loop / Top
tested loop.
48. Define for loop.
 When we need to repeatedly execute a block of statements.
 Java for loop provides a concise way of writing the loop structure.
 The for statement consumes the initialization, condition and increment/decrement in
one line thereby providing a shorter, easy to debug structure of looping.
49. What is the general form of for each version of the for statement? Apr 2023
INCLUDEPICTURE "http://www.btechsmartclass.com/java/java_images/java-for-each-

Page | 90
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

statement-syntax.jpg" \* MERGEFORMATINET

50. Define break and continue statements.


Break
 The break statement in java is used to terminate from the loop immediately.
 Whenever a break statement is encountered inside a loop, the control directly comes out
of loop and the loop gets terminated for rest of the iteration.
Continue
 The continue statement in Java is used to skip the current iteration of a loop.
 The Java continue statement is used to continue the loop.
 It continues the current flow of the program and skips the remaining code at the
specified condition. In case of an inner loop, it continues the inner loop only.
51. Give the structure of java Program.

Page | 91
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

52. How to write a java program?


 Java program can be written using simple text editors like Notepad or WordPad.
 The file name should be same as the name of the class used in the corresponding Java
program.
 Note that the name of the program is Firstprog and class name is Firstprog.
 The extension to the file name should be .java.
 Therefore we have saved our first program by the name Firstprog.java.
53. Define Tokens.
 The smallest individual and logical units of the java statements are called tokens.
 In Java there are five types of tokens used.
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separator
54. What is Identifier?
 Identifiers are the kind of tokens defined by the programmer.
 They are used for naming the classes, methods, objects, variables, interfaces and
packages in the program.
55. Define Literals.
 Literals are the kind of variables that store the sequence of characters for representing
the constant values.
Five types of literals are -
1. Integer literal
2. Floating point literal
3. Boolean literal
4. Character literal
5. String literal

Page | 92
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

56. Mention some of the separators used in Java programming. Dec 2012

57. Define constants.


 Constants mean the fixed values that do not change during the execution of a program.
58. What is class?
 A class is a basic building block. A class is declared by use of the class keyword.
 Each class is a collection of data and the functions that manipulate the data.
 The data components of the class are called data fields.
 The function components of the class are called member functions or methods.
59. How to Defining A Class In Java.
 Java provides a reserved keyword class to define a class. The keyword must be followed
by the class name. Inside the class, we declare methods and variables.
Syntax Class
<access specifier> class class_name
{
// member variables
// class methods
}
60. What are the methods defined in class.
 Methods are nothing but the functions defined by the particular class.
There are four parts of the method -
1. Return type of the method
2. Name of the method
3. Parameter passed to the method
4. Body of the method

Page | 93
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

61. Define constructor.


 Constructor in Java is a special method that is used to initialize objects.
 The constructor is called when an object of a class is created.
 Name of the constructor is same as that of its class name.
 In other words, the name of the constructor and class name is same.
Types of Constructors in Java
1. Default / No-argument constructor: A constructor that has no parameter is known
as the default constructor.
2. Parameterized Constructor: A constructor that has parameters is known as
parameterized constructor.
62. Define Constructor Overloading.
 The constructor overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different
task.
63. What are access specifiers?
 Access modifiers control access to data fields, methods, and classes. Access modifiers in
Java helps to restrict the scope of a class, constructor, variable, method, or data member
There are four types of access modifiers available in java
1. Private
2. Default – No keyword required
3. Protected
4. Public
64. What is Static in Java? Apr 2013
 Static keyword is non access modifier used for methods and attributes.
 Static methods can be accessed without creation an object of a class.
 Static means single copy storage for variables or methods.
 The members that are declared with the static keyword inside a class are called static
members in java.
 We can apply static keyword with variables, methods, blocks and nested classes.
 The static members can be static data member or static method.
 The static members are those members which can be accessed without using object.

Page | 94
II Year / III Semester – CSE CS3391 – OBJECT ORIENTED PROGRAMMING (R-2021)

65. Define Static Members.


Static Variable
 These are declared inside a class using the static keyword
 Static variables initialize themselves to their default value
 The static variable is created only once for the whole class, which does not depend upon
the objects.
Static Method
 Static functions are defined inside the class with the help of static keyword
 They can only access members of the same class
 They can be used by using the class names and dot operators.
66. Define comments in java.
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
In Java there are three types of comments
12. Single-line comments.
13. Multi-line comments.
14. Documentation comments.

67. Differentiate between method and constructor. ND 2022


Constructor Method
Constructor is used to create and initialize an
Method is used to execute certain statements.
Object .
A constructor is invoked implicitly by the A method is to be invoked during program
System. code.
A constructor is invoked when new keyword is
A method is invoked when it is called.
used to create an object.
A constructor can not have any return type. A method can have a return type.
A constructor initializes an object which is not A method can be invoked only on existing
existent. object.

Page | 95

You might also like