[go: up one dir, main page]

0% found this document useful (0 votes)
5 views38 pages

Java and DS Unit-1

The document provides an introduction to Object-Oriented Programming (OOP) and Java, detailing programming paradigms, basic concepts of OOP, and the history and evolution of Java. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting key features such as encapsulation, inheritance, and polymorphism. Additionally, it outlines the benefits of OOP and its applications in various fields, including user interface design and real-time systems.

Uploaded by

layanalokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views38 pages

Java and DS Unit-1

The document provides an introduction to Object-Oriented Programming (OOP) and Java, detailing programming paradigms, basic concepts of OOP, and the history and evolution of Java. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting key features such as encapsulation, inheritance, and polymorphism. Additionally, it outlines the benefits of OOP and its applications in various fields, including user interface design and real-time systems.

Uploaded by

layanalokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

UNIT-I java and data structures

Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of


Object Oriented Programming– Benefits of OOPs – Application of OOPs, History
and Evolution of Java–Java features – Java Environment. Introduction to Java:
Creating and Executing a Java program– Java Tokens–Data Types - Variables–
Scope of variables–Type casting– Operators– control statements – arrays.

1. Discuss about programming paradigms?


There are two types of programming paradigms they are
1. Procedure – Oriented Programming
2. Object oriented programming
Procedure – Oriented Programming:
The high level languages such as COBOL, FORTRAN and C are commonly known as Global data are easy to change by any function in the program. In a large program
procedureoriented programming (POP). In the procedure-oriented approach, the it is very difficult to identify what data is used by which function.
problem is viewed as a sequence of number functions are written to accomplish Another serious drawback with the procedural approach is that it does not model
these tasks. The primary focus is on functions. real world problems very well. This is because functions are action-oriented and
do not really corresponding to the elements of the problem.
1.Procedural Programming Model: Each problem is divided into smaller problems Some characteristics exhibited by procedure-oriented programming are:
and solved using specified modules that act on data.  Emphasis is on doing things (algorithms).
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

2.Object-Oriented Programming Paradigm: The major motivating factor in the


invention of object-oriented approach is to remove some of the flaws
encountered in the procedural approach.

OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system. It ties data more closely to the functions
that operate on it, and protects it from accidental modification from outside
functions.
In a multi-function program, many important data items are placed as global so OOP allows decomposition of a problem into a number of entities called objects
that they may be accessed by all the functions. Each function may have its own and then builds data and functions around these objects. The organization of data
local data. Fig shows the relationship of data and functions in a procedure- and functions in object-oriented program is shown in figure.
oriented program.

1 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing

Object: Object is an instance of Class (or) Everything is an object Objects are the
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 the program has to
handle. When a program executed, the object interact by sending messages to
one another.
For example customer object requesting account object to know his bank balance
by sending a message in the form of function such as getblance(cust_id);
Each object contain data, and code to manipulate the data. Fig shows two
notations that are popularly used in objectoriented analysis and design.

The data of an object can be accessed only by the functions associated with the
object. However, functions of one object can access the functions of other
objects.
Some of the striking features of object-oriented programming are:
 Emphasis is on data rather than procedure
 Programs are divided into what are known as object Classes: Class is a set of attributes(data) and behavior(methods) shared by similar
 Data structures are designed such that they characterize the object. objects (or) in simple way collection of objects of similar type is called a Class.
 Functions that operate on the data of on object are tied together in the The entire set of data and code of an object can be made a user-defined data type
data structure with the help of a class. Objects are variable of the type class. Once a class has
 Data is hidden and cannot be accessed by external functions. been defined, we can create any number of objects belonging to that class.
 New data and functions can be easily added whenever necessary. class Student
 Follows bottom-up approach in program design. {
String name;
2. Discuss about basic concepts of Object oriented programming String dob;
approach? int marks;
BASICS CONCEPTS OF OBJECT –ORIENTED PROGRAMMING }
Some of the concepts used extensively in object-oriented programming. Student s1=new Student();
These include: Here s1 is the object of student class and also s1 is the variable of type class
1. Objects student.
2. Classes
3. Data abstraction and encapsulation

2 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Data Encapsulation:
The wrapping up of data and function into a single unit (called class) is Class: A class is a group of objects which have common properties. It is a template
known as encapsulation. The data is not accessible to the outside world, and only or blueprint from which objects are created.
those functions which are wrapped in the class can access it. Encapsulation is one Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
of the best Java OOPs concepts of wrapping the data and code. In this OOPs called a derived class, extended class, or child class.
concept, the variables of a class are always hidden from other classes. It can only Super Class/Parent Class: Super class is the class from where a subclass inherits
be accessed using the methods of their current class the features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates
Data Abstraction: you to reuse the fields and methods of the existing class when you create a new
Abstraction refers to the act of representing essential features without class. You can use the same fields and methods already defined in the previous
including the background details or explanations. Classes use the concept of class.
abstraction and are defined as a list of abstract attributes such as size, weight and
cost, and functions to operate on these attributes. Polymorphism:
The attributes are sometimes called data members because they hold • Polymorphism is another important OOP concept. Polymorphism, a Greek
information. The functions that operate on these data are sometimes called term, means the ability to take more than one form. An operation may
methods or member functions. exhibit different behaviors in different instances.
• The behavior depends upon the types of data used in the operation.
Inheritance: • For example, consider the operation of addition. For two numbers, the
Inheritance is the process by which object of one class acquire the operation will generate a sum. If the operands are string, then the
properties of objects of another class. Create a new class derived from the old operation would produce a third string by concatenation.
class. It supports the concept of hierarchical classification. The principle behind • This process of making an operator to exhibit different behaviors in
this sort of division is that each derived class shares common characteristics with different instances is known as operator overloading.
the class from which it is derived as illustrated in fig. • Using a single function name to perform different types of tasks is known
as function overloading. Figure illustrates that a single function name can
be used to handle different number and different types of arguments.

In OOP, the concept of inheritance provides the idea of reusability. This


means that we can add additional features to an existing class without modifying Dynamic Binding:
it. This is possible by deriving new class from the existing one. The new class will Binding refers to the linking of a procedure call to the code to be
have the combined features of both the class. executed in response to the call. Dynamic Binding (also known as late binding)

3 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


means that the code associated with a given procedure call is not known until the 5. It is easy to partition the work in a project based on objects.
time of the call at run-time. It is associated with polymorphism and inheritance. 6. Object-oriented systems can be easily upgraded from small to large
A function call associated with a polymorphic reference depends on the systems.
dynamic type of that reference. Consider the procedure “draw” in above figure by 7. Message passing techniques for communication between objects makes
inheritance; every object will have this procedure. Its algorithms are, however, the interface descriptions with external systems much simpler.
unique to each object and so the draw procedure will be redefined in each class 8. Software complexity can be easily managed.
that defines the object.
Applications of OOP:
Message Passing: Applications of OOP are beginning to gain importance in many areas.
An object-oriented program consists of a set of objects that The most popular application of object-oriented programming, up to
communicate with each other. now, has been in the area of user interface design such as windows. Windows are
The process of programming in an object-oriented language, therefore, developed using OOP techniques. OOP is simplifying the complex problem.
involves the following basic steps:
i. Creating classes that define objects and their behavior. The other areas for application of OOP include:
ii. Creating objects from class definitions, and • Real-time systems
iii. Establishing communication among objects. • Simulation and modeling
A message for an object is a request for execution of a procedure, and • Object-oriented databases
therefore will invoke a function (procedure) in the receiving object that generates • Hypertext, hypermedia and expertext
the desired result. Message passing involves specifying the name of the object, • AI and expert systems
the name of the function (message) and the information to be sent. Example: • Neural networks and parallel programming
• Decision support and office automation systems
• CAM/CAD systems

3. Write the differences between POP and OOP?


Key Difference between OOP and POP
 The main purpose of OOP is on Data Security, whereas the main focus of
