KEMBAR78
Mailam Engineering College Oop-Cs8392 - Unit - I | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
134 views79 pages

Mailam Engineering College Oop-Cs8392 - Unit - I

The document discusses object oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It then provides examples of how these concepts are implemented in Java and defines terms like constructors, methods, access specifiers, packages and garbage collection.
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)
134 views79 pages

Mailam Engineering College Oop-Cs8392 - Unit - I

The document discusses object oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It then provides examples of how these concepts are implemented in Java and defines terms like constructors, methods, access specifiers, packages and garbage collection.
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/ 79

MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 1


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

UNIT I - INTRODUCTION TO OOP AND JAVA FUNDAMENTALS

Object Oriented Programming - Abstraction – objects and classes - Encapsulation- Inheritance - Polymorphism-
OOP in Java – Characteristics of Java – The Java Environment - Java Source File -Structure – Compilation.
Fundamental Programming Structures in Java – Defining classes in Java – constructors, methods -access
specifiers - static members -Comments, Data Types, Variables, Operators, Control Flow, Arrays , Packages -
JavaDoc comments.
Basic Concepts of OOP Definition
Objects
Objects are basic run- time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle. Each object has the data and
code to manipulate the data and theses objects interact with each other.
Class
The entire set of data and code of an object can be made a user-defined data type with the help of a
class. Once a class has been defined, we can create any number of objects belonging to the classes. Classes are
user-defined data types and behave like built- in types of the programming language.
Data Abstraction
Abstraction refers to the act of representing essential features without including the background details
or explanations.
Encapsulation
Wrapping up of data and function within the structure is called as encapsulation.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class. It
supports the concept of hierarchical classification. It provides the idea of reusability. We can add additional
features to an existing class without modifying it by deriving a new class from it.
Polymorphism
Polymorphism a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data used in the operation.
Dynamic binding or late binding
Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic
binding means that the code associated with a given procedure call is not known until the time of the call at the
run-time.
Information Hiding (or Data Hiding)
The insulation of the data from direct access by the program is called data hiding or information hiding.
Abstract class:
Abstract class is one that is not used to create objects. An abstract class is designed only to act as a base
class. It is a design concept in program development and provides a base upon which other classes may be built.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 2


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PART – A
1) What is meant by Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around "objects"
rather than "actions" and data rather than logic. A program has been viewed as a logical procedure that takes
input data, processes it, and produces output data.

2) What is a Class?(Nov/Dec-18)
A class is a collection of objects that have common properties, operations and behaviours. A class is a
combination of state (data) and behaviour (methods).
A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.

3) What is an Object? ?(Nov/Dec-18)


• Object is an instance of a class.
• An object is a location in memory having a value and referenced by an identifier.
• An object can be a variable, function, or data structure.
• It has state, behaviour and identity.

4) What are the key characteristics of objects?


Three properties characterize objects:
o Identity: the property of an object that distinguishes it from other objects
o State: describes the data stored in the object
o Behavior: describes the methods in the object's interface by which the object can be used

5) What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are
defined in their common class. An instance is also called as an object.

6) What are the core OOP’s concepts?


Abstraction, Encapsulation, Inheritance and Polymorphism are the core OOP’s concepts.

7) What is meant by abstraction?


Abstraction refers the act of representing essential features without including background details.

8) What is meant by Encapsulation?


Encapsulation is the process of combining data & functions together into a single entity.

9) What are Inheritance and Polymorphism?


Inheritance is the process by which one object acquires the properties of another object.
Polymorphism is the feature that allows one interface to be used for general class actions.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 3


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

10) What are methods and how are they defined?


Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes. Method definition has
four parts.
They are name of the method, type of object or primitive type the method returns, a list of
parameters and the body of the method. A method’s signature is a combination of the first three parts
mentioned above.

11) What are different types of access modifiers (Access specifiers)?


Access specifiers are keywords that determine the type of access to the member of a class. These
keywords are for allowing privileges to parts of a program such as functions and variables.
o public: Any thing declared as public can be accessed from anywhere.
o private:Any thing declared as private can’t be seen outside of its class.
o protected:Any thing declared as protected can be accessed by classes in the same package and
subclasses in the other packages.
o default modifier :Can be accessed only to classes in the same package.

12) What is an Object and how do you allocate memory to it?


Object is an instance of a class and it is a software unit that combines a structured set of data with a
set of operations for inspecting and manipulating that data. When an object is created using new operator,
memory is allocated to it.

13) Explain the usage of Java packages.


This is a way to organize files when a project consists of multiple modules. It also helps resolve
naming conflicts when different packages have classes with the same names. Packages access level also
allows you to protect data from being used by the non-authorized classes.

14) What is method overloading and method overriding(runtime polymorphism)?


Method overloading: When a method in a class having the same method name with different
arguments is said to be method overloading.
Method overriding: When a method in a class having the same method name with same arguments is
said to be method overriding.

15) What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain byte codes. These byte codes can be run
in any platform and hence java is said to be platform independent.

16) What is a Constructor and Destructor?


• Constructor is a special type of method that can be used to initialize an object.
• Constructor will be automatically invoked when an object is created

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 4


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

• The name of the constructor name is same as the class name.


• Constructor do not have any return type.
• Destructor is a special type of method that frees the state of an object and/or destroys the object
itself. In Java, there is no concept of destructors. Its taken care by the JVM.

17) What is the difference between Constructor and Method?


• Constructor will be automatically invoked when an object is created
• Whereas method has to be called explicitly.

18) What are Static member classes?


Static member class is a static member of a class. Like any other static method, a static member class
has access to all static methods of the parent, or top-level, class.

19) What is Garbage Collection and how to call it explicitly?


When an object is no longer referred to by any variable, java automatically reclaims memory used by
that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

20) In Java, How to make an object completely encapsulated?


All the instance variables should be declared as private and public getter and setter methods should be
provided for accessing the instance variables.

21) What are the functions of a constructor?


• It can be used to initialize the fields.
• It can be used to allocate a memory to the field.

22) What is a default constructor?


Default constructor is ac constructor with no arguments. If no constructor is defined in a class
then a default constructor is automatically provided by the compiler. This constructor is assigned default
values to all fields in class.

23) What is static variable and static method?


• Static variable is a class variable which value remains constant for the entire class.
• Static method is the one which can be called with the class itself and can hold only the static
variable.

24) What is finalize() method?


finalize () method is used just before an object is destroyed and can be called just prior to garbage
collection.

25) What is a package?


A package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 5


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

26) What is the difference between this() and super()?


this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a
super class constructor.

27) Explain working of Java Virtual Machine (JVM)?


JVM is an abstract computing machine like any other real computing machine which first converts
.java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte
codes.
28) What is casting?
Conversion of one type of data to another when appropriate. Casting makes explicitly converting
of data.
29) What is an Abstract Class?
Abstract class is a class that has no instances. An abstract class is written with the expectation that its
concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.
30) What is an Interface?
Interface is an outside view of a class or object which emphaizes its abstraction while hiding its
structure and secrets of its behaviour.
31) What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract
classes, you have to inherit your class from it and Java does not allow multiple inheritances. On the other hand,
you can implement multiple interfaces in your class.

32) What's the difference between constructors and other methods?


Constructors must have the same name as the class and cannot return a value. They are only called once while
regular methods could be called many times.

33) Write the characteristics of java?


• Simple , small and Familiar
• Object oriented
• Distributed
• Robust
• Secure
• Platform independent
• Portable
• Compiled and interpreted
• High performance
• Multithreaded
• Dynamic and interactive.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 6


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

34) How does one import a single package. (April/May-2019)


Import a single package .it can be achieved by
Import packagename . classname
Or
Import packagename.*
Example: Import java.lang.thread;
Import java.lang.*;

35) What is instance variable?