POP is on how to get the task done.
 OOP is Object-Oriented Programming, and POP is Procedure-Oriented
Benefits of OOPs: Programming.
OOP offers several benefits to both the program designer and user.  OOP has three accessing modes: “Public”, “Private”, and “Protected,”
1. Through inheritance, we can eliminate redundant code and extend the while POP has no specific accessing modes.
use of existing classes.  POP doesn’t support inheritance, while OOP supports inheritance that
2. The principle of data hiding helps the programmer to build secure allows using attributes and functions of other classes by inheriting.
programs that cannot be invaded by code on other parts of the program.  In OOP, the virtual function supports polymorphism, whereas there is no
3. It is possible to have multiple instances of on object to co-exist without concept of virtual function in POP.
any interference. On the Object-oriented
S.no. Procedural Programming
4. It is possible to map objects in the problem domain to those objects in basis of programming
the program. 1. Definition The concept of dividing the large The large program is

4 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


program into sub-programs known divided into entities operator
as functions and all functions known as objects overloading.
shares common data and has its these objects are It gives importance
It gives importance to functions
own data called local data runtime entities that 10. Importance to data over
over data.
have data and functions.
functions bind There is not any proper way for There is a possibility
11. Data hiding
together. data hiding. of data hiding.
Data hiding is In OOP, a program is
In Procedural programming, a
possible in object- divided into small
Program program is divided into small
oriented 12. parts that are
division programs that are referred to as
programming due to referred to as
2. Security It is less secure than OOPs. functions.
abstraction. So, it is objects.
more secure than The examples of
procedural object-oriented
programming. Examples of Procedural
programming are -
13. Examples programming include C, Fortran,
It follows a bottom- .NET, C#, Python,
3. Approach It follows a top-down approach. Pascal and VB.
up approach. Java, VB.NET, and
In OOP, objects can C++.
In procedural programming, data move and
Data
4. moves freely within the system communicate with
movement
from one function to another. each other via 4. Discuss about history and evolution of java?
member functions.
5. Orientation It is structure/procedure-oriented. It is object-oriented. • Java is a programming language and a platform. Java is a high level,
The access modifiers robust, object-oriented and secure programming language.
Access There are no access modifiers in in OOP are named as
6.
modifiers procedural programming. private, public, and • Java was developed by Sun Microsystems (which is now the subsidiary of
protected. Oracle) in the year 1995. James Gosling is known as the father of Java.
There is a feature of Before Java, its name was Oak. Since Oak was already a registered
Procedural programming does not inheritance in object-
7. Inheritance company, so James Gosling and his team changed the name from Oak to
have the concept of inheritance. oriented
programming. Java.
It offers code
History of Java
Code There is no code reusability present reusability by using
8.
reusability in procedural programming. the feature of • Java was developed by James Gosling, who is known as the father of Java,
inheritance.
in 1995. James Gosling and his team members started the project in the
In OOP, there is a
Overloading is not possible in early '90s.
9. Overloading concept of function
procedural programming.
overloading and

5 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Beta
JDK 1.0 January The Very first version was released on January 23, 1996.
1996 The principal stable variant, JDK 1.0.2, is called Java 1.
JDK 1.1 February Was released on February 19, 1997. There were many
1997 additions in JDK 1.1 as compared to version 1.0 such as
Inner classes added to the language
JavaBeans
Currently, Java is used in internet programming, mobile devices, games, e- JDBC
RMI
business solutions, etc. Following are given significant points that describe the
J2SE December “Play area” was the codename which was given to this
history of Java. 1.2 1998 form and was released on 8th December 1998.
Sun’s JVM was outfitted with a JIT compiler
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green J2SE May 2000 Codename- “KESTREL” Release Date- 8th May 2000
Team. 1.3 Additions:
HotSpot JVM included
2) Initially it was designed for small, embedded systems in electronic appliances
like set-top boxes. J2SE February Codename- “Merlin” Release Date- 6th February 2002
1.4 2002 Additions:
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was Library improvements
.gt. Regular expressions
J2SE September Codename- “Tiger” Release Date- “30th September 2004”
4) After that, it was called Oak and was developed as a part of the Green project. 5.0 2004 Originally numbered as 1.5 which is still used as its
internal version.
5) In 1995, Oak was renamed as "Java" because it was already a trademark by
Added several new language features such as:
Oak Technologies. for-each loop
Generics
6) Java is an island in Indonesia where the first coffee was produced (called Java Var-args
coffee). It is a kind of espresso bean. Java name was chosen by James Gosling JAVA December Codename- “Mustang” Released Date- 11th December
while having a cup of coffee nearby his office. SE 6 2006 2006 Packaged with a database supervisor and
encourages the utilization of scripting languages with the
Evolution of java JVM.
Replaced the name J2SE with java SE and dropped the .0
History of various Java versions: from the version number.
JDBC 4.0 support (JSR 221)
Version Release Major changes JAVA July 2011 Codename- “Dolphin” Release Date- 7th July 2011 Added
Date SE 7 small language changes including strings in the switch.
JDK 1995 The JVM was extended with support for dynamic

6 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


languages. JAVA March Released Date – 16th March 2021
Additions: SE 16 2021 Additions-
Compressed 64-bit pointers. Records (preview feature).

JAVA March Released Date- 18th March 2014 Language level support JAVA September Released Date – 14th September 2021
SE 8 2014 for lambda expressions and default methods and a new SE 17 2021 Additions-
date and time Strong encapsulation of JDK internals by default.
JAVA September Release Date: 21st September 2017 Project Jigsaw: New macOS rendering pipeline.
SE 9 2017 designing and implementing a standard, a module system JAVA 22 Mar New java features were added for strong programming
for the Java SE platform, and to apply that system to the SE 18 2022
platform itself and the JDK.
JAVA 20 Sep Feature added - Record pattern, Vector API (Fourth
JAVA March Released Date- 20th March SE 19 2022 incubator)
SE 10 2018 Addition:
JAVA 21 Mar Feature added Record Patterns, Pattern Matching for
Thread-local handshakes
SE 20 2023 switch.
JAVA September Released Date- 25th September, 2018
SE 11 2018 Additions- JAVA 19 Sep Feature added - String Templates , Pattern Matching for
Dynamic class-file constants SE 21 2023 switch etc.
HTTP client (standard)
Transport Layer Security (TLS) 1.3
5. Discuss about features of Java in detail?
JAVA March Released Date- 19th March 2019
SE 12 2019 Additions-
Default CDS Archives
JAVA September Released Date – 17th September 2019
SE 13 2019 Additions-
Text Blocks (Multiline strings).

JAVA March Released Date – 17th March 2020


SE 14 2020 Additions-
Records (new class type for data modeling).
Pattern Matching
Helpful NullPointerExceptions.
JAVA September Released Date – 15th September 2020
SE 15 2020 Additions-
Sealed Classes.
Hidden Classes.

7 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


The primary objective of Java programming language creation was to make it  Inheritance
portable, simple and secure programming language. Apart from this, there are  Polymorphism
also some excellent features which play an important role in the popularity of this  Abstraction
language. The features of Java are also known as Java buzzwords.  Encapsulation
A list of the most important features of the Java language is given below.
1. Simple 3. Portable
2. Object-Oriented Java is portable because it facilitates you to carry the Java bytecode to any
3. Portable platform. It doesn't require any implementation.
4. Platform independent 4. Platform Independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

1. Simple Java is a write once, run anywhere language. A platform is the hardware or
Java is very easy to learn, and its syntax is simple, clean and easy to understand. software environment in which a program runs.
According to Sun Microsystem, Java language is a simple programming language
because: Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted
 Java syntax is based on C/C++ (so easier for programmers to learn it after
C++). into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
 Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an 5. Secured
Automatic Garbage Collection in Java. Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
2. Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and functions.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
 Object
 Class