• Instance variables are variables within a class but outside any method. These variables are
instantiated when the class is loaded.
• Instance variables can be accessed from inside any method, constructor or blocks of that particular
class.
36) Write the types of constructors.
• Default constructor
• Parameterized constructor
• Copy constructor
37) What is command line parameters in java?
• A Java application can accept any number of arguments from the command line.
• This allows the user to specify configuration information when the application is launched.
• The user enters command-line arguments when invoking the application and specifies them after the
name of the class to be run.
38) Write the types of variables.
• Local variables . variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed
when the method has completed.
• Instance variables . Instance variables are variables within a class but outside any method. These
variables are instantiated when the class is loaded. Instance variables can be accessed from inside
any method, constructor or blocks of that particular class.
• Class variables . Class variables are variables declared with in a class, outside any method, with the
static keyword.
39) What is Overloaded Constructors?
Constructors can also be overloaded. Since the constructors in a class all have the same name as the
class, their signatures are differentiated by their parameter lists.
40) What are the advantages of using packages?
1. class can be easily reused
2. Two classes in different packages can have same name
3. it provides a way to hide a classes.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 7


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

41) what is meant by array and how will you declare?


The array, which stores a fixed-size sequential collection of variables (or) elements of the
same type.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference.
Syntax:
dataType[] arrayRefVar; //preferred way
(or)
dataType arrayRefVar[]; //works but not preferred way.

42.Define Access Specifier.(Nov/Dec-18) (Nov/Dec-19)


Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods
in Java. These Specifiers determine whether a field or method in a class, can be used or invoked by another
method in another class or sub-class. Access Specifiers can be used to restrict access.

43. Can a java source file be saved using a name other than the class name?(April/May-2019)

Yes, you can save your java source code file with any other name, not same as your main class name but
when you compile it than byte code file name will be same as your main class name. ... And you have compile
and run a class with different name other than the filename, If you don't have any public methods in this class.

44. What are inline function? Give examples. (April/May-2019)

The keyword inline can be used to hint to the compiler to perform inline expansion of the body of a member or
nonmember function. To replace a function call with a copy of the function's code during compilation.

For example it is written something like : When a method is final, it may be inlined.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 8


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PART – B

1.Explain the basic concepts of object oriented programming in detail. (or) . Explain the
characteristics (or) Principles of OOPs.(Nov/Dec-18)(April/May-19)
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Abstract Class

Objects:
Objects are the basic run-time entities in an object oriented programming. They may represent a
person, a place, a bank account or any item that the program has to handle. They may represent user-defined
data such as vectors, time and lists.
Programming problem is analyzed in terms of objects and the nature of communication between them.
Program objects should be chosen such that they match closely with the real world objects.
When a program is executed, the objects interact by sending messages to another. Each object contains
data and code to manipulate the data. Objects can interact without having to know the details of each others
data or code. It is sufficient to know the type of messageaccepted, and the type of message accepted and the
type of response returned by the objects.

Classes:
The entire set of data and code of an object can made a user defined data type with the help of a class. In
fact the objects are variable of the type class. Once class has been defined we can create any number of objects
belonging to that class.
A Class is thus a collection of objects of similar type. For example, mango, apple and orange are
members of the class fruit. Classes are user defined data type and behave like the built-in types of a
programming language.
In short, a class serves as a blueprint or a plan or a template. It specifies what data and what functions
will be included in objects of that class. Defining the class doesn’t create any objects, just as the mere existence
of a type int doesn’t create any variables.

Data Abstraction and Encapsulation:


The wrapping up of data and functions into a single unit is known as encapsulation. It is the most
striking feature of the class. The data is not accessible to the outside world and only those functions which are
wrapped in the class can access it. These functions provide interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding or information
hiding.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 9


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Abstraction represents the act of representing the essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost and functions to operate on these attributes. The attributes are called data
members and functions are called member functions or methods. Since the classes use the concept of
dataabstraction, they are known as Abstract Data Types (ADT).
Inheritance:
Inheritance is the process by which new classes called derived classes are created from existing classes
called base classes. The derived classes have all the features of the base class and the programmer can choose to
add new features specific to the newly created derived class. For example, a programmer can create a base class
named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes has all the
features of the base class with additional attributes or features specific to these newly created derived classes.
Mango would have its own defined features, orange would have its own defined features, banana would have its
own defined features, etc.

It is the process by which objects of one class acquire the properties of objects of another class. It
supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part of the class ‘flying
bird’ which is again a part of the class ‘bird’.
This concept provides the idea of reusability. This means that we can add additional features to an
existing class without modifying it. This is possible by a deriving a new class from an existing one. The new
class will have the combined features of both the classes.
Polymorphism:
It means the ability to take more than one form. An operation may exhibit different behavior in different
instances. The behavior depends upon the types of data used in the operation. For example the operation
addition will generate sum if the operands are numbers whereas if the operands are strings then the operation
would produce a third string by concatenation.
There are two types of polymorphism, they are
1.Compile time polymorphism
2.Runtime polymorphism
i) Compile time polymorphism – The compiler selects the appropriate function for a particular call at the
compile time itself. It can be achieved by function overloading and operator overloading.
ii) Run time Polymorphism - The compiler selects the appropriate function for a particular call at the run
time only. It can be achieved using virtual functions.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 10


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.

A single function name can be used to handle different types of tasks based on the number and types of
arguments. This is known as function overloading.

Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Linking a function call to a function code during compile time is known as static binding. Normal
functions are statically bound.
Linking a function call to a function code during runtime is known as dynamic binding. Virtual
functions are dynamically bound.
Dynamic Binding (also known as late binding) means the code associated with the given procedure call
is not known until the time of the call at run-time. It is associated with the polymorphism and inheritance. A
function call associated with a polymorphic reference depends on the dynamic type of that reference.
Abstract class:
Abstract class is one that is not used to create objects. An abstract class is designed only to act as a base
class. It is a design concept in program development and provides a base upon which other classes may be
built.

2)Describe in detail of java Buzzwords? (or) Explain the features and characteristics of
JAVA.(Nov/Dec-18) (Nov/Dec-19)

CHARACTERISTICS OF JAVA:
Java is guaranteed to be Write Once, Run Anywhere.
 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
 Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever
platform it is being run.
 Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy to master.
 Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
 Architectural-neutral : Java compiler generates an architecture-neutral object file format which makes
the compiled code to be executable on many processors, with the presence of Java runtime system.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 11


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

 Portable: Being architectural-neutral and having no implementation dependent aspects of the


specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability
boundary which is a POSIX subset.
 Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile
time error checking and runtime checking.
 Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many
tasks simultaneously. This design feature allows developers to construct smoothly running interactive
applications.
 Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
light weight process.
 High Performance: With the use of Just-In-Time compilers, Java enables high performance.
 Distributed: Java is designed for the distributed environment of the internet.
 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that can be
used to verify and resolve accesses to objects on run-time.

Discuss about OOP Concepts in Java

OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming. They are an
abstraction, encapsulation, inheritance, and polymorphism. Basically, Java OOP concepts let us create
working methods and variables, then re-use all or part of them without compromising security.

There are four main OOP concepts in Java. These are:

• Abstraction. Abstraction means using simple things to represent complexity. In Java, abstraction means
simple things like objects, classes, and variables represent more complex underlying code and data. This is
important because it lets avoid repeating the same work multiple times.

• Encapsulation. This is the practice of keeping fields within a class private, then providing access to
them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself.
This way, we can re-use objects like code components or variables without allowing open access to the data
system-wide.

• Inheritance. This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes.

• Polymorphism. This Java OOP concept lets programmers use the same word to mean different things in
different contexts. One form of polymorphism in Java is method overloading. That’s when different
meanings are implied by the code itself. The other form is method overriding. That’s when the different
meanings are implied by the values of the supplied variables.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 12


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

3)Describe the Java Environment in detail. (Nov/Dec-19)

JAVA RUNTIME ENVIRONMENT (JRE)

The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development
Kit (JDK), a set of programming tools for developing Java applications. The Java Runtime Environment
provides the minimum requirements for executing a Java application; it consists of the Java Virtual
Machine (JVM), core classes, and supporting files.

JAVA DEVELOPMENT KIT (JDK)


The Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc) and other tools needed in Java
development.
JAVA VIRTUAL MACHINE (JVM)

 A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other
companies.
 An implementation is a computer program that meets the requirements of the JVM specification
 Runtime Instance Whenever you write java command on the command prompt to run the java class,