8 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java
application anymore.
o There are exception handling and the type checking mechanism in Java.
All these points make Java robust.

7. Architecture-neutral
Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture. However, it occupies
4 bytes of memory for both 32 and 64-bit architectures in Java.

8. Interpreted
Java programs produce intermediate byte code these byte code are line by line
o No explicit pointer interpreted by JVM with the help of JIT compiler to speed up the process.
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime 9. High-performance
Environment (JRE) which is used to load Java classes into the Java Virtual Java is faster than other traditional interpreted programming languages because
Machine dynamically. It adds security by separating the package for the Java bytecode is "close" to native code. It is still a little bit slower than a compiled
classes of the local file system from those that are imported from language (e.g., C++). Java is an interpreted language that is why it is slower than
network sources. compiled languages, e.g., C, C++, etc.
o Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects. 10.Distributed
o Security Manager: It determines what resources a class can access such Java is distributed because it facilitates users to create distributed applications in
as reading and writing to the local disk. Java. RMI and EJB are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on the
Java language provides these securities by default. Some security can also be internet.
provided by an application developer explicitly through SSL, JAAS, Cryptography, 11 Multi-threaded
etc. A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
6. Robust main advantage of multi-threading is that it doesn't occupy memory for each
The English mining of Robust is strong. Java is robust because: thread. It shares a common memory area. Threads are important for multi-media,
o It uses strong memory management. Web applications, etc.
o There is a lack of pointers that avoids security problems.

9 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


the implementation of JVM. It physically exists. It contains a set of libraries +
12 Dynamic other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides
Java is a dynamic language. It supports the dynamic loading of classes. It means
Sun Micro Systems.
classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
6. Explain about java environment in detail?
because it doesn't physically exist. It is a runtime environment in which Java
bytecode can be executed.
JAVA DEVELOPMENT KIT (JDK)
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a JVM Architecture
software development environment which is used to develop Java applications. It Let's understand the internal architecture of JVM. It contains classloader, memory
physically exists. It contains JRE + development tools. area, execution engine etc.
JDK is an implementation of any one of the below given Java Platforms released
by Oracle Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform

JRE-Java Runtime Environment 1. Class Loader Subsystem


JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. It is mainly responsible for three activities.
The Java Runtime Environment is a set of software tools which are used for  Loading
developing Java applications. It is used to provide the runtime environment. It is  Linking
 Initialization

10 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Loading: The Class loader reads the “.class” file, generate the corresponding Execution engine executes the “.class” (bytecode). It reads the byte-code
binary data and save it in the method area. For each “.class” file, JVM stores the line by line, uses data and information present in various memory area
following information in the method area. and executes instructions. It can be classified into three parts:
 Interpreter: It interprets the bytecode line by line and then executes.
The fully qualified name of the loaded class and its immediate parent class.  Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an
Whether the “.class” file is related to Class or Interface or Enum. interpreter..
Modifier, Variables and Method information etc.  Garbage Collector: It destroys un-referenced objects.(releases memory
space of unused objects).
After loading the “.class” file, JVM creates an object of type Class to represent this
file in the heap memory. 4. Java Native Interface (JNI) :
Java Native Interface (JNI) is a framework which provides an interface to
Linking: Performs verification, preparation. communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or interact
 Verification: It ensures the correctness of the .class file i.e. it checks with OS libraries.
whether this file is properly formatted and generated by a valid compiler 7. Explain the Structure of Java Program?
or not. If verification fails, we get run-time Java is an object-oriented programming, platform-independent, and secure
exception java.lang.VerifyError. programming language that makes it popular. Using the Java programming
 Preparation: JVM allocates memory for class variables and initializing the language, we can develop a wide variety of applications.
memory to default values.

Initialization: In this phase, all static variables are assigned with their values
defined in the code and static block (if any). This is executed from top to bottom
in a class and from parent to child in the class hierarchy.

2. JVM Memory
 Method area: In the method area, all class level information like class
name, immediate parent class name, methods and variables information
etc. are stored, including static variables.
 Heap area: Information of all objects is stored in the heap area. There is
also one Heap Area per JVM.
 Stack area: All local variables of that method are stored in their
corresponding frame.
 PC Registers: Store address of current execution instruction to be
fetched.
 Native method stacks: It stores native method (built-in library) o Documentation Section
o Package Declaration
information.
o Import Statements
3. Execution Engine o Interface Section
o Class Definition

11 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