an instance of JVM is created.

Difference between JDK, JRE and JVM

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 13


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

JDK – Java Development Kit (in short JDK) is Kit which provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) which includes two things
1. Development Tools(to provide an environment to develop your java programs)
2. JRE (to execute your java program).
JRE – Java Runtime Environment (to say JRE) is an installation package which provides environment
to only run(not develop) the java program(or application)onto your machine. JRE is only used by them who
only wants to run the Java Programs i.e. end users of your system.

JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line by line hence it is also known as interpreter.

JRE consists of the following components:


 Deployment technologies, including deployment, Java Web Start and Java Plug-in.
 User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility,
Image I/O, Print Service, Sound, drag and drop (DnD) and input methods.
 Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity
(JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote
Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.
 Other base libraries, including international support, input/output (I/O), extension mechanism, Beans,
Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override
Mechanism, Security, Serialization and Java for XML Processing (XML JAXP).
 Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection,
Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref Objects and
Regular Expressions.
 Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

How does JRE works?


To understand how the JRE works let us consider a Java source file saved as Example.java. The file is
compiled into a set of Byte Code that is stored in a “.class” file. Here it will be “Example.class“.
The following actions occur at runtime.

Class Loader
The Class Loader loads all necessary classes needed for the execution of a program. It provides security
by separating the namespaces of the local file system from that imported through the network. These files are
loaded either from a hard disk, a network or from other sources.

Byte Code Verifier

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 14


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The JVM puts the code through the Byte Code Verifier that checks the format and checks for an illegal
code. Illegal code, for example, is code that violates access rights on objects or violates the implementation of
pointers.

The Byte Code verifier ensures that the code adheres to the JVM specification and does not violate system
integrity.
 Interpreter
o At runtime the Byte Code is loaded, checked and run by the interpreter. The interpreter has the
following two functions:
 Execute the Byte Code
 Make appropriate calls to the underlying hardware

How does JVM works?

JVM becomes an instance of JRE at runtime of a Java program. It is widely known as a runtime
interpreter.JVM largely helps in the abstraction of inner implementation from the programmers who make use
of libraries for their programmes from JDK.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 15


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

4)Explain in detail about Java Source File Structure and Compilation.

A First Simple Program


/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
Entering the Program
For most computer languages, the name of the file that holds the source code to a program is immaterial.
However, this is not the case with Java.
 The first thing that you must learn about Java is that the name you give to a source file is very important.
For this example, the name of the source file should be Example.java.
 In Java, a source file is officially called a compilation unit.
 It is a text file that contains one or more class definitions. The Java compiler requires that a source file
use the .java filename extension.
 As you can see by looking at the program, the name of the class defined by the program is also
Example.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 16


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

 In Java, all code must reside inside a class. By convention, the name of the main class should match the
name of the file that holds the program.

Compiling the Program:

To compile the Example program, execute the compiler, javac, specifying the name of the source file
on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the
program. The Java bytecode is the intermediate representation of your program that contains instructions the
Java Virtual Machine will execute.

To actually run the program, you must use the Java application launcher called java. To
do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:

This is a simple Java program.

When Java source code is compiled, each individual class is put into its own output file named after the
class and using the .class extension. This is why it is a good idea to give your Java source files the same name
as the class they contain—the name of the source file will match the name of the .class file.

When you execute java as just shown, you are actually specifying the name of the class that you want to
execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it
will execute the code contained in the specified class.

A Closer Look at the First Sample Program:

The program begins with the following lines:


/*
This is a simple Java program.
Call this file "Example.java".
*/
This is a comment. Like most other programming languages, Java lets you enter a remarkinto a
program’s source file. The contents of a comment are ignored by the compiler.

The next line of code in the program is shown here:

class Example {

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 17


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

This line uses the keyword class to declare that a new class is being defined. Exampleis an identifier that is the
name of the class. The entire class definition, including all of itsmembers, will be between the opening curly
brace ({) and the closing curly brace (}).

The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
The next line of code is shown here:
public static void main(String args[ ]) {
This line begins the main( ) method. All Java applications begin execution by calling main( ).
 The public keyword is an access modifier, which allows the programmer to control the visibility
of class members.
 When a class member is preceded by public, then that member may be accessed by code outside
the class in which it is declared.
 In this case, main( ) must be declared as public, since it must be called by code outside of its
class when the program is started.

 The keyword static allows main( ) to be called without having to instantiate a particular instance
of the class.
 The keyword void simply tells the compiler that main( ) does not return a value.
 In main( ), there is only one parameter, String args[ ] declares a parameter named args, which
is an array of instances of the classString. Objects of type String store characterstrings. In this
case, args receives any command-line arguments present when the programis executed.
 The last character on the line is the {. This signals the start of main( )’s body. All of thecode that
comprises a method will occur between the method’s opening curly brace and itsclosing curly
brace.
The next line of code is shown here. Notice that it occurs inside main( ).

System.out.println("This is a simple Java program.");

 This line outputs the string "This is a simple Java program." followed by a new line on the screen.
 Output is actually accomplished by the built-in println( ) method. In this case, println( )displays the
string which is passed to it.
 As you will see, println( ) can be used to display other types of information, too. The line begins with
System.out., System is a predefined class that provides access to the system,and out is the output
stream that is connected to the console.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 18


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

 The first } in the program ends main( ), and the last } ends the Example class definition.

5)Explain about java data types with example?

There are two data types available in Java:

 Primitive Data Types and Reference/Object Data Types

Primitive Data Types:

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.

These can be put in four groups:


• Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers.
• Floating-point numbers: This group includes float and double, which represent numbers with fractional
precision.
• Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
• Boolean: This group includes boolean, which is a special type for representing true/false values.

The primitive types represent single values—not complex objects. Because of Java’s portability requirement,
all data types have a strictly defined range. For example, an int is always 32 bits, regardless of the particular
platform.

Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values.
Java does not support unsigned, positive-only integers.

byte:

The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of
type byte are especially useful when you’re working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword.

For example, byte b, c;

short:

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 19


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least used Java type.

For example, short s, t;

int:

The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to
index arrays.

For example, int a, b;

long:

long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the
desired value. The range of a long is quite large.

For example, long x, y;

Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision.

Each of these floating-point types is examined next.


float:
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some
processors and takes half as much space as double precision, but will become imprecise when the values are
either very large or very small.
For example, float hightemp, lowtemp;

double: Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is
actually faster than single precision on some modern processors that have been optimized for high-speed
mathematical calculations.
For example, double pi, r, a;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 20


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Characters:
In Java, the data type used to store characters is char. Java uses Unicode to represent characters. Thus, in Java
char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127.
For example, char ch1, ch2;

Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true
or false.
This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required
by the conditional expressions that govern the control statements such as if and for.
For example,boolean b;

Reference Data Types:


 Reference variables are created using defined constructors of the classes. They are used to access
objects. These variables are declared to be of a specific type that cannot be changed.

For example, Employee, Puppy etc.


 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");

6)Explain in detail about variable and types?

Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals, or characters in these variables.

Declaring a Variable:

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here:
type identifier [ = value][, identifier [= value] ...] ;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 21


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value.

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5;

Dynamic Initialization:
Variables to be initialized dynamically, using any expression valid at the time the variable is declared.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}}

Types of Variable:
Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
Class / static variables:
• Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 22


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

• Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final and static. Constant variables never change from
their initial value.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.

7)Explain in detail about java operators?

Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:

The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean
types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.

The Basic Arithmetic Operators


The basic arithmetic operations—addition, subtraction, multiplication, and division—all behave as you
would expect for all numeric types. The unary minus operator negates its single operand. The unary plus
operator simply returns the value of its operand.

class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
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);

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 23


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

System.out.println("e = " + e);


}
}

The Modulus Operator


The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-
point types as well as integer types.

class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Arithmetic Compound Assignment Operators:
Java provides special operators that can be used to combine an arithmetic operation with an assignment.
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;

This version uses the += compound assignment operator.


There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form

var = var op expression;

Increment and Decrement

The ++ and the – – are Java’s increment and decrement operators.


The increment operator increases its operand by one. The decrement operatordecreases 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--;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 24


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

These operators are unique in that they can appear both in postfix form, where theyfollow the operand as just
shown, and prefix form, where they precede the operand.

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);
}
}

The Bitwise Operators:

Java defines several bitwise operators that can be applied to the integer types, long, int, short,char, and byte.
These operators act upon the individual bits of their operands. They aresummarized in the following table:

All of the integer types are represented by binary numbers of varying bit widths. Forexample, the byte value for
42 in binary is 00101010.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 25


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The Bitwise Logical Operators

The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome ofeach operation. In the
discussion that follows, keep in mind that the bitwise operators are applied to each individual bit within each
operand.

The Bitwise NOT

Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand.
For example, the number 42, which has the following bit pattern:

00101010becomes11010101after the NOT operator is applied.

The Bitwise AND


The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced inall other cases. Here is
an example:
00101010 42
& 00001111 15
00001010 10

The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, thenthe resultant bit is a 1,
as shown here:
00101010 42
| 00001111 15
00101111 47

The Bitwise XOR


The XOR operator, ^, combines bits such that if exactly one operand is 1, then the resultis 1. Otherwise, the
result is zero.
00101010 42
^ 00001111 15

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 26


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

00100101 37

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number oftimes. It has this
general form:value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the<<moves all of the bits
in the specified value to the left by the number of bit positionsspecified by num.

The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a specified number oftimes. Its general
form is shown here:value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>moves all of the bits
in the specified value to the right the number of bit positions specifiedby num.

Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

The outcome of these operations is a boolean value. The relational operators are most frequently used in the
expressions that control the if statement and the various loop statements.

Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands. All of thebinary logical operators
combine two boolean values to form a resultant boolean value.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 27


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The Assignment Operator:

The assignment operator is the single equal sign, =. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression.

The ? Operator

Java includes a special ternary (three-way) operator that can replace certain types of if-then else statements.
This operator is the ?.

The ? has this general form:


expression1 ? expression2 : expression3

 Here, expression1 can be any expression that evaluates to a boolean value.


 If expression1 istrue, then expression2 is evaluated;
 otherwise, expression3 is evaluated.
 The result of the ?operation is that of the expression evaluated.
 Both expression2 and expression3 are requiredto return the same (or compatible) type, which can’t be
void.

Operator Precedence:

8) Explain about control statement?(or) Explain about selection statements.


(April/May-2019)

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 28


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

A programming language uses control statements to cause the flow of execution to advance and branch based
on changes to the state of a program. Java’s program control statements can be put into the following
categories:
 selection
 iteration
 jump.

Selection statements allow your program to choose different paths of execution based upon the outcome of an
expression or the state of a variable. Iteration statements enable program execution to repeat one or more
statements. Jump statements allow your program to execute in a nonlinear fashion.

Java’s Selection Statements


Java supports two selection statements: if and switch. These statements allow you to control the flow of your
program’s execution based upon conditions known only during run time.

The if Statement

Syntax:
if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is executed.

If condition is false, then the statement is bypassed.


Here is an example:
if(num < 100)
System.out.println("num is less than 100");

The if – else Statement


It can be used to route program execution through two different paths.

Syntax:
if (condition) statement1;
else statement2;

The condition is any expression that returns a boolean value. The else clause is optional. If the condition is
true, then statement1 is executed. Otherwise,statement2 is executed. In no case will both statements be
executed.
Here is an example:
if(a < b)
a = 0;
else

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 29


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

b = 0;

The Nested ifs Statement

A nested if is an if statement that is the target of another if or else.

Here is an example:
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)

The if-else-if Ladder Statement


The if statements are executed from the top down. As soon as one of the conditions controlling the if is true,
the statement associated with that if is executed, and the rest ofthe ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed.

Syntax:
if(condition)
statement;
else if(condition)
.
.
.
else
statement;

Here is an example:

class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 30


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.

Switch:

The switch statement is Java’s multiway branch statement. The switch statement works like this: The value of
the expression is compared with each of the values in the case statements.
If a match is found, the code sequence following that case statement is executed. If none of the constants
matches the value of the expression, then the default statement is executed. However, the default statement is
optional.

Syntax:
switch (expression) {
case value1:
// statement sequence
break;
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

Here is an example:

// A simple example of the switch.


class SampleSwitch {

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 31


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

public static void main(String args[]) {


for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}

Iteration Statements
Java’s iteration statements are for, while, and do-while. A loop repeatedly executes the same set ofinstructions
until a termination condition is met.

The for Loop:

Syntax:
for(initialization; condition; iteration) statement;

In its most common form, the initialization portion of the loop sets a loop control variable to an initial value.
The condition is a Boolean expression that tests the loop control variable. If the outcome of that test is true, the
for loop continues to iterate. If it is false, the loop terminates. The iteration expression determines how the loop
control variable is changed each time the loop iterates.

Here is an example:

class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 32


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

}
}

While Loop:

The while loop repeats a statement or block while its controlling expression is true.

Syntax:
while(condition) {
// body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed as longas the conditional
expression is true. When condition becomes false, control passes to thenext line of code immediately following
the loop.

Here is an example:
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Do-While Loop:

If the conditional expression controlling a while loop is initially false, then the body of the loop will not be
executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the
conditional expression is false to begin with.

Syntax:

do {
// body of loop
} while (condition);

Here is an example:

class DoWhile {
public static void main(String args[]) {

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 33


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}

The For-Each Version of the for Loop:


A foreachstyle loop is designed to cycle through a collection of objects, such as an array, in strictly sequential
fashion, from start to finish. The for-each style of for is also referred to as the enhanced for loop.

Syntax:
for(type itr-var : collection) statement-block

Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end. The collection being cycled through is
specified by collection.

Here is an example:
class Foreach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
}}
Jump Statements:
Java supports three jump statements: break, continue, and return. These statements transfer control to another
part of your program.

Break:

In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a
switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of goto.

Using break to Exit a Loop


By using break, you can force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement following the loop.

Here is a simple example:

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 34


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Continue:

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the
loop but stop processing the remainder of the code in its body for this particular iteration.

Here is a simple example:


class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}

return
The return statement is used to explicitly return from a method. That is, it causes program control to transfer
back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch back to the caller of the
method. Thus, the return statement immediately terminates the method in which it is executed.

Here is a simple example:


class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 35


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

9)Explain class and object with example.

Classes in Java
 Class - A class can be defined as a template/blue print that describes the behaviors/states that object of
its type support.
 Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.

The Class Declaration: For example

public class Book


{
//Statements
}

 The first line contains the two Java keywords "public" and "class":
 The public keyword is known as an access modifier. It controls what parts of your Java program can
access your class.
 The class keyword is used to declare that everything within the curly brackets is part of our class
definition. It's also followed directly by the name of the class.

A class can contain any of the following variable types.

 Local variables: Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed when
the method has completed.

 Instance variables: Instance variables are variables within a class but outside any method. These
variables are instantiated when the class is loaded. Instance variables can be accessed from inside any
method, constructor or blocks of that particular class.

 Class variables: Class variables are variables declared with in a class, outside any method, with the
static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 36


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Creating an Object:

A class provides the blueprints for objects. So basically an object is created from a class. In Java, the
new key word is used to create new objects.

There are three steps when creating an object from a class:

 Declaration: A variable declaration with a variable name with an object type.


 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new
object.

An object encapsulates state and behavior.

An object reference provides a handle to an object that is created and stored in memory.

The new operator returns the location of the object which you assign to a reference type.

Example of creating an object is given below:

public class Puppy{


public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is: tommy

Java Objects:
The Object Class is the super class for all classes in Java.

Some of the object class methods are


1.equals()
2.toString()
3.wait()
4.notify()
5.notifyAll()
6.hashcode()
7.clone()

Example:

public class Cube

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 37


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

{
int length = 10;
int breadth = 10;
int height = 10;
public int getVolume()
{
return (length * breadth * height);
}
public static void main(String[] args)
{
Cube cubeObj; // Creates a Cube Reference
cubeObj = new Cube(); // Creates an Object of Cube
System.out.println("Volume of Cube is : " + cubeObj.getVolume());
}
}

10)Explain Arrays In Java its types and example?