o Class Variables and Variables either import a specific class or import all classes of a particular package. In a Java
o Main Method Class program, we can use multiple import statements. For example:
o Methods and Behaviors
Documentation Section import java.util.Scanner; //it imports the Scanner class only
The documentation section is an important section but optional for a Java import java.util.*; //it imports all the class of the java.util package
program. It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program name, company Interface Section
name, and description of the program. It improves the readability of the It is an optional section. We can create an interface in this section if required. For
program. Whatever we write in the documentation section, the Java compiler example:
ignores the statements during the execution of the program. To write the interface Car
statements in the documentation section, we use comments. The comments may {
be single-line, multi-line, and documentation comments. void start();
void stop();
Single-line Comment: It starts with a pair of forwarding slash (//). }
For example:
//First Java Program
Multi-line Comment: It starts with a /* and ends with */. We write between
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the
these two symbols.
class, we cannot create any Java program. A Java program may conation more
For example:
than one class definition. We use the class keyword to define the class. The class
/*It is an example of
is a blueprint of a Java program. It contains information about user-defined
multiline comment*/
methods, variables, and constants. Every Java program has at least one class that
contains the main() method.
Documentation Comment: It starts with the delimiter (/**) and ends with */.
we define variables and constants that are to be used later in the program.
For example:
For example:
/**It is an example of documentation comment*/
class Student //class definition
{
Package Declaration
String sname; //variable
The package declaration is optional. It is placed just after the documentation
int id;
section. In this section, we declare the package name in which the class is placed.
}
For example:
package arithmeticpackage; //where arithmeticpackage is the package name
package arithmeticpackage.add; //where arithmeticpackage is the root directory Main Method Class
and add is the subdirectory In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In
other words, it is an entry point of the class. It must be inside the class. Inside the
Import Statements main method, we create objects and call the methods. We use the following
The import statement represents the class stored in the other package. We use statement to define the main() method:
the import keyword to import the class. It is written before the class declaration
and after the package statement. We use the import statement in two ways, class Studentdemo

12 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


{
public static void main(String args[])
{
Student s1=new Student();
s1.method1(); //calling methods
s1.method2();
}
}

8. Discuss about Compilation and Execution of a Java Program?


Java, being a platform-independent programming language, doesn’t work on the
one-step compilation. Instead, it involves a two-step execution
The two principal stages are explained below:
Principle 1: Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes
the source code into a machine-independent encoding, known as Bytecode. The
content of each class contained in the source file is stored in a separate ‘.class’
file. While converting the source code into the bytecode.

Principle 2: Execution
The class files generated by the compiler are independent of the machine or the At compile time, the Java file is compiled by Java Compiler (It does not interact
OS, which allows them to be run on any system. To run, the main class file (the with OS) and converts the Java code into bytecode.
class that contains the method main) is passed to the JVM and then goes through
three main stages before the final machine code is executed.

At runtime, the following steps are performed:

The Complete flow diagram and then we will understand the execution process
step by step. Note that there basically are 2 phases – Compile time and Run Time

13 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


class DemoFile
{
public static void main(String args[])
{
System.out.println("Hello!");
System.out.println("Java");
}
}
Step 2:
Open Command Prompt.
 Java program is created, compiled and executed.
Step 3:
 Java code is written in .java file.
Set the directory in which the .java file is saved. In our case, the .java file is saved
 This code contains one or more Java language attributes like Classes, in C:\\demo.
Methods, Variable, Objects etc. javac is used to compile this code and to
generate .class file. Class file is also known as “byte code“.
 The name byte code is given may be because of the structure of the
instruction set of Java program.
 Java byte code is an input to Java Virtual Machine. JVM read this code
and interpret it and executes the program.
Step 4:
Use the following command to compile the Java program. It generates a .class file
in the same folder. It also shows an error if any.
:/>javac DemoFile.java

Step 5:
Use the following command to run the Java program:
:/> java DemoFile

Running a java program in windows


Step 1:
Write a program on the notepad and save it with .java (for example,
DemoFile.java) extension.

14 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


9. What are Java Tokens? 26. native 27. new 28. package 29. private 30. protected
The Java compiler breaks the line of code into text (words) is called Java tokens. 31. public 32. return 33. short 34. static 35. super
These are the smallest element of the Java program. That is the smallest 36. switch 37. synchronized 38. this 39. throw 40. throws
individual parts of the java program are known as tokens. 41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
The Java compiler identified these words as tokens. These tokens are separated 2. Identifier: Identifiers are used to name a variable, constant, function,
by the delimiters. It is useful for compilers to detect errors.
class, and array. It usually defined by the user. It uses letters, underscores, or a
dollar sign as the first character.Remember that the identifier name must be
different from the reserved keywords.
There are some rules to declare identifiers are:
1. The first letter of an identifier must be a letter, underscore . It cannot
start with digits but may contain digits.
2. The space cannot be included in the identifier.
3. Identifiers are case sensitive(upper case letter s differs from lower case)
Some valid identifiers are:
PhoneNumber
PRICE
radius
a
12radius //invalid
Types of Tokens
Java token includes the following:
3. Literals in Java
 Keywords
In Java literal is a notation that represents a fixed value in the source
 Identifiers
code. In lexical analysis, literals of a given type are generally known
 Literals
as tokens
 Operators Literals
 Separators In Java, literals are the constant values that appear directly in the
 Comments program. It can be assigned directly to a variable. Java has various types
1. Keywords: These are the pre-defined reserved words of any programming of literals. The following figure represents a literal.
language. Each keyword has a special meaning. It is always written in lower case.
Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements 1. Integer Literals
21. import 22. instanceof 23. int 24. interface 25. long

15 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Integer literals are sequences of digits. There are three types of integer separator ; , . ( ) | { } [ ]
literals: Note that the first three separators (; , and .) are tokens that separate other
For example, 5678, +657, -89, etc. tokens, and the last six (3 pairs of braces) separators are also known as delimiters.
int decVal = 26;
Parentheses (): It is used to call the functions and parsing the parameters.
Character Literals Curly Braces {}: The curly braces denote the starting and ending of a code block.
For example, 'a', '%', '\u000d', etc. Comma (,): It is used to separate two values, statements, and parameters.
Boolean Literals Semicolon (;): It is the symbol that can be found at end of the statements. It
boolean isEven = true; separates the two statements.
String Literals Period (.): It separates the package name form the sub-packages and class. It also
For example, "Jack", "12345", "\n", etc. separates a variable or method from a reference variable.

4. Operators: In programming, operators are the special symbol that tells the 6. Comments: Comments allow us to specify information about the program
compiler to perform a special operation. Java provides different types of inside our Java code. Java compiler recognizes these comments as tokens but
operators that can be classified according to the functionality they provide. There excludes it form further processing. The Java compiler treats comments as
are eight types of operators in Java, are as follows: whitespaces. Java provides the following two types of comments:

o Arithmetic Operators Single line comments: It begins with a pair of forwarding slashes (//).
o Assignment Operators Multi-line comments: It begins with /* and continues until it founds */.
o Relational Operators
o Unary Operators 10. Explain about Data Types in Java?
o Logical Operators Data types specify the different sizes and values that can be stored in the
o Ternary Operators variable. There are two types of data types in Java:
o Bitwise Operators
o Shift Operators 1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
Operator Symbols 2. Non-primitive data types: The non-primitive data types include Classes,
Arithmetic +,-,/,*,% Interfaces, and Arrays.
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^= Java Primitive Data Types
Relational ==, != , < , >, <= , >= In Java language, primitive data types are the building blocks of data
Logical && , || manipulation. These are the most basic data types available in Java language
Ternary (Condition) ? (Statement1) : (Statement2);  boolean data type
Bitwise &,|,^,~  byte data type
Shift << , >> , >>>  char data type
 short data type
5. Separators: The separators in Java is also known as punctuators. There are  int data type
nine separators in Java, are as follows:  long data type

16 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


 float data type Example:
 double data type boolean one = false

2. byte Data Type


The byte data type is an example of primitive data type. It occupies 1 byte in
memory. The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times smaller
than an integer
Example:
byte a = 10, byte b = -20

3. short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range
lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.
Data Size Description The short data type can also be used to save memory just like byte data type. A
Type short data type is 2 times smaller than an integer.
byte 1 byte Stores whole numbers from -128 to 127 Example:
short 2 Stores whole numbers from -32,768 to 32,767 short s = 10000, short r = -5000
bytes
int 4 Stores whole numbers from -2,147,483,648 to 2,147,483,647 4.int Data Type
bytes The int data type is a 32-bit signed two's complement integer. Its value-range lies
long 8 Stores whole numbers from -9,223,372,036,854,775,808 to 31 31
between - 2,147,483,648 (-2 ) to 2,147,483,647 (2 -1) (inclusive). Its
bytes 9,223,372,036,854,775,807
minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its
float 4 Stores fractional numbers. Sufficient for storing 6 to 7
default value is 0.
bytes decimal digits
double 8 Stores fractional numbers. Sufficient for storing 15 decimal
The int data type is generally used as a default data type for integral values unless
bytes digits
if there is no problem about memory.
boolean 1 bit Stores true or false values
Example:
char 2 Stores a single character/letter or ASCII values int a = 100000, int b = -200000
bytes
5. Long Data Type
1.boolean Data Type The long data type is a 64-bit two's complement integer. Its value-range lies
The Boolean data type is used to store only two possible values: true and false. 63
between -9,223,372,036,854,775,808(-2 ) to 9,223,372,036,854,775,807
This data type is used for simple flags that track true/false conditions. 63
(2 -1)(inclusive). Its default value is 0. The long data type is used when you need
The Boolean data type specifies one bit of information, but its "size" can't be a range of values more than those provided by int.
defined precisely.
17 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS
Example: Syntax: Declaring a string
long a = 100000L, long b = -200000L
String_Type string_variable = “sequence_of_string”;
6. Float Data Type Example:
The float data type is a single-precision 32-bit floating point. Its value range is String sname = "suresh kumar";
unlimited. Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits. It
is recommended to use a float (instead of double) if you need to save memory in 2. Array
large arrays of floating point numbers. Its default value is 0.0F. An array is a group of like-typed variables that are referred to by a common
name. Arrays in Java work differently than they do in C/C++. The following are
Example: some important points about Java arrays.
float f1 = 234.5f
In Java, all arrays are dynamically allocated.
7. Double Data Type Since arrays are objects in Java, we can find their length using member length.
The double data type is a double-precision 64-bit floating point. Stores fractional This is different from C/C++ where we find length using size.
numbers. Sufficient for storing 15 decimal digits. Its value range is unlimited. The A Java array variable can also be declared like other variables with [] after the
double data type is generally used for decimal values just like float. Its default data type.
value is 0.0d. The variables in the array are ordered and each has an index beginning from 0.
Declaring an array in java
Example: int arr[]=new int[size];
double d1 = 12.3
11. Explain about variables and scopes of variables in java?
8. Char Data Type A variable is a container which holds the value while the Java program is
The char data type is a single 16-bit Unicode character. The char data type is used executed. A variable is assigned with a data type.
to store characters. Variable is a name of memory location.
Example: You must declare all variables before they can be used. Following is the basic
char choice = 'A' form of a variable declaration
data type variable =value
Non-Primitive Data Type or Reference Data Types
The Reference Data Types will contain a memory address of variable values
There are three types of variables in java: local, instance and static.
because the reference types won’t store the variable value directly in memory.
Variable:
They are strings, objects, arrays, etc.
A variable is the name of a reserved area allocated in memory. In other words, it
is a name of the memory location. It is a combination of "vary + able" which
1. Strings
means its value can be changed.
Strings are defined as an array of characters. The difference between a character
int data=50;//Here data is variable
array and a string in Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character array is a collection of
Example of Valid Variables Declarations and Initializations
separate char type entities. Unlike C/C++, Java strings are not terminated with a
Following are valid examples of variable declaration and initialization in Java −
null character.
int a, b, c; // Declares three ints, a, b, and c.

18 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


int a = 10, b = 10; // Example of initialization int sid; //instance data
byte B = 22; // initializes a byte type variable B. String sname; //instance data
double pi = 3.14159; // declares and assigns a value of PI. void get_data()
char a = 'a'; // the char variable a iis initialized with value 'a' {
}
Types of Variables void put_data()
There are three types of variables in Java {
 local variable }
 instance variable }
 static variable It is called an instance variable because its value is instance-specific and is not
shared among instances.
1) Local Variable We can create an object of student such as
A variable declared inside the body of the method is called local variable. You can Student s1 = new Student();
use this variable only within that method and the other methods in the class Now we can access instance variable outside a class such as
aren't even aware that the variable exists. s1.sid=101
A local variable cannot be defined with "static" keyword. and
Example 1: Variable's local scope with initialization s1.sname=”ramesh”
Here, age is a local variable. This is defined inside display() method and its scope similarly we can crate object s2 such as
is limited to only this method. Student s2 = new Student();
public class Test Now we can access instance variable outside a class such as
{ s2.sid=102
public void display() and
{ s2.sname=”raja”
int age = 0; each and every object and store different data on sid and sname so they called
age = age + 7; instance variables.
System.out.println("Puppy age is : " + age);
} 3) Static variable
A variable that is declared as static is called a static variable. It cannot be local.
2) Instance Variable You can create a single copy of the static variable and share it among all the
A variable declared inside the class but outside the body of the method, is called instances of the class. Memory allocation for static variables happens only once
an instance variable. It is not declared as static. when the class is loaded in the memory.
 Instance variables are declared in a class, but outside a method. class Student
 Instance variables are created when an object is created with the use of {
the keyword 'new' and destroyed when the object is destroyed. int sid; //instance data
For example the following class Student contains sid and sname as instance String sname; //instance data
variables static String college=”MTDC”; //static data
class Student void get_data()
{ {

19 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


} long p = (long)y; // manual casting: double to long
void put_data()
{ Types of Type Casting
} There are two types of type casting:
} 1. Widening Type Casting
Now all objects s1 and s2 also have same memory for college variable that is 2. Narrowing Type Casting
“MTDC”.
Memory is only created one time for static variable and this can be shared by all 1. Widening Type Casting
objects of the class such as s1 and s2 Converting a lower data type into a higher one is called widening type casting. It is
s1.college=”MTDC” and also s2.college=”MTDC”. also known as implicit conversion or casting down. It is done automatically. It is
safe because there is no chance to lose data. It takes place when:
12. Explain about Type casting and Object casting? byte -> short -> char -> int -> long -> float -> double
Type Casting in Java
public class Wideningdemo
In Java, type casting is a method or process that converts a data type into another
{
data type in both ways manually and automatically. The automatic conversion is
public static void main(String[] args)
done by the compiler and manual conversion performed by the programmer.
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Convert a value from one data type to another data type is known as type casting. OUTPUT
In Java, there are two types of casting: Before conversion, the value is: 7
After conversion, the long value is: 7
Widening Casting (automatically) - converting a smaller type to a larger type size After conversion, the float value is: 7.0
byte -> short -> char -> int -> long -> float -> double
In the above example, we have taken a variable x and converted it into a long
Narrowing Casting (manually) - converting a larger type to a smaller size type type. After that, the long type is converted into the float type.
double -> float -> long -> int -> char -> short -> byte
Narrowing Type Casting
double y = 9.78d; Converting a higher data type into a lower one is called narrowing type casting. It
int x = (int) y ; // Manual casting: double to int is also known as explicit conversion or casting up. It is done manually by the

20 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


programmer. If we do not perform casting then the compiler reports a compile- {
time error. int a=10;
double -> float -> long -> int -> char -> short -> byte int b=5;
System.out.println(a+b);//15
public class Narrowingdemo System.out.println(a-b);//5
{ System.out.println(a*b);//50
public static void main(String args[]) System.out.println(a/b);//2
{ System.out.println(a%b);//0
double d = 166.66; }
//converting double data type into long data type }
long l = (long)d;
//converting long data type into int data type 2. Relational Operators: These operators are used to check for relations like
int i = (int)l; equality, greater than, and less than. They return boolean results after the
System.out.println("Before conversion: "+d); comparison. The general format is,
//fractional part lost
System.out.println("After conversion into long type: "+l); variable relation_operator value
//fractional part lost
System.out.println("After conversion into int type: "+i); Some of the relational operators are-
}  ==, Equal to returns true if the left-hand side is equal to the right-hand
} side.
 !=, Not Equal to returns true if the left-hand side is not equal to the
Output right-hand side.
Before conversion: 166.66  <, less than: returns true if the left-hand side is less than the right-hand
After conversion into long type: 166 side.
After conversion into int type: 166  <=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
13. Discuss about Operators in Java in detail?  >, Greater than: returns true if the left-hand side is greater than the
1. Arithmetic Operators: They are used to perform simple arithmetic operations right-hand side.
on primitive data types.  >=, Greater than or equal to returns true if the left-hand side is greater
 * : Multiplication than or equal to the right-hand side.
 / : Division For example these relational expressions can be used in conditional statements
 % : Modulo as follows.
 + : Addition
 – : Subtraction int x=20 ,y=30;
if(x>=y)
public class OperatorExample {
{ System.out.println(“ x is bigger”)
public static void main(String args[]) }

21 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


{
3. Assignment Operator: ‘=’ Assignment operator is used to assigning a value to System.out.println(“Distinction”);
any variable. It has a right to left associativity, i.e. value given on the right-hand }
side of the operator is assigned to the variable on the left, and therefore right-
hand side value must be declared before using it or should be a constant. if(marks1<35 || marks2<35 || marks3<35)
{
The general format of the assignment operator is: System.out.println(“Fail”);
variable = value; }

In many cases, the assignment operator can be combined with other operators to 5. Unary Operators: Unary operators need only one operand. They are used to
build a shorter version of the statement called a Compound Statement. For increment, decrement or negate a value.
example, instead of a = a+5, we can write a += 5.
– : Unary minus, used for negating the values.
 +=, for adding left operand with right operand and then assigning it to the ++ : Increment operator, used for incrementing the value by 1. There are two
variable on the left. varieties of increment operators.
 -=, for subtracting right operand from left operand and then assigning it Post-Increment: Value is first used for computing the result and then
to the variable on the left. incremented.
 *=, for multiplying left operand with right operand and then assigning it Pre-Increment: Value is incremented first, and then the result is computed.
to the variable on the left. -- : Decrement operator, used for decrementing the value by 1. There are
 /=, for dividing left operand by right operand and then assigning it to the two varieties of decrement operators.
variable on the left. Post-decrement: Value is first used for computing the result and then
 %=, for assigning modulo of left operand by right operand and then decremented.
assigning it to the variable on the left. Pre-Decrement: Value is decremented first, and then the result is computed.
For example
4. Logical Operators: These operators are used to perform “logical AND” and int x=5;
“logical OR” operations, i.e., a function similar to AND gate and OR gate in digital y=x++;// post increment so y=5 and x=6
electronics. Used extensively to test for several conditions for making a decision. assigns first and then increments
Java also has “Logical NOT”, which returns true when the condition is false and y=++x;// pre decrement so y=6 and x=6
vice-versa increments and assigns later
similarly pre/post decrements also works.
Conditional operators are:
 Logical AND(&&): returns true when both conditions are true. 6. Bitwise Operators: These operators are used to perform the manipulation
 Logical OR(||): returns true if at least one condition is true. of individual bits of a number. They can be used with any of the integer types.
 Logical NOT(!): returns true when a condition is false and vice-versa. They are used when performing update and query operations of the Binary
For example indexed trees.
&& ,|| can be used to combine two or more relational expressions into one
 &, Bitwise AND operator: returns bit by bit AND of input values.
if(marks<=100 && marks>=90)  |, Bitwise OR operator: returns bit by bit OR of input values.

22 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values. The value of x is 20 = 0 0 0 1 0 1 0 0 (binary format). Now x << 3 will
 ~, Bitwise Complement Operator: This is a unary operator which shift the bits of x towards left by 3 positions. Due to which leftmost 3
returns the one’s complement representation of the input value, i.e., bits will be lost.
with all bits inverted.
 <<, Left shift operator: shifts the bits of the number to the left and Hence, after shifting, bits of x is 1 0 1 0 0 0 0 0 that is 160 in decimal
fills 0 on voids left as a result. Similar effect as multiplying the form. The bit pattern after the left shift is shown in the below figure:
number with some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit depends on
the sign of the initial number. Similar effect as dividing the number
with some power of two.

Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR
of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary) 7. Ternary Operator: In Java, the ternary operator is a type of Java conditional
Bitwise OR Operation of 5 and 7 operator. The meaning of ternary is composed of three parts. The ternary
0101 operator (? :) consists of three operands. It is used to evaluate Boolean
| 0111 expressions. The operator decides which value will be assigned to the variable.
________
0111 = 7 (In decimal)

Bitwise AND (&)


This operator is a binary operator, denoted by ‘&.’ It returns bit by bit
AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101 Syntax:
& 0111 variable = Expression1 ? Expression2: Expression3;
________
0101 = 5 (In decimal) The following program demonstrates Ternary Operator in java
class Ternary
If int x = 20. Calculate x value if x << 3. {
public static void main(String[] args)

23 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


{ 9. instanceof operator: In Java, instanceof is an operator which is used to check
int n1 = 5, n2 = 10, max; object reference. It checks whether an object belongs to the provided class or
not. It returns either true or false, if an object is of specified type then it return
System.out.println("First num: " + n1); true otherwise false.
System.out.println("Second num: " + n2);
max = (n1 > n2) ? n1 : n2; Syntax for declaring instanceof operator is given below.
System.out.println("Maximum is = " + max); Syntax
} object instanceof class
}
for example
8.MemberOperator: It is also known as separator or period or member operator. consider two classes Employee and Student
o It is used to separate a variable and method from a reference variable.
Employee emp=new Employee();
o It is also used to access classes and sub-packages from a package.
For example : To check emp is object of type Employee or not
import java.io; boolean ans = emp instanceof Employee
Import java.util.Scanner Now ans contains true
If
o It is also used to access the member of a class. Student stu =new Student();
boolean ans = stu instanceof Employee();
In simple words, we can say that the dot operator is actually access provider of here ans contains false;
objects and classes. For example:
10. new operator: The ‘new’ operator is used to assign memory dynamically in
class sum java. This operator can be used to declare an object from a class and provide
{ memory for that new object. So it is called instantiation operator.
void get_data()
{  It is used to create the object.
}  It allocates the memory at runtime.
void calculate()
 All objects occupy memory in the heap area.
{
 It invokes the object constructor.
}
For example
void put_data()
{
class Employee
}
{
}
}
Now to create Employee class variable known as object the ‘new’ operator can
sum s =new sum()
be used as follows
s.get_data(); //using dot operator access methods
Employee emp=new Employee();
s.calculate();
s.put_data();

24 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


11. cast operator <= Relational less than or equal
In Java, type casting is a method or process that converts a data type into another > Relational greater than
data type in both ways manually and automatically using cast operator (datatype) >= Relational greater than or equal
.The automatic conversion is done by the compiler and manual conversion instanceof Type comparison (objects only)
performed by the programmer. 8 == Relational is equal to Left to right
Type casting is when you assign a value of one primitive data type to another != Relational is not equal to
type. 7 & Bitwise AND Left to right
double y = 9.78d; 6 ^ Bitwise exclusive OR Left to right
int x = (int) y ; // Manual casting: double to int 5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
long p = (long)y; // manual casting: double to long 3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
Operator Precedence in java 1(least) = Assignment
In java operators follows some order 15(high) precedence (priority) to low += Addition assignment
priority 1(low) as shown below table -= Subtraction assignment
*= Multiplication assignment
Precedence Operator Type Associativity /= Division assignment
15(high) () Parentheses Left to Right %= Modulus assignment
[] Array subscript
· Member selection
14 ++ Unary post-increment Right to left
Control Structures in Java
-- Unary post-decrement
The statements in the code are executed according to the order in which they
appear. However, Java provides statements that can be used to control the flow
13 ++ Unary pre-increment Right to left
of Java code. Such statements are called control flow statements.
-- Unary pre-decrement
+ Unary plus
- Unary minus
It is one of the fundamental features of Java, which provides a smooth flow of
! Unary logical negation
program.
~ Unary bitwise complement
Java provides three types of control flow statements.
(type) Unary type cast
12 * Multiplication Left to right
1. Decision Making statements(Conditional statements)
o if statements
/ Division
% Modulus
a) simple if
11 + Addition Left to right
b) if-else
- Subtraction
c) nested if
d) else-if ladder
10 << Bitwise left shift Left to right
o switch statement
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
2. Loop statements(Iterative statements)
o while loop
9 < Relational less than Left to right
o do while loop