Arrays:

The array, which stores a fixed-size sequential collection of variables (or) elements of the same type. Instead of
declaring individual variables, such as
number0, number1, ..., and number99
you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables.

Declaring Array Variables


Syntax:

dataType[] arrayRefVar; //preferred way


or
dataType arrayRefVar[]; //works but not preferred way.
Example:
double[] myList; // preferred way.
Or
double myList[];// works but not preferred way

 you must declare a array variable and type of array the variable can reference.

Note:
 The style dataType[] arrayRefVar is preferred.
 The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to
accommodate C/C++ programmers.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 38


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Creating and initializing size of Arrays:

Syntax:
dataType[] arrayRefVar; // Declaring
arrayRefVar = new dataType[arraySize]; // initializing size

The above statement does two things:


 It creates an array using new dataType[arraySize];

 It assigns the reference of the newly created array to the variable arrayRefVar.

 Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:

Syntax:
dataType[] arrayRefVar =new dataType[arraySize];

Alternatively you can create arrays as follows:


dataType[] arrayRefVar ={value0, value1,..., valuek};

 The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to
arrayRefVar.length-1.

One-Dimensional Arrays:

To create an array, you firstmust create an array variable of the desired type. The general form of a one-
dimensional array declaration is

type var-name[ ];// eg int month_days[];


Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type, and
assigns its reference to myList.:

double[] myList =newdouble[10];

Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 39


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Multidimensional Arrays:

In Java, multidimensional arrays are actually arrays of arrays.To declare a multidimensional array variable,
specify each additional index using another set of square brackets. For example, the following declares a
twodimensional array variable called twoD.

Int[][] twoD = new int[4][5];

Processing Arrays:

When processing array elements often use either for loop or for each loop because all of the elements in an
array are of the same type and the size of the array is known.

Example:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " "); // Print all the array elements
}
double total = 0;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 40


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

for (int i = 0; i < myList.length; i++)


{
total += myList[i]; // Summing all elements
}
System.out.println("Total is " + total);
double max = myList[0];
for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max) max = myList[i]; // Finding the largest element
}
System.out.println("Max is " + max);
}
}

This would produce following result:


1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Passing Arrays to Methods:

For example, the following method displays the elements in an int array:

public static void printArray(int[] array)


{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}

can invoke it by passing an array. For example, the following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:

printArray(newint[]{3,1,2,6,4,2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal
of another array:

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 41


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

public static int[] reverse(int[] list)


{
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--)


{
result[j] = list[i];
}
return result;
}
The foreach Loops: ( brief about foreach and give example? 6mark)

 JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable.

The following code displays all the elements in the array myList:

public class TestArray


{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

for (double element: myList)


{
System.out.println(element); // Print all the array elements
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5

11)Explain constructor and constructor overloading with examples?

A java constructor has the same name as the name of the class to which it belongs.
 Constructor’s syntax does not include a return type, since constructors never return a value.
 Constructors may include parameters of various types.
 When the constructor is invoked using the new operator, the types must match those that are specified in
the constructor definition.
 Java provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.
 The only action taken by the implicit default constructor is to call the super class constructor using the
super () call.
 Constructor arguments provide you with a way to provide parameters for the initialization of an object.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 42


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Below is an example of a cube class containing 2 constructors. (one default and one parameterized
constructor).

public class Cube1


{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;
breadth = 10;
height = 10;
}

Cube1(int l, int b, int h)


{
length = l;
breadth = b;
height = h;
}
public static void main(String[] args)
{
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
Note:
 If a class defines an explicit constructor, it no longer has a default constructor to set the state of the
objects.
 If such a class requires a default constructor, its implementation must be provided.
 Any attempt to call the default constructor will be a compile time error if an explicit default constructor
is not provided in such a case.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 43


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Overloaded Constructors:

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as
the class, their signatures are differentiated by their parameter lists.

 The above example shows that the Cube1 constructor is overloaded one being the default constructor
and the other being a parameterized constructor.
 It is possible to use this() construct, to implement local chaining of constructors in a class.
 The this() call in a constructor invokes the another constructor with the corresponding parameter list
within the same class.
 Calling the default constructor to create a Cube object results in the second and third parameterized
constructors being called as well.
 Java requires that any this() call must occur as the first statement in a constructor.
 Below is an example of a cube class containing 3 constructors which demostrates the this() method in
Constructors context.

Example:
public class Cube2
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}

Cube2()
{
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube2(int l, int b)
{
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having 2 params");
}
Cube2(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having 3 params");
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 44


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

public static void main(String[] args)


{
Cube2 cubeObj1, cubeObj2;
cubeObj1 = new Cube2();
cubeObj2 = new Cube2(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
}
}

12)Write a short notes on method in Java?(Nov/Dec-18)

Methods
Methods are similar to functions or procedures that are available in other programming languages.

Difference between methods and functions


Difference between method and function is method declared inside class, function can be declared any
where inside or outside of the class.

Writing methods in java

If we had to repeatedly output a header such as:


System.out.println("Mailam");
System.out.println("Engineering College");
System.out.println("Tindivanam");
We could put it all in a method like this:
public static void printHeader()
{System.out.println("Mailam");
System.out.println("Engineering College");
System.out.println("Tindivanam");
}
And to call it we simply write: printHeader();

Example:
public class Invoice
{
public static void main(String[] args)
{
printHeader();
System.out.println("You owe us $47.00");
}
public static void printHeader()
{

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 45


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

System.out.println("Mailam");
System.out.println("Engineering College");
System.out.println("Tindivanam");
}
}

Types of methods

There are two types of methods.


Instance methods: are associated with an object and use the instance variables of that object. This is default.

Static methods:
 Static variable is a class variable which value remains constant for the entire class.
 Static method is the one which can be called with the class itself and can hold only the static variable.

← Example:
← class MyUtils
← {
← public static double mean(int[] p)
{ int sum = 0; // sum of all the elements
← for (int i=0; i<p.length; i++)
← {
← sum += p[i];
0 }
return ((double)sum) / p.length;
}//endmethod mean
}
1
Static Methods:
Why declare a method as static
 The above mean() method would work just as well if it wasn't declared static, as long as it was called
from within the same class.
 If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly)
with an object.
 Even when used within the class, there are good reasons to define a method as static
 Similarly, any programmer looking at the code will know that a static method can't interact with instance
variables, which makes reading and debugging easier.

Calling methods :
There are two cases.

1.Called from within the same class


Eg,
//Called from inside the MyUtils class

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 46


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

double avgAtt = mean(attendance);

2.Called from outside of the class

 If a method (static or instance) is called from another class, something must be given before the method
name to specify the class where the method is defined.
 For instance methods, this is the object that the method will access.
 For static methods,
The class name should be specified.

Eg,
double avgAtt = MyUtils.mean(attendance);

If an object is specified before it, the object value will be ignored and the class of the object will be used.

Method overloading:
Methods having same name but different arguments is called method overloading.

Example:
public class Overload2
{
void add(int m, int n)
{
int sum = m + n;
System.out.println( "Sum of a+b is " +sum);
}
void add(int a, int b, int c)
{
int sum = a + b + c;
System.out.println("Sum of a+b+c is " +sum);
}
}
class overloadfunc
{
public static void main(String args[])
{
Overload2 obj = new Overload2();
obj.add(4,19);
obj.add(4,17,11);
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 47


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

13)Explain access specifiers in detail.

Access Specifiers:

Public
It can be accessed from anywhere in the class or packages.
Friendly
It is also known as default, the difference between public and friendly is public can be accessed from any
package whereas friendly is accessed with the packages only.
Protected
It lies between public and friendly, this makes visible all classes and sub classes with in the same package
and also to subclasses in other packages.
Private
It is the highest degree of protection, which is accessible within own class alone.
Default
Java provides a default specifier which is used when no access modifier is present. Any class, field,
method or constructor that has no declared access modifier is accessible only by classes in the same package.
The default modifier is not used for fields and methods within an interface.

Example:

Class Baseclass
{
Public int x=10;
Private int y=10;
Protected int z=10;
int a=10; //Implicit Default Access Modifier

Public int getX()


{
return x;
}
Public void setX(int x)
{
this.x=x;
}
Private int gety()
{
return y;
}
Private void setY(int y)
{
this.y=y;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 48


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

}
Protected int getZ()
{
return z;
}

Protected void setZ(int z)


{
this.z=z;
}
}

14)Describe the static variables and methods used in java :

The static members are,


Static variables
Static methods

Static Variables:

 We use class variables also know as Static fields when we want to share characteristics across all objects
within a class.
 When you declare a field to be static, only a single instance of the associated variable is created common
to all the objects of that class. Hence when one object changes the value of a class variable, it affects all
objects of the class.
 We can access a class variable by using the name of the class, and not necessarily using a reference to an
individual object within the class. Static variables can be accessed even though no objects of that class
exist. It is declared using static keyword.

Static Methods:

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods
are often used to provide global functions for Java programs.

For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods
from inside a static method.

Ex:
Class Cube
{
int length=10;
int breadth=10;
int height=10;
public static int numOfCubes=0;//static variable

public static int getNoOfCubes() //static method


{
Return numOfCubes;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 49


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Public Cube()
{
numOfCubes++;
}
}
Public class CubeStaticTest
{
Public static void main(String args[])
{
System.out.println(“number of cube objects=”+Cube.numOfCubes);

System.out.println(“number of cube objects=”+ Cube.getNoOfCubes());


}
}

15)What is package? How to add a class into a package? Give example.

Packages is a way of grouping a variety of classes and/or interfaces together.

Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating
and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations )
providing access protection and name space management.
Some of the existing packages in Java are:

 java.lang - bundles the fundamental classes


 java.io - classes for input , output functions are bundled in this package

We may like to use many of the classes contained in a package. It can be achieved by

Import packagename . classname


Or
Import packagename.*

Creating the package

package firstpackage;// package declaration


public class FirstClass //class definition
{…..
(body of class)
…….
}
The file is saved as FirstClass.java,located at firstpackage directory. When it is compiled .class file will be

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 50


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

created in same directory.

Access a package :

The import statement can be used to search a list of packages for a particular class.

The general form of import statement for searching class is a as follows.


Import package1 [.package2] [.package3].classname;

Using the package :

package package1 ;
public class classA
{
public void displayA()
{
System.out.println(“class A”);
}
}

Example:

An example that creates a package called animals. It is common practice to use lowercased names of packages
to avoid any conflicts with the names of classes, interfaces.

Put an interface in the package animals:

/* File name : Animal.java */


package animals;

interface Animal
{
public void eat();
public void travel();
}
Now put an implementation in the same package animals:
package animals;

/* File name : MammalInt.java */

public class MammalInt implements Animal


{

public void eat()


{
System.out.println("Mammal eats");
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 51


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

public void travel()


{
System.out.println("Mammal travels");
}

public int noOfLegs()


{
return0;
}

public static void main(String args[])


{
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}

16)Explain The Javadoc Comments. (Nov/Dec-19)

Commenting in Java can take two forms,

1. Single line comments


2. Multiline comments

Then there are Javadoc comments that are unique to the Java language.

The Need for Comments


There are a number of reasons for including comments in source code. Some of the reasons for using comments
are:
 Often comments are added at the start of each source file to give a description of what source the file
contains and copyright information.
 The fields and methods of a class are often given brief comments that describe their purpose and what
they do.
 Complex code is often commented heavily to make it clearer and easier to understand.

Comments in Java
Single Line Comments
 Single line comments are used to add a very brief comment within some code, often a long or
complex method.
 They begin with a double forward slash (//) and end with the end of line or carriage return.
EX:
private static String name = "Guys"; //The name to print

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 52


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

Multi Line Comments


 If a comment is going to span across more than one line then a multi-line comment should be
used.
 These are often useful for providing more in-depth information.
 They start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by
a forward slash (*/).
EX:
/* Getter method provides public access in read only fashion.
This function returns the port number. */
int getPort() { ... }

Javadoc Comments:
 Javadoc Comments are specific to the Java language and provide a means for a programmer to fully
document his / her source code as well as providing a means to generate an Application Programmer
Interface (API) for the code using the javadoc tool that is bundled with the JDK.
 These comments have a special format which we will discuss in this section and then in the following
section we will look at how to use the javadoc tool to generate an API.

The Format of Javadoc Comments

 A Javadoc comment precedes any class, interface, method or field declaration and is similar to a multi-
line comment except that it starts with a forward slash followed by two atserisks (/**).
 The basic format is a description followed by any number of predefined tags.
 The entrie comment is indented to align with the source code directly beneath it and it may contain any
valid HTML.
 Generally paragraphs should be separated or designated with the <p> tag.

EXample:
/**
* A Container is an object that contains other objects.
* @author Trevor Miller
* @version 1.2
* @since 0.3
*/
public abstract class Container
{
/**
* Create an empty container.
*/
protected Container() { }

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 53


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

/**
* Return the number of elements contained in this container.
* @return The number of objects contained
*/
public abstract int count();

/**
* Clear all elements from this container.
* This removes all contained objects.
*/
public abstract void clear();
/**
* Accept the given visitor to visit all objects contained.
* @param visitor The visitor to accept
*/
public abstract void accept(final Visitor visitor);
/**
* Return an iterator over all objects conatined.
* @return An iterator over all objects
*/
public abstract Iterator iterator();
/**
* Determine whether this container is empty or not.
* @return <CODE>true</CODE> if the container is empty:
* <CODE>count == 0</CODE>, <CODE>false</CODE>
* otherwise
*/
public boolean isEmpty()
{
return (this.count() == 0);
}
/**
* Determine whether this container is full.
* @return <CODE>true</CODE> if conatiner is full,
* <CODE>false</CODE> otherwise
*/
public boolean isFull() {
return false;
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 54


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

The descriptions of a Javadoc comment

 The description should give a concise summary of the item being commented.
 It should be written in simple and clear English using correct spelling and grammar.
 Punctuation is required.
 The first sentence of the description is the most important part of the entire description.
 It should be a short and concise summary of the item being commented.
 This is due to the fact that the Javadoc tool copies the first sentence to the appropriate class or package
summary page, which implies that the first sentence should be compact and can stand on its own.

Take a look at the example above again and you'll see that the first sentence is a brief descriptive summary of
each item.
The use of the <code> tag
The use of the <code> tag is greatly encouraged and should be used for all Java keywords, names and
code samples.

Omission of parenthesis

When referring to a method that has no parameters or a method which has multiple forms (method
overloading) it is acceptable and even encouraged to simply omit the parenthesis. Consider the following
example:
The <code>add</code> method inserts items into the vector.

This is the correct way of doing it as opposed to the incorrect way in the next example:

The <code>add()</code> method inserts items into the vector.

Method descriptions begin with a verb

A method usually defines a certain behavior or operation; because of this it usually signals an action that
is best described by a verb.

Determine whether this container is empty or not.


As opposed to:
This method is used to determine whether this container is empty or not.

Avoid abbreviation
 One final word on style guidelines is to avoid the use of abbreviation at all costs as this renders
comments unclear.
 Instead of using an abbreviation one should use its expanded form.

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 55


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

 This applies to all abbreviations.

17)State the purpose of finalize() method In java? With an example explain how finalize()
method can be used in Java program.(Nov/Dec-18)

Finalize() is the method of Object class. This method is called just before an object is garbage collected.
finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory
leaks.

Syntax
protected void finalize() throws Throwable  
Throw

Throwable - the Exception is raised by this method

Example

public class JavafinalizeExample1 {  
     public static void main(String[] args)   
    {   
        JavafinalizeExample1 obj = new JavafinalizeExample1();   
        System.out.println(obj.hashCode());   
        obj = null;   
        // calling garbage collector    
        System.gc();   
        System.out.println("end of garbage collection");   
  
    }   
    @Override  
    protected void finalize()   
    {   
        System.out.println("finalize method called");   
    }   
}  

Output:

2018699554
end of garbage collection
finalize method called

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 56


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

18) What are literals? Explain the types of literals supported by java. (April/May-19)

Java Literals: A literal in java refers to a fixed value that appears directly in a program. Java define five
primary types of literals. By literal we mean any number, text, or other information that represents a value.
Types of Literals:

19) Write a Java code using do while loop that counts down to 1 from 10 printing exactly ten lines of
“hello”.( April/May-2019)

class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(“hello”);
i--;
}while(i>1);
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 57


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

ADDITIONAL PROGRAMS:
HELLOWORLD
import java.io.*;
class hello
{
public static void main(String arg[])
{
System.out.println("Hello World.");
}
}

INPUT
import java.util.*;
class Scanner_Ex
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}

INPUT AND OUTPUT STATEMENT


import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Creates a reader instance which takes input from standard input - keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
// nextInt() reads the next integer from the keyboard
int number = reader.nextInt();
// println() prints the following line to the output screen
System.out.println("You entered: " + number);
}
}
PROGRAM TO ADD TWO INTEGERS
public class AddTwoIntegers {
public static void main(String[] args) {
int first = 10;
int second = 20;
int sum = first + second;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 58


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

System.out.println("The sum is: " + sum);


}}
MULTIPLY TWO FLOATING POINT NUMBERS
public class MultiplyTwoNumbers {
public static void main(String[] args) {
float first = 1.5f;
float second = 2.0f;
float product = first * second;
System.out.println("The product is: " + product);
}
}
COMPUTE QUOTIENT AND REMAINDER
public class QuotientRemainder {
public static void main(String[] args) {
int dividend = 25, divisor = 4;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
System.out.println("Quotient = " + quotient);
System.out.println("Remainder = " + remainder);
}
}
SWAP TWO NUMBERS USING TEMPORARY VARIABLE
public class SwapNumbers {
public static void main(String[] args) {
float first = 1.20f, second = 2.45f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
float temporary = first;
first = second;
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
SWAP TWO NUMBERS WITHOUT USING TEMPORARY VARIABLE
public class SwapNumbers {
public static void main(String[] args) {
float first = 12.0f, second = 24.5f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
first = first - second;
second = first + second;
first = second - first;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 59


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

}
}
CHECK WHETHER A NUMBER IS EVEN OR ODD USING IF...ELSE STATEMENT
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}

CHECK WHETHER A NUMBER IS EVEN OR ODD USING TERNARY OPERATOR


import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
String evenOdd = (num % 2 == 0) ? "even" : "odd";
System.out.println(num + " is " + evenOdd);
}
}