25 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


o for loop
o for-each loop
3. Jump statements (Unconditional statements)
o break statement
o continue statement
14. Discuss about if and if-else statements in java?
1. Decision-Making statements:
Decision-making statements decide which statement to execute depending upon
true or false value. Decision-making statements evaluate the Boolean expression
and control the program flow depending upon the result of the condition
provided. There are two types of decision-making statements in Java, i.e., If
statement and switch statement. Write a java program for simple if to check voting eligibility
1) If Statement: import java.lang.*;
In Java, the "if" statement is used to evaluate a condition. The control of the import java.util.*;
program is diverted depending upon the specific condition. The condition of the If import java.io.*;
statement gives a Boolean value, either true or false. In Java, there are four types class Votedemo
of if-statements given below. {
a) Simple if statement public static void main(String args[])
b) if-else statement {
c) Nested if-statement int age;
d) else-if ladder Scanner obj=new Scanner(System.in);
a) Simple if statement: System.out.println("Enter the age of the person \n");
It is the most basic statement among all control flow statements in Java. It age=obj.nextInt();
evaluates a Boolean expression and enables the program to enter a block of code if(age>=18)
if the expression evaluates to true. {
System.out.println("You are eligible to vote\n");
Syntax of if statement is given below. }
if(condition) }
{ }
statement 1; //executes when condition is true
} b) if-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the if-
block is evaluated as false.

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
26 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS
else{ c). Nested if-statement
statement 2; //executes when condition is false In nested if-statements, the if statement can contain a if or if-else statement
} inside another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition1)
{
if(condition2)
{
statement 1; //executes when condition 1 and 2 is true
}
}
else
{
statement 2; //executes when condition 1 is false
}
Write a java program to check even or odd using if-else
import java.lang.*;
import java.util.*;
import java.io.*;
class Evenoddemo
{
public static void main (String args[])
{
int num;
Scanner obj=new Scanner(System.in);
System.out.println("\n Enter any number\n");
num1=obj.nextInt();
if(num%2==0)
{ Write a java program for finding biggest of three numbers
System.out.println("\n The given number"+num+" is even\n"); import java.lang.*;
} import java.util.*;
else import java.io.*;
{ class Bigdemo
System.out.println("\n The given number"+num+" is odd\n"); {
} public static void main(String args[])
} {
} int a,b,c;

27 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Scanner obj=new Scanner(System.in);
System.out.println("Enter any three numbers"); if(condition 1)
a=obj.nextInt(); {
b=obj.nextInt(); statement 1; //executes when condition 1 is true
c=obj.nextInt(); }
if(a>b) else if(condition 2)
{ {
if(a<c) statement 2; //executes when condition 2 is true
{ }
System.out.println("The biggest="+a); else
} {
else statement 2; //executes when all the conditions are false
{ }
System.out.println("The biggest="+c);
}
}
else
{
if(b>c)
{
System.out.println("The biggest="+b);
}
else
{
System.out.println("The biggest="+c);
}
}
}
}

d) else-if ladder:
The else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements import java.lang.*;
that create a decision tree where the program may enter in the block of code import java.util.*;
where the condition is true. We can also define an else statement at the end of import java.io.*;
the chain. class Marksdemo
{
Syntax of if-else-if statement is given below. public static void main(String args[])
{

28 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


String sname,course; }
int s1,s2,s3,total; }
float avg;
Scanner obj=new Scanner(System.in); Switch Statement:
System.out.println("\n Enter student name \n"); In Java, Switch statements are similar to else-if statements. The switch statement
sname=obj.nextLine(); contains multiple blocks of code called cases and a single case is executed based
System.out.println("\n Enter course name \n"); on the variable which is being switched. The switch statement is easier to use
course=obj.nextLine(); instead of if-else-if statements. It also enhances the readability of the program.
System.out.println("\n Enter three subjects marks");
s1=obj.nextInt(); Points to be noted about switch statement:
s2=obj.nextInt();
s3=obj.nextInt();  The case variables can be int, short, byte, char, or enumeration. String
total=(s1+s2+s3); type is also supported since version 7 of Java
avg=(float)(total/3);  Cases cannot be duplicate
System.out.println("STUDENT NAME="+sname);  Default statement is executed when any of the case doesn't match the
System.out.println("COURSE="+course); value of expression. It is optional.
System.out.println("SUBJECT1="+s1+"SUBJECT2="+s2+"SUBJECT3="+s3);  Break statement terminates the switch block when the condition is
System.out.println("TOTAL="+total+"AVERAGE="+avg); satisfied.
if(avg<=100&&avg>=90)  While using switch statements, we must notice that the case expression
{ will be of the same type as the variable.
System.out.println("\n DISTINCTION");
} Syntax of switch statement
else if(avg<90&&avg>=70) switch (expression)
{ {
System.out.println("\n FIRST CLASS"); case value1:
} statement1;
else if(avg<70&&avg>=60) break;
{ case value2:
System.out.println("\n SECOND CLASS"); statement2;
} break;
else if(avg<60&&avg>=40) .
{ .
System.out.println("\n THIRD CLASS"); .
} case valueN:
else if(avg<40) statementN;
{ break;
System.out.println("\n FAIL");
} default:

29 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


default statement; case 'I':
} case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
System.out.println("\n The given character is vowel \n");
break;
default:
System.out.println("\n The given character is consonant \n");
}
}
}