CHECK WHETHER AN ALPHABET IS VOWEL OR CONSONANT USING SWITCH STATEMENT


public class VowelConsonant {
public static void main(String[] args) {
char ch = 'z';
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println(ch + " is vowel");
break;
default:
System.out.println(ch + " is consonant");
}
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 60


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

FIND LARGEST AMONG THREE NUMBERS USING IF..ELSE STATEMENT


public class Largest {
pblic static void main(String[] args) {
double n1 = -4.5, n2 = 3.9, n3 = 2.5;
if( n1 >= n2 && n1 >= n3)
System.out.println(n1 + " is the largest number.");
else if (n2 >= n1 && n2 >= n3)
System.out.println(n2 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
}
}

JAVA PROGRAM TO CHECK A LEAP YEAR


public class LeapYear {
public static void main(String[] args) {
int year = 1900;
boolean leap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year % 400 == 0)
leap = true;
else
leap = false;
}
else
leap = true;
}
else
leap = false;

if(leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 61


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

SUM OF NATURAL NUMBERS USING FOR LOOP


public class SumNatural {
public static void main(String[] args) {
int num = 100, sum = 0;
for(int i = 1; i <= num; ++i)
{
// sum = sum + i;
sum += i;
}
System.out.println("Sum = " + sum);
}
}
SUM OF NATURAL NUMBERS USING WHILE LOOP
public class SumNatural {
public static void main(String[] args) {
int num = 50, i = 1, sum = 0;
while(i <= num)
{
sum += i;
i++;
}
System.out.println("Sum = " + sum);
}
}

FIND FACTORIAL OF A NUMBER USING FOR LOOP


public class Factorial {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}

FIND FACTORIAL OF A NUMBER USING WHILE LOOP


public class Factorial {
public static void main(String[] args) {
int num = 5, i = 1;
long factorial = 1;
while(i <= num)
{
factorial *= i;
i++;
}
System.out.printf("Factorial of %d = %d", num, factorial); }}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 62


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

DISPLAY FIBONACCI SERIES USING FOR LOOP


public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
DISPLAY FIBONACCI SERIES USING WHILE LOOP
public class Fibonacci {
public static void main(String[] args) {
int i = 1, n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
while (i <= n)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
i++;
}
}
}
FIND GCD OF TWO NUMBERS USING FOR LOOP AND IF STATEMENT
public class GCD {
public static void main(String[] args) {
int n1 = 81, n2 = 153, gcd = 1;
for(int i = 1; i <= n1 && i <= n2; ++i)
{
if(n1 % i==0 && n2 % i==0)
gcd = i;
}
System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
}
LCM USING WHILE LOOP AND IF STATEMENT
public class LCM {
public static void main(String[] args) {
int n1 = 72, n2 = 120, lcm;
lcm = (n1 > n2) ? n1 : n2;
while(true)
{

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 63


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

if( lcm % n1 == 0 && lcm % n2 == 0 )


{
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
}
}

REVERSE A NUMBER USING A WHILE LOOP IN JAVA


public class ReverseNumber {
public static void main(String[] args) {
int num = 1234, reversed = 0;
while(num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}

PROGRAM TO CHECK PALINDROME USING FOR LOOP


public class Palindrome {
public static void main(String[] args) {
int num = 11221, reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
for( ;num != 0; num /= 10 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
}
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");
else
System.out.println(originalInteger + " is not a palindrome.");
}
}

PROGRAM TO CHECK PRIME NUMBER USING A FOR LOOP


public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 64


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

CHECK ARMSTRONG NUMBER FOR 3 DIGIT NUMBER


public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}

SIMPLE CALCULATOR USING SWITCH STATEMENT


import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double first = reader.nextDouble();
double second = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = reader.next().charAt(0);
double result;
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 65


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}

FACTORIAL OF A NUMBER USING RECURSION


public class Factorial {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}
PROGRAM TO CONVERT BINARY NUMBER TO DECIMAL
public class BinaryDecimal {
public static void main(String[] args) {
long num = 110110111;
int decimal = convertBinaryToDecimal(num);
System.out.printf("%d in binary = %d in decimal", num, decimal);
}
public static int convertBinaryToDecimal(long num)
{
int decimalNumber = 0, i = 0;
long remainder;
while (num != 0)
{
remainder = num % 10;
num /= 10;
decimalNumber += remainder * Math.pow(2, i);
++i;
}
return decimalNumber; }}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 66


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PROGRAM TO CONVERT DECIMAL NUMBER TO BINARY


public class DecimalBinary {
public static void main(String[] args) {
int num = 19;
long binary = convertDecimalToBinary(num);
System.out.printf("%d in decimal = %d in binary", num, binary);
}
public static long convertDecimalToBinary(int n)
{
long binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n!=0)
{
remainder = n % 2;
System.out.printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
n /= 2;
binaryNumber += remainder * i;
i *= 10;
}
return binaryNumber;
}
}

PROGRAM TO ADD TWO MATRICES


public class AddMatrices {
public static void main(String[] args) {
int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
System.out.println("Sum of two matrices is: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 67


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PROGRAM TO MULTIPLY TWO MATRICES


public class MultiplyMatrices {
public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
System.out.println("Sum of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

PROGRAM TO FIND TRANSPOSE OF A MATRIX


public class Transpose {
public static void main(String[] args) {
int row = 2, column = 3;
int[][] matrix = { {2, 3, 4}, {5, 6, 4} };
display(matrix);
int[][] transpose = new int[column][row];
for(int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
transpose[j][i] = matrix[i][j];
}
}
display(transpose);
}
public static void display(int[][] matrix) {
System.out.println("The matrix is: ");

for(int[] row : matrix) {


for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 68


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

CALCULATE AVERAGE OF NUMBERS ENTERED BY USER


import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
System.out.println("How many numbers you want to enter?");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
double[] arr = new double[n];
double total = 0;
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = scanner.nextDouble();
}
scanner.close();
for(int i=0; i<arr.length; i++){
total = total + arr[i];
}
double average = total / arr.length;
System.out.format("The average is: %.3f", average);
}
}

PROGRAM TO DISPLAY FIRST N PRIME NUMBERS


import java.util.Scanner;
class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
n = scanner.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are:");
System.out.println(2);
}

for ( int i = 2 ; i <=n ; )


{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 69


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}

PROGRAM TO CHECK WHETHER INPUT NUMBER IS PRIME OR NOT


import java.util.Scanner;
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter any number:");
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 70


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

JAVA PROGRAM TO PRINT FLOYD’S TRIANGLE


import java.util.Scanner;
class FloydTriangleExample
{
public static void main(String args[])
{
int rows, number = 1, counter, j;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows for floyd's triangle:");
rows = input.nextInt();
System.out.println("Floyd's triangle");
System.out.println("****************");
for ( counter = 1 ; counter <= rows ; counter++ )
{
for ( j = 1 ; j <= counter ; j++ )
{
System.out.print(number+" ");
number++;
}
System.out.println();
}
}
}
JAVA PROGRAM TO CALCULATE AREA OF RECTANGLE
import java.util.Scanner;
class AreaOfRectangle {
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of Rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of Rectangle:");
double width = scanner.nextDouble();
double area = length*width;
System.out.println("Area of Rectangle is:"+area);
}
}
JAVA PROGRAM TO CALCULATE AREA OF SQUARE
import java.util.Scanner;
class SquareAreaDemo {
public static void main (String[] args)
{
System.out.println("Enter Side of Square:");
Scanner scanner = new Scanner(System.in);
double side = scanner.nextDouble();
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 71


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

JAVA PROGRAM TO CALCULATE AREA OF TRIANGLE


import java.util.Scanner;
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the width of the Triangle:");
double base = scanner.nextDouble();
System.out.println("Enter the height of the Triangle:");
double height = scanner.nextDouble();

double area = (base* height)/2;


System.out.println("Area of Triangle is: " + area); }}

JAVA PROGRAM TO CALCULATE AREA AND CIRCUMFERENCE OF CIRCLE


import java.util.Scanner;
class CircleDemo
{
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
System.out.print("Enter the radius: ");
double radius = sc.nextDouble();
double area = Math.PI * (radius * radius);
System.out.println("The area of circle is: " + area);
double circumference= Math.PI * 2*radius;
System.out.println( "The circumference of the circle is:"+circumference) ;
}
}

BUBBLE SORT PROGRAM FOR SORTING IN ASCENDING ORDER

import java.util.Scanner;
class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter " + num + " integers: ");
for (i = 0; i < num; i++)
array[i] = input.nextInt();
for (i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1])
{

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 72


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}

JAVA PROGRAM FOR LINEAR SEARCH


import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
array = new int[num];
System.out.println("Enter " + num + " integers");
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println("Enter the search value:");
item = input.nextInt();
for (counter = 0; counter < num; counter++)
{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 73


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PROGRAM TO DISPLAY THE GRADE OF STUDENT


import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int marks[] = new int[6];
int i;
float total=0, avg;
Scanner scanner = new Scanner(System.in);
for(i=0; i<6; i++) {
System.out.print("Enter Marks of Subject"+(i+1)+":");
marks[i] = scanner.nextInt();
total = total + marks[i];
}
scanner.close();
avg = total/6;

System.out.print("The student Grade is: ");


if(avg>=80)
{
System.out.print("A");
}
else if(avg>=60 && avg<80)
{
System.out.print("B");
}
else if(avg>=40 && avg<60)
{
System.out.print("C");
}
else
{
System.out.print("D");
}
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 74


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

PROGRAM TO FIND AREA OF SQUARE, RECTANGLE AND CIRCLE USING METHOD


OVERLOADING:

class JavaExample
{
void calculateArea(float x)
{
System.out.println("Area of the square: "+x*x+" sq units");
}
void calculateArea(float x, float y)
{
System.out.println("Area of the rectangle: "+x*y+" sq units");
}
void calculateArea(double r)
{
double area = 3.14*r*r;
System.out.println("Area of the circle: "+area+" sq units");
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
obj.calculateArea(6.1f);
obj.calculateArea(10,22);
obj.calculateArea(6.1);
}
}

CLASS PROGRAM 1

class student
{
int regno;
String name;
}
public class J2aSimpleClass
{
public static void main(String args[])
{
student s=new student();
s.regno = 100;
s.name = "John Marshal";
System.out.println("Reg No " + s.regno);
System.out.println("Name " + s.name);
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 75


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

CLASS PROGRAM 2

import java.util.Scanner;
class students
{
private int regno;
private String name;
void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();
}
void showdata()
{
System.out.println("Reg No " + regno);
System.out.println("Name " + name);
}
}
public class J2bSimpleClass
{
public static void main(String args[])
{
students s=new students();
s.getdata();
s.showdata();
//s.regno = 10; //ERROR: regno is private
}
}

CLASS PROGRAM 3

import java.util.Scanner;
class stud
{
private String name,result;
private int regno,m1,m2,m3,total;
private float percentage;

void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 76


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

System.out.println ("Enter mark1");


m1 = in.nextInt();
System.out.println ("Enter mark2");
m2 = in.nextInt();
System.out.println ("Enter mark3");
m3 = in.nextInt();
}
void calculation()
{
total=m1+m2+m3;
percentage=(total)/3;
if(m1>=50 && m2>=50 && m3>=50)
{
result="PASS";
}
else
{
result="FAIL";
}
}
void show()
{
System.out.println ("\t\t\tStudent Details");
System.out.println ("Name = "+name);
System.out.println ("Register Number = "+regno);
System.out.println ("Marks of 1st Subject = "+m1);
System.out.println ("Marks of 2nd Subject = "+m2);
System.out.println ("Marks of 3rd Subject = "+m3);
System.out.println ("Total Marks = "+total);
System.out.println ("Result = "+result);
System.out.println ("Percentage = "+percentage+"%");
}
}

class J2cSimpleClass
{ public static void main(String[] args)
{ stud s=new stud();
System.out.println ("\t\t\tStudent Information System");
s.getdata();
s.calculation();
s.show();
}
}

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 77


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

ANNA UNIVERSITY QUESTIONS

NOV/DEC 2018

PART-A

1. Define Objects and Classes in java. ( Q.NO:2,3 )

2. Define access specifier. ( Q.NO:42 )

PART-B

1. Explain the characteristics of OOPs. ( Q.NO: 1)


2. Explain the features and characteristics of JAVA. ( Q.NO:2 )
3. What is method? How method is defined? Give Example. ( Q.NO:12 )
4. State the purpose of finalize() method In java? With an example explain how finalize() method can be
used in Java program. ( Q.NO:17)

April/May 2019

PART-A

1.Can a java source file be saved using a name other than the class name? ( Q.NO: 43 )
2. What are inline functions? Give examples. ( Q.NO:44 )

PART-B

1. Discuss the three OOP principles in detail.( Q.NO:1 )


2.What are literals? Explain the types of literals supported by java. ( Q.NO:18 )
3. Explain the selection statements in java using suitable examples. .( Q.NO:8 )
4. Write a Java code using do while loop that counts down to 1 from 10 printing exactly ten lines of
“hello”.( Q.NO:19)

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 78


MAILAM ENGINEERING COLLEGE OOP- CS8392 – UNIT - I

(Nov/Dec-19)
PART-A

1. What is access specifier? ( Q.NO:42)


2. What is javadoc? ( Q.NO:16)
PART-B

1. Explain the various features of java in detail. ( Q.NO:2)


2. What is JVM? Explain the internal architecture of JVM with neat sketch. ( Q.NO:3)

PREPARED BY: D.MURALI, AP/CSE & D.SARANYA, AP/CSE 79

You might also like