15 . Explain about Looping Statements in java?


In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
For every loop in java required three important statements
->initialization
->condition checking
import java.lang.*;
->incrementation/decrementation
import java.util.*;
import java.io.*;
Java while loop
class Switchdemo
The while loop is also used to iterate over the number of statements multiple
{
times. It is also known as the entry-controlled loop since the condition is checked
public static void main(String args[])
at the start of the loop. If the condition is true, then the loop body will be
{
executed; otherwise, the statements after the loop will be executed.
char choice;
Scanner obj=new Scanner(System.in);
The syntax of the while loop is given below.
System.out.println("\n Enter any character\n");
choice=obj.next().charAt(0);
while(condition)
switch(choice)
{
{
//looping statements
case 'A':
}
case 'a':
case 'E':
case 'e':

30 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


import java.lang.*;
import java.util.*;
import java.io.*;
class Amstrongnumber
{
public static void main(String args[])
{
int num,sum=0,i,rem,temp;
Scanner obj=new Scanner(System.in);
System.out.println("\n Enter any number to check Amstrong or not \n");
import java.lang.*; num=obj.nextInt();
import java.util.*; temp=num;
import java.io.*; while(num>0)
class Palindromenumber {
{ rem=(num%10);
public static void main(String args[]) sum=sum+(rem*rem*rem);
{ num=(num/10);
int num,sum=0,rem=0,temp; }
Scanner obj=new Scanner(System.in); if(sum==temp)
System.out.println("\n Enter any number \n"); {
num=obj.nextInt(); System.out.println("\n The given number"+sum+"is Amstrong number");
temp=num; }
while(num>0) else
{ {
rem=(num%10); System.out.println("\n The given number"+sum+"is Amstrong number");
sum=(sum*10)+rem; }
num=(num/10); }
} }
if(temp==sum)
{ Java do-while loop
System.out.println("\n The given number is palindrome "); The do-while loop checks the condition at the end of the loop after executing the
} loop statements. When the number of iteration is not known and we have to
else execute the loop at least once, we can use do-while loop.
{
System.out.println("\n The given number is not a palindrome "); It is also known as the exit-controlled loop since the condition is not checked in
} advance. The syntax of the do-while loop is given below.
}
}

31 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


do Java for loop
{ In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
//statements check the condition, and increment/decrement in a single line of code. We use
} while (condition); the for loop only when we exactly know the number of times, we want to execute
the block of code.

for(initialization, condition, increment/decrement)


{
//block of statements
}

import java.lang.*;
import java.lang.*; import java.util.*;
import java.util.*; import java.io.*;
import java.io.*; class Printshape
class Squareofnumbers {
{ public static void main(String args[])
public static void main(String args[]) {
{ int n,i,j;
int n,sum=0,i; Scanner obj=new Scanner(System.in);
Scanner obj=new Scanner(System.in); System.out.println("\n Enter n value \n");
System.out.println("\n Enter n value \n"); n=obj.nextInt();
n=obj.nextInt(); for(i=1;i<=n;i++)
i=1; {
do for(j=1;j<=i;j++)
{ {
sum=sum+(i*i); System.out.print("*");
i++; }
}while(i<=n); System.out.print("\n");
System.out.println("\n The sum of square of natural numbers is" +sum); }
} }
} }

32 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


16. Explain about break and continue in java? Consider the following example to understand the functioning of the continue
Jump statements are used to transfer the control of the program to the specific statement in Java.
statements. In other words, jump statements transfer the execution control to public class ContinueExample
the other part of the program. There are two types of jump statements in Java, {
i.e., break and continue. public static void main(String[] args)
{
Java break statement for(int i = 1; i<= 10; i++)
As the name suggests, the break statement is used to break the current flow of {
the program and transfer the control to the next statement outside a loop or if(i == 5)
switch statement. However, it breaks only the inner loop in the case of the nested {
loop. continue;
}
The break statement cannot be used independently in the Java program, i.e., it System.out.print(i);
can only be written inside the loop or switch statement. }
The following example demonstrates break statement }
public class BreakExample }
{ OUTPUT:
public static void main(String[] args) 1 2 3 4 6 7 8 9 10
{
for(int i = 1; i<= 10; i++) 17. Define Arrays and Explain types of Arrays in java?
{
System.out.print(i); DEFINITION: An array is a collection of homogeneous (similar data type) elements
if(i==5) that share a common name.
{ Normally, an array is a collection of similar type of elements which has contiguous
break; memory location.
} Java array is an object which contains elements of a similar data type.
}
} Additionally, The elements of an array are stored in a contiguous memory
} location. It is a data structure where we store similar elements. We can store only
Output: a fixed set of elements in a Java array.
1 2 3 4 5
Array in Java is index-based, the first element of the array is stored at the 0th
Java continue statement index, 2nd element is stored on 1st index and so on.
Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.

33 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


Length of the array is given by the number of elements stored in it. The general
formula to calculate the length of
the array is, Length = upper_bound - lower bound + 1
where upper_bound is the index of the last element and lower bound is the index
of the first element in the array.

Storing values in arrays


1. Initialization of Arrays
Types of Array in java When an array is initialized, we need to provide a value for every element in the
There are two types of array. array. Arrays are initialized by writing,
type array_name[size]={list of values};
o Single Dimensional Array The values are written with curly brackets and every value is separated by a
o Multidimensional Array comma. When we write,

Single Dimensional Array in Java int marks[ ]={90, 82, 78, 95, 88};
Syntax to Declare an Array in Java 2. Inputting values
dataType[] arr; (or) An array can be filled by inputting values from the keyboard. In this method, a
dataType []arr; (or) while/do-while or a for loop is executed to input the value for each element of
dataType arr[]; the array. For example, look at the code shown below
Instantiation of an Array in Java // Input value of each element of the array
arr=new datatype[size]; int marks []=new int[10] ;
for(int i=0; i<10; i++)
for example {
// declare an array marks[i]=obj.nextInt();
double[] data; }
In the code, we start with the index i at 0 and input the value for the first element
// allocate memory of the array. Since the array can have 10 elements, we must input values for
data = new double[10]; elements whose index varies from 0 to 9.
Here, the array can store 10 elements. We can also say that the size or length of
the array is 10. To display values of an array we use for loop as follows
for(int i=0;i<marks.length;i++)
In Java, we can declare and allocate the memory of an array in one single {
statement. For example, System.out.println(marks*i++” ”);
}
double[] data = new double[10];
Or
CALCULATING THE LENGTH OF THE ARRAY for( int i: marks)
{

34 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


System.out.println(i); Linear search, also known as sequential search, is a very simple, method used for
} searching an array for a particular value. It works by comparing every element of
the array one by one in sequence until a match is found.
The following program demonstrates arrays in java import java.util.*;
import java.lang.*; import java.io.*;
import java.util.*; import java.lang.*;
import java.io.*; class Linearsearch
class Arraydemo {
{ public static void main(String args[])
public static void main(String args[]) {
{ int arr[]={41,52,89,21,17,25,78,11,45,82};
int arr[]=new int[100]; int i,ele,pos,found=0;
int i,n; Scanner obj=new Scanner(System.in);
Scanner obj=new Scanner(System.in); System.out.println("Enter the element you want to search");
System.out.println("\n Enter size of the array \n"); ele=obj.nextInt();
n=obj.nextInt(); System.out.println("The array elements are");
System.out.println("\n Enter "+n+" array values \n"); for(i=0;i<arr.length;i++)
for(i=0;i<n;i++) {
{ System.out.println(arr[i]);
arr[i]=obj.nextInt(); }
}
System.out.println("\n The Array values are "); for(i=0;i<arr.length;i++)
for(i=0;i<n;i++) {
{ if(arr[i]==ele)
System.out.println(arr[i]); {
} pos=i;
} found=1;
} break;
}
Searching an element in an one dimensional array }
Searching means to find whether a particular value is present in the array or not.
If the value is present in the array then searching is said to be successful and the if(found==1)
searching process gives the location of that value in the array. {
System.out.println("Element found at"+pos);
There are two popular methods for searching the array elements. One is linear }
search and the second is binary search. else
1. Linear Search {
System.out.println("Element not found");

35 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


} {val21,val22,val23},
} {val31,val32,val33}
} };
For Example, if you have a 2×3 array of type int, then you can initialize it with the
Two Dimensional arrays in java declaration as:
A 1D array is organized linearly and only in one direction. However, at times, we
need to store data in the form of matrices or tables. A 2D array is specified using int arr[][] = {{1, 2, 3},
two subscripts where one subscript denotes row and the other denotes column. {4, 5, 6}};
C considers the 2D array as an array of 1D arrays. The following 2D array which The following example shows the 2d array declaration with initialization.
can be viewed as an array of arrays.
public class Twodimensional
Declaration of Two-dimensional Arrays {
we can create a 2D array using new as follows: public static void main(String[] args)
data_type [] [] array_name = new data_type[row_size][column_size]; {
Here, int arr[][] = { { 1, 2,4 }, { 3, 4,7 },{5,6,8}};
row_size = number of rows an array will contain. System.out.println("The Two dimensional array:");
column_size = number of columns array will contain. for (int i = 0; i < 3; i++)
So if you have an array of 3×3, this means it will have 3 rows and 3 columns. {
int[][] a = new int[3][4]; for (int j = 0; j < 3; j++)
Here, we have created a multidimensional array named a. It is a 2-dimensional {
array, that can hold a maximum of 12 elements. System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
OUTPUT
The Two dimensional array
1 2 4
3 4 7
5 68
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts
with 0 and not 1.
Once the array is declared and created, it is time to initialize it with values. The following programs demonstrates 2D arrays that represents matrices
2. Write a java program for addition of two matrices
Initialize 2d Array class Matrixaddition
The general syntax for this initialization method is as given below: {
data_type array_name[][] = { public static void main(String args[])
{val11,val12,val13},

36 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


{ array_name = name of the 3d array
int a[][]={{1,3,4},{3,4,5},{4,6,9}};
int b[][]={{1,3,4},{3,4,5},{1,7,8}}; Example of 3d array definition is:
int c[][]=new int[3][3]; int arr[][][]= new int[3][3][3];

//adding and printing addition of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("The Result matrix is");

for(int i=0;i<3;i++) [i]-First index shows number of pages


{ [j]-Second index shows number of rows
for(int j=0;j<3;j++) [k]-Third index shows number of coulmns
{
System.out.print(c[i][j]+" "); Initialize 3D Array
} The general syntax for this initialization method is as given below:
System.out.println(); data_type array_name[][][] = {
} {x1,x2,x3},{x4,x5,x6},{x7,x8,x9},
} {y1,y2,y3},{y4,y5,y6},{y7,y8,y9},
} {z1,z2,z3},{z4,z5,z6},{z7,z8,z9}
Similarly if we place };
c[i][j]=a[i][j]-b[i][j]; The 3D arrays is in the following form
we got subtraction of two matrices.
x1 x2 x3
Three-Dimensional Arrays In Java x4 x5 x6
Three-dimensional arrays are complex for multi-dimensional arrays. A three x7 x8 x9
dimensional can be defined as an array of two-dimensional arrays.
The general definition of a Three-dimensional array is given below: y1 y2 y3
y4 y5 y6
data_type array_name[][][] = new data_type [pages][rows][columns]; y7 y8 y9
Here,

data_type = data type of the elements of the array z1 z2 z3


z4 z5 z6

37 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS


z7 z8 z9

The following program demonstrates 3D arrays input and display


class Threedimensionarray
{
public static void main(String args[])
{
int arr=new int [2] [2][2] ;
int i, j,k;
Scanner obj=new Scanner(System.in);
System.out.println(“Enter the elements of the three dimensional array \n”);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
for(k=0;k<2;k++)
{
arr[i][j][k]=obj.nextInt();
}
}
}

System.out.println(“The three dimensional array is \n”);

for(i=0; i<2; i++)


{
for(j=0; j<2; j++)
{
for(k=0;k<2;k++)
{
System.out.print( arr[i][j][k]+” “);
}
System.out.println();
}
System.out.println();
}
}

38 JAVA AND DATA STRUCTURES II BCA MTDC G UMAMAHESH LECT IN COMPUTERS

You might also like