0% found this document useful (0 votes)
11 views33 pages

Java - Notes - Unit I & II

The document provides an overview of Object-Oriented Programming (OOP), its paradigms, basic concepts, and differences from Procedure-Oriented Programming (POP). It also discusses the benefits and applications of OOP, along with a detailed history and features of the Java programming language. Additionally, it covers the Java Development Kit (JDK) and the concept of platform independence in Java.
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)
11 views33 pages

Java - Notes - Unit I & II

The document provides an overview of Object-Oriented Programming (OOP), its paradigms, basic concepts, and differences from Procedure-Oriented Programming (POP). It also discusses the benefits and applications of OOP, along with a detailed history and features of the Java programming language. Additionally, it covers the Java Development Kit (JDK) and the concept of platform independence in Java.
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

VYSYA COLLEGE, SALEM-103

CLASS : II [Link](CS) ‘B’ UNIT: I


SUBJECT: PROGRAMMING IN JAVA [Link]: 21UCS06

INTRODUCTION TO OOPS
1. Explain about OOPs. (PART B)
 Object-Oriented Programming (OOP) is an approach to program organization and development, which
attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best
of structured programming features with several new concepts.
 It is a new way of organizing and developing programs and has nothing to do with any particular language.
However, not all languages are suitable to implement the OOP concepts easily. Languages that support
OOP features include Smalltalk, Objective C, C++, Ada and Object Pascal.
 C++, an extension of C language, is the most popular OOP language today. C++ is basically a procedural
language with object-oriented extension.
 Java, a pure object-oriented language, is one of the recent languages added to this list, the latest one being
c#.
PARADIGMS OF PROGRAMMING LANGUAGES
2. Discuss about paradigms of programming languages. (PART C)

Imperative:
 Imperative programming paradigms use code that clearly specifies the actions to be performed.
Procedural:
 Procedural programming is one of the most widely-used paradigms as it can be applied to a wide range of
problems and is relatively easy to write and interpret. This is a type of imperative programming which uses
a sequence of instructions which may be contained within procedures. These instructions are carried out in a
step-by-step manner.
 Examples: Pascal, Python, Logo
Object-Oriented:
 Object-oriented programming (referred to as OOP) is another popular paradigm as it is applicable to certain
types of problem with lots of reusable components which have similar characteristics. OOP is built on
entities called objects formed from classes which have certain attributes and methods. OOP focuses on
making programs that are reusable and easy to update and maintain.
 Examples: Python, Delphi, Java
Declarative:
 Declarative programming focuses on stating the desired result rather than the exact series of instructions
that need to be performed to get to the result. It is the role of the programming language to determine how
best to obtain the result and the details about how it is obtained are abstracted from the user. This type of
programming is common in expert systems and artificial intelligence.
Functional:
 Functional programming uses the concept of reusing a set of functions, which form the core of the program.
Programs are made up of lines of code consisting of function calls, often combined within each other.
Functional programming is closely linked to mathematics.
 Examples: Haskell, C#, Java
1
Logic:
 Logic languages are also part of the declarative programming paradigm and use code which defines a set of
facts and rules based on the problem. Queries are used to find answers to problems.
 Example: Prolog

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING


3. Discuss about basic concepts of OOPs. (PART B/C)
Objects:
 Objects are the basic run time entities in an object oriented system. Ex: Person, Place, Bank account.
 Objects interact by sending messages to one another.
Classes:
 The class is a collection of similar objects.
 The entire set of data and code of an object can be made a user-defined data type by using the concept of a
class. E.g. Flower - class
Rose, hibiscus -objects
Data abstraction and encapsulation:
 The wrapping up of data and methods into a single unit is known as Encapsulation.
 Abstraction refers to the act of representing
essential features without including the background
details or explanations.
Inheritance:
 When the property of one class is acquired by
another class it is called as Inheritance.
 The new class is called a derived class of the
original class and the original class is called the
base class of the new class.
 Inheritance provides the reusability of coding.
Dynamic binding:
 Dynamic binding refers to the linking of a
procedure call to the code to be executed in
response to the function call at run time.
Message communication:
 A message for an object is a request for execution
of a procedure and therefore will invoke a method
in the receiving object hat generates the desired
result.
 Message passing involves specifying the name of
the object, the name of the method and the information to be sent.
Polymorphism:
 Polymorphism means the ability to take more than one form. A single function name can be used to handle
different number and different types of arguments.
 Polymorphism is mainly used in implementing inheritance.

DIFFERENCES BETWEEN PROCEDURE ORIENTED PROGRAMMING AND OBJECT


ORIENTED PROGRAMMING
4. Write the differences between POP and OOP? (PART B/C)

2
PROCEDURAL ORIENTED PROGRAMMING OBJECT-ORIENTED PROGRAMMING
In procedural programming, the program is divided In object-oriented programming, the program is
into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-up
approach. approach.
There is no access specifier in procedural Object-oriented programming has access specifiers
programming. like private, public, protected, etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper Object-oriented programming provides data hiding so
way of hiding data so it is less secure. it is more secure.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
In procedural programming, there is no concept of In object-oriented programming, the concept of data
data hiding and inheritance. hiding and inheritance is used.
In procedural programming, the function is more In object-oriented programming, data is more
important than the data. important than function.
Procedural programming is based on the unreal Object-oriented programming is based on the real
world. world.
Procedural programming is used for designing Object-oriented programming is used for designing
medium-sized programs. large and complex programs.
Procedural programming uses the concept of Object-oriented programming uses the concept of
procedure abstraction. data abstraction.
Code reusability absent in procedural programming, Code reusability present in object-oriented
programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
BENEFITS OF OOPS
5. Explain about the benefits of oops? (PART B)
 Oops offers several benefits to both the program designer and the user.
 The principal advantages are,
 Through inheritance, we can eliminate redundant code and extend the use of existing classes.
 We can build programs from the standard working modules that communicate with one another.
 The principle of data hiding helps the programmers to build secure programs that cannot be invaded
by code in other parts of the programs.
 It is possible to have multiple instance of an object to co-exist without any interference.
 It is possible to map objects in the problem to those in the program.
 It is easy to partition the work in a project base on objects.
 Software complexity can be easily managed.
 This feature is importance depends on the type project and the preference of the programmer.
APPLICATION OF OOPS
6. What are Applications of OOPs? (PART B)
 Real business systems are often much more complex and contain many more objects with complicated
attributes and methods.
 OOP is useful in these types of application because it can simply a complex problem.
 The areas for application of OOP include:
 Real-time systems
 Simulation and modeling
 Object-oriented databases
 Hypertext, hypermedia and expertext
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAM/CAD systems
JAVA
HISTORY
7. Explain the history of Java. (PART B)
3
YEAR DEVELOPMENT
1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer
electronic devices. A team of Sun Microsystems programmers headed by James Gosling was formed to
undertake this task.
1991 After exploring the possibility of using the most popular object-oriented language C++, the team
announced a new language named “Oak”.
1992 The team, known as Green Project team by Sun, demonstrated the application of their new language to
control a list of home appliances using a hand-held device with a tiny touch-sensitive screen.
1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-based Internet into a
graphical-rice environment. The Green Project team came up with the idea of developing Web applets
using the new language that could run on all types of computers connected to the Internet.
1994 The team developed a Web Browser called “Hot Java” to locate and run applet programs on Internet.
1995 Oak was renamed “Java”, due to some legal snags. Many popular companies including Netscape and
Microsoft announced their support to Java.
1996 Java established itself not only as a leader for Internet Programming but also as a general-purpose
object-oriented programming language. Sun releases Java Development Kit 1.0.
1997 Sun releases Java Development Kit 1.1 (JDK 1.1)
1998 Sun releases the Java 2 with version 1.2 of the Software Development Kit (SDK 1.2).
1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).
2000 J2SE with SDK1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0
2006 JAVA SE 6
2011 JAVA SE 7
2014 JAVA SE 8
2017 JAVA SE 9
2018 JAVA SE 10

JAVA FEATURES
8. Explain the features of java? (PART B/C)
 The main objective of java programming language creation was to make it portable, simple and secure
programming language.
 The features of java are as follows:
1. Simple 7. Architectural Neutral
2. Object Oriented 8. Dynamic
3. Portable 9. Interpreted
4. Platform Independent 10. High performance
5. Secured 11. Multithreaded
6. Robust 12. Distributed
Simple:
 Java inherits the c++ syntax.
 Java makes it easy to learn.
 Java is simple and small language.
 Java does not use pointer concept.
Object Oriented:
 Java is a Pure Object Oriented Program.
 Object oriented means we organize our software as a
combination of different types of objects that incorporates
both data and behavior.

Portable:
 Java is portable because it facilitates you to carry the java bytecode to any platforms.
Platform Independent:

4
 Java is a write once, run anywhere.
 Java program compiled with specific platform machines.
 A platform is the hardware or software environment in which a program runs.
 Two components are support to make java has platform indepent:
1. Runtime Environment
2. API(Application Programming Interface)
Secured:
 Java is best known for its security. With
Java, we can develop virus-free systems.
Java is secured because:
 No explicit pointer
 Java Programs run inside virtual
machine sandbox
Robust:
 Robust simply means strong. Java is
robust because:
 It uses strong memory management.
 There are lack of pointers that avoids security problem.
 There is automatic garbage collection in java.
 There is exception handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
 Java is architecture neutral because there is no implementation dependent features e.g. size of primitive
types is fixed.
Dynamic:
 Java is a dynamic language and capable of dynamically link new libraries, methods and objects.
Interpreted:
 Java enables the cross platform program by compiling into an intermediate representation.
 This can be interpreted on any system that provides java virtual machine.
 .Java designed to perform well on very-low power CPU.
 Java byte code will be translate into native code for every high performance by using Just-In –Time
compiler.
High-performance
 Java is faster than traditional interpretation since bytecode is "close" to native code still somewhat slower
than a compiled language (e.g., C++).
 Java is an interpreted language, so it is also a reason that why it is slower than compiled language C, C++.
Distributed
 Java is distributed because it facilitates us to create distributed applications in java.
 RMI and EJB are used for creating distributed applications.
Multi-threaded
 A thread is like a separate program, executing concurrently.
 The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area.
JAVA ENVIRONMENT
9. Explain in detail about java development environment? (PART B/C)
Discuss the followings (i) API and (ii) JDK (PART C)
 Java environment includes a large number of development tools and hundreds of classes and methods.
 The development tools are part of the system known as Java Development Kit (JDK).
 The classes and methods are part of the Java Standard Library (JSL), also known as the Application
Programming Interface (API).
JAVA DEVELOPMENT KIT(JDK)
 The JDK comes with a collection of tools that are used for develop and running java programs.
 Appletviewer(for viewing java Applet)
 Javac (Java compiler)  String literals
 Java ( Java interpreter)  Boolean literals
 Javap (Java disassemble)

5
APPLICATION PROGRAMMING INTERFACE (API)
 The java standard library (or API) includes hundreds of classes and methods grouped into several functional
packages.
Most commonly used packages are:
 Language support package: - A collection of classes and methods required for implementing basic
features of java.
 Utilities package: - A collection of classes to provide utility functions such as date and time functions.
 Input/output packages: -A collection of classes required for Input/output manipulation.
 Networking packages: - A collection of classes for communicating with other computers via internet.
 AWT packages: - The Abstract window Tool Kit package contains class that implements platform
independent graphical interface.
 Applet package: - This includes set of classes that allows us to create java applets.

INTRODUCTION TO JAVA
10. What do you mean by platform independent? (PART B)
 Java is an object oriented programming, Multithreaded programming language; it was developed by Sun
Microsystems in 1991, originally it called oak.
 Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan.
 Java is a Platform independent language. Platform independent means that the same compiled program
can run on virtually any computer in the world.
 Java compiled program can store on a single server and client machine of any type can easily download and
run the program.
 Java manages this by compiling its compiling its source code into a generic byte code language, which the
client machine run using a program called a Java Virtual Machine (JVM).
 Java byte code is also platform independent and can run on multiple platforms without need to recompile
the source code.
 Java provides local compiler for each system that will compile a byte code file into an executable image for
faster running.
 Java calls these as “Just-In-Time” (JIT) compilers.
 Java is a Object Oriented Programming-like most Object oriented Programming Java
 Includes a set of class libraries that provides basic data types, System input and Output and other utility
functions.
TYPES OF JAVA PROGRAM
11. Explain about Types of java program. (PART B)
 Java is a general-purpose, object-oriented programming language. We can develop two types of Java
programs:
1. Standalone applications
2. Web applets

6
 They are implemented as shown in Fig. 3.1. Standalone applications are programs written in Java to carry
out certain tasks on a standalone local computer. In fact, Java can be used to develop programs for all kinds
of applications, which earlier, were developed using languages like C and C++. As pointed out earlier,
HotJava itself is a Java application program.
 Executing a standalone Java program involves two
steps:
1. Compiling source code into bytecode using
javac compiler.
2. Executing the bytecode program using java
interpreter.
 Applets are small Java programs developed for
Internet applications. An applet located on a
distant computer (Server) can be downloaded via
Internet and executed on a local computer (Client)
using a Java-capable browser. We can develop
applets for doing everything from simple animated
graphics to complex games and utilities. Since
applets are embedded in an HTML (Hypertext
Markup Language) document and run inside a
Web page, creating and running applets are more
complex than creating an application.
 Standalone programs can read and write files and
perform certain operations that applets cannot do. An applet can only run within a Web browser.

Installing java software development kit


12. Explain in detail about the steps to install a Java SDK? (PART B)
 The process of designing, coding, testing, debugging, documenting, maintaining and upgrading
computer program is called software development.
 There are two options for developing java software, namely
1. Use an integrated development environment.
2. Use the command line.
 An Integrated Development Environment (IDE) is a collection of inter-working programs that
facilitate software development.
 The Command line of an operating System is used for compiling and running a java program.
 The Java Software Development Kit (SDK) bundles together all the java class libraries and other
software tools to develop java programs.
The following steps are used to download and install java SDK.
1. Go to [Link] on the web, and select J2SE1.4.2 SDK
2. In the first page, find the list of operating system and select either the Net Beans IDE with J2SE or just
the J2SE alone.
3. On the next page, scroll down to the bottom and click on the ACCEPT BUTTON.
4. It brings us finally to the Download page.
5. Click on the link and save the j2sdk file in some folder.
6. After the download is complete, go to the .exe file, and double-click on its icon to install the software.
7. Go back to the first page, and download the Document for the SDK.
Setting the path variable
13. How will you set the path variable? (PART B)
The steps in setting the PATH variable are:
1. Select My Computer and press mouse right button select properties option.
2. It shows System Properties dialog box. Select the Advanced tab and click on Environment variables.
3. Select the path variable in System variables list box and click Edit button.
4. Click in the variable value field, type;C:\JDK1.3\BIN and press OK button.
5. Click on OK button to close the System Properties dialog box.

7
Highlighted Points:
 Open the Command Prompt.
 Move to the drive to work the java program.
 C:\>Z:
 Z:\>
 Set the PATH variable temporarily.
 Z:\>set PATH = c:\jdk1.3\bin
 Create and run a java program.

CREATING AND EXECUTING A JAVA PROGRAM


14. How do you create and execute a java program? (PART B)
Creating the program:
 To create a Java program, a Text editor can be used.
 A popular windows-based text editor is Notepad.
 Other text editors like Text pad or Dos Edit can also be used.
Example: [Link]
class Sample
{
public static void main(String args[])
{
[Link](“Welcome BCA”);
}
}
 Once the program is typed in, Save it by clicking on File->Save.
 Ensure that the filename contains the class name properly. This file is called the source file.
 Also ensure that the program is saved with the extension .java.
 Note also that if a program contains multiple classes, the file name must be the classname of the class
containing the main method.
Compiling the program:
 The next step is to compile the program.
 Compile the program using the command z:\>javac [Link].
 When a program is compiled an object file with byte code is created [Link].
 Byte codes are the basic instructions that can be executed only by the Java Virtual Machine.
Running the program:
 We need to use the java interpreter to run a standalone program.
 Once the program is error free, Execute the program using the command Z:\>java Sample.
 The message “Welcome BCA” appears on the screen.

JAVA TOKENS
8
15. Explain in detail about tokens? (PART B/C)
 The smallest individual units in a program are known as tokens.
 A java program is a collection of tokens, comments and white spaces.
 Java language includes five types of tokens:-
 Reserved Keyword
 Operators
 Identifiers
 Separators
 Literals
Java Character Set
 The smallest units of java language are the characters used to write java tokens. It includes letters, digits and
punctuation marks.
 These characters are defined by the Unicode character set, an emerging standard that tries to create
characters for a large number of scripts worldwide.
 The Unicode is a 16 bit character coding system and currently supports more than 34000 defined characters
derived 24 languages from America, Europe, Middle East, Africa and Asia (including India).
Keywords
 There are 49 reserved keywords in java.
 This keyword cannot be used as names for a variable, class and method.
 Java is a case-sensitive language so all the keywords are to be written in lower-case letters.
abstract boolean break byte byvalue case catch
char default double do else float for
Int long native new package private return
short static super switch throw throws try
void voltile continue goto synchronized assert if
this return transient extend implements final Interface
finally class super while const assert
Identifiers:
 Identifiers are programmer-designed tokens.
 They are used for naming classes, methods, variables, objects, packages, labels, interfaces of the program.
Rules:
What are the rules for naming a variable? (2M)
1. They can have alphabets, digits, underscore & dollar sign.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct
4. They can be of any length
 E.g., average, sum,total_Marks,length,$test,a4
Literals:
 Literals in Java use a sequence of characters that represent constant values to be stored in variables.
 Java language specifies five major types of literals. They are:
 Integer literals
 String literals
 Floating-point literals
 Boolean literals
 Character literals
 The type describes how the values behave and stored.
Operators:
 An operator is a symbol that takes one or more arguments and operators on them to produce a result.
 Example: a+b, a+b*c, (a+b)/(b*c)
What are separators? Describe the various separators in java? (5M)

Separators:
 Separators are symbols used to indicate where groups of code are divided and arranged.
 Example: Parentheses, braces, brackets, semicolon, comma, and period.
Symbols Name Purpose
() Parentheses  Used to contain lists of parameters in method.
 Used t defines precedence in expression.

9
{} Braces  Used to define a block of code for class, methods.
 Used to contain values of initialized arrays.
[] Brackets  Used to declare array.
; Semicolon  Terminate statements.
, Comma  Separates consecutive identifier in a variable declaration.
. Period  Used to separate package name from sub packages and classes.

JAVA VIRTUAL MACHINE (JVM)


[Link] does java achieve architecture neutrality? (PART B)
 The java compiler produces an intermediate code known as byte code for a machine that does not exist. This
machine is called the java virtual machine (JVM).

 The process of compiling a java program into byte code is called virtual machine code.
 The virtual machine code is not specific. The machine specific code is generated by java interpreter. It is
different for different machine.

 The below fig illustrates how java works on a typical computer. The java object framework(Java API) acts
as the intermediary between the user programs and the virtual machine which in turn acts as the
intermediary between the operating system and the java object framework.

COMMAND LINE ARGUMENTS


[Link] are command line arguments? How are they useful? (PART B)
 The command line arguments are parameters that are supplied to the application program at the time of
invoking it for execution.
Example:
class comdlinetest
{
public static void main (String args[])
{
int count=[Link];
10
[Link]("Number of arguments= "+count);
}
}
 The above example args is known as string objects. Any arguments provided in the command line are
passed to the array args as its elements. Consider the following command line:
java comdlinetest a b c d
 This command line contains three arguments. These are assigned to the array args as follows:
a-> args[0] c-> args[2]
b->args[1] d->args[3]

 The individual elements of an array are accessed by using an index or subscripts.


 The output of the program is: “Number of arguments= 4”.
COMMENTS IN JAVA PROGRAM
18. Explain about comments in JAVA with Example. (PART B)
 The Java comments are the statements in a program that are not executed by the compiler and interpreter.
 Types of Comments:
1. Single Line Comment
2. Multi Line Comment
Single Line Comment
 The single-line comment is used to comment only one line of the code. It is the widely used and easiest way
of commenting the statements.
 Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.
 Example:
// This is a comment
[Link]("Hello World");
[Link]("Hello World"); // This is a comment
Multi Line Comment
 The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex
code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there).
 Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
 Example:
/* The code below will print the words Hello World
To the Screen, and it is amazing */
[Link]("Hello World");
Referred in:
1. E. Balagurusamy, ―Programming with Java‖, TataMc-Graw Hill, 5th Edition.
2. Sagayaraj, Denis, Karthick and Gajalakshmi, ―”Java Programming for Core and advanced learners”,
Universities Press (INDIA) Private Limited 2018.
3. Herbert Schildt, ―The complete reference Java‖, TataMc-Graw Hill, 7th Edition.

*****UNIT – I COMPLETED****

UNIT- II
ELEMENTS: CONSTANTS
CONSTANTS
1. Explain Constants with its types. (PART B)
11
 Constant refer to fixed values that do not change during the execution of a program.
Types of Constant:
 The Java language supports several types of constants.
Java Constants

Numeric Character

Integer Real Character String


Integer Constants:
 It refers to a sequence of digits. There are three types of integers:
 Decimal
 Octal
 Hexa decimal
Decimal:
 It consists of a set of digits, 0 through 9, preceded by an optional minus sign.
Example: +78, -123,321
Octal:
 It consists of any combination of digits from the set 0 through 7, with leading zero (0).
Example: 0, 0551, 03
Hexa decimal:
 It consists of sequence of digits preceded by 0x or 0X. They may also include alphabets A through F or
a through f. The letters A through F represents the numbers 10 to 15.
Example: 0xb, 0X2
Real Constants:
 It is represented by numbers containing fractional parts. Such numbers are called real or floating point
constant.
 A real number may also be expressed in exponential or scientific notation.
General Format: Mantissa e exponent
 The mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer number with an optional plus or minus sign.
Example: 0.65e4
Character Constants:
 It contains single character enclosed within a pair of single quote marks.
Example: '1', 'z'
String Constants:
 It is a sequence of characters enclosed between double quotes.
Example: "Welcome"
Backslash Character Constants:
 It is used for output methods. The symbol ‘\n’ stands for new line character.
Example:
'\b'  backspace '\f'  form feed '\n'  new line
'\r'  carriage return '\t'  horizontal tab '\\'  backslash

VARIABLES
2. Explain variables. (PART B)
 A variable is an identifier that represents a storage location used to store a data value.
 A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in
a program. Ex: average, height
 Variable name may consist of alphabets, digits, the underscore (_) and dollar symbol.
Rules for variable declaration:
 They must not begin with a digit.
 Uppercase and lowercase are distinct.
 It should not be a keyword
12
 White space is not allowed.
 Variable names can be of any length.
DATA TYPES
3. Discuss Data types in detail. (PART C)
 Data types specify the size and type of values that can be stored.
 Type determines behavior, not size.
 Java does not support the concept of unsigned types.
 Data types in Java under various two categories:
 Primitive type (intrinsic or built in type).
 Non-primitive (derives or reference type).
Primitive data type:
 It is also called as standard or intrinsic or built-in data type.
 There are eight primitive data types in java. They are classified into four groups:
 Integers
 Characters
 Floating-point numbers
 Boolean

Data types

Primitive Non - Primitive

Non -Numeric Classes


Numeric Arrays
Interface

Integer Floating point Character Boolean

Non-primitive data type:


 It is also known as derived/abstract/reference data type.
 Eg: class,array,interface.
 The default value of reference data type is null.
Integer types:
 A whole number without decimal point.
 The size of the values that can be stored depending on the integer type. Java supports four types of 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.
 The width of an integer type should not be thought of as the amount of storage it consumes, but rather as the
behavior it defines for variables and expressions of that type.
TYPE SIZE [Link] [Link]
byte One byte -128 127
short Two bytes -32,768 32,767
int Four bytes -2,147,483,648 2,147,483,647
long Eight bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Floating-point type:
 A whole number with decimal point. There are two kinds of floating point storage in Java.
 Float type values are single-precision numbers while the double types represent double-precision numbers.
 Double precision types are used when we need greater precision in storage of floating point numbers.

TYPE SIZE [Link] [Link]


13
float 4 bytes 3.4e-038 3.4e+038
double 8 bytes 1.7e-308 1.7e+308
Character type:
 To store the character constant in memory, the character data type is used. It occupies 2 bytes but it can hold
only a single character.
 A character can be enclosed with single quotes.
 The range of character data type is 0 to 65535.
 Ex: char x; x=’t’;
Boolean type:
 It is used to test a particular condition during the execution of the program. It contains either true or false
results.
 Ex: Boolean b; b=false;
SCOPE OF VARIABLES

4. Discuss about the Scope Of Variables. (PART B)


 The area of the program where the variable is accessible is called its scope.
 Variables are created when their scope is entered, and destroyed when their scope is left.
 Variables declared within a method will not hold their values between calls to that methods.
 The Java variable classified into three types:
 Instance
 Class
 Local
Instance Variable:
 These variables are declared inside a class. It was created when the objects are instantiated and associated
with the objects. They take different value for each object. It is called an instance variable because its value
is instance-specific and is not shared among instances.
Class Variable:
 These variables are global to a class and belong to the entire set of objects that class creates. Only one
memory location is created for each class variable.
Local Variable:
 The variables declared and used inside the methods are called local variables. It can also be declared inside
the program blocks that are defined between an open brace {and a close brace}. A local variable cannot be
defined with "static" keyword.
TYPE CASTING
5. Write about type casting in detail. (PART B)
 There is a situation where there is a need to store a value of one type into a variable of another type.
 In such situation, the user must cast the values to be stored by proceeding it with the type name in
parenthesis.
Syntax: type var 1= (type) var 2;
 The process of converting one data type to another is called casting.
 Example: int m=50;
byte n= (byte) m;
long count= (long) m;
Casts that results no loss of information:
From To
byte short,char,int,long, float, double
short int,long,float,double
char int,long,float,double
int long,float,double
long float,double
float double
Automatic conversion:
 It is possible to assign a value of one type to a variable of a different type without a cast.
 Java does the conversion of the assigned value automatically. This is known as automatic type conversion.
 Automatic type conversion is possible only if the destination type that enough precision to store the source
value
14
 The process of assigning a smaller type to a larger one is known as widening or promotion and that of
assigning a larger type to a smaller type one is known as narrowing.
OPERATORS
6. Explain about different types of operators in java. (PART C)
 Java provides a rich operator environment.
 Operators divided into four groups:
1. Arithmetic operators
2. Relational operators
3. Boolean/Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic Operators
 Arithmetic operators are used in mathematical expression. OPR MEANING
 The operands of the arithmetic operators must be of + Addition
numeric type. - Subtraction(unary)
 Ex: a-b, a*b, a/b * Multiplication
/ Division
% Modulus(return remainder division)
Relational Operators
 We often compare two quantities and depending on their
relation, take certain decisions. OPERATOR MEANING
 It determines the relationship that one operand has to the other. == Equal to
ae-1 relational operator ae-2 != not equal to
 ae-1 andae-2 are arithmetic expression. > Greater than
< Less than
 [Link](“a<b is “+(a<b)); >= Greater than or equal to
It displays result as true. <= Less than or equal to

Logical Operators
 It operates on Boolean operands. OPERATOR MEANING
 The logical operators are used to form compound condition by combining && Logical AND
two or more relation. || Logical OR
 It combines two Boolean values to form a resultant Boolean value. ! Logical NOT
 EX: (Total>=100 || average >=80)
Truth table
Value of the expression
op-1 op-2 op-1 && op-2 op-1 || op-2
True True True True
True False False True
False True False True
False False False False

 Op-1 && op-2 is true if both op-1 and op-2 are true and false otherwise.
 Op-1 || op-2 is false if both op-1 and op-2 are false and true otherwise.
AND operator example:
public class OperatorExample{
public static void main(String args[]){ Output:
int a=10; false
int b=5; 10
int c=20; false
[Link](a<b&&a++<c);//false && true = false 11
[Link](a);//10 because second condition is not checked
[Link](a<b&a++<c);//false && true = false
15
[Link](a);//11 because second condition is checked
}
}
OR operator
public class OperatorExample{ Output:
public static void main(String args[]){ true
int a=10; true
int b=5; true
int c=20; 10
[Link](a>b||a<c);//true || true = true true
[Link](a>b|a<c);//true | true = true 11
[Link](a>b||a++<c);//true || true = true
[Link](a);//10 because second condition is not checked
[Link](a>b|a++<c);//true | true = true
[Link](a);//11 because second condition is checked
}
}
Assignment Operators
 ‘=’ is an assignment operator. It assigns the value/variable on right side to the variable on the left side.
Syntax: op= exp;
 Where v is a variable, exp is an expression and op is a java binary operator.
assignment operator Shorthand operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/n(n+1) a/=n+1
a=a%b a %=b
 Java has some shorthand assignment operators.
 Example for shorthand assignment operator: a+=5 which is equivalent to simple assignment operator a=a+5.
 The use of shorthand assignment operators has three advantages:
 What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
 The statement is more concise and easier to read.
 Use of shorthand operator results in a more efficient code.
 Java allows the user to create a chain of assignment.
 Ex: intx,y,z; x=y=z=100;
Example:
public class OperatorExample{ Output:
public static void main(String[] args){ 13
int a=10; 9
a+=3;//10+3 18
[Link](a); 9
a-=4;//13-4
[Link](a);
a*=2;//9*2
[Link](a);
a/=2;//18/2
[Link](a);
}
}
Increment and Decrement Operators
 ++ and -- are increment and decrement operators.
 The operator ++ adds 1 to the operand while –subtracts 1.
 Both are unary operator.
 Ex: ++m; or m++
16
 --m or m—
Ex:
class inc
{
public static void main(String ar[])
{
int a=1;
int b=2;
intc,d;
c=++b;
d=a++;
c++;
[Link](“a= “+a);
[Link](“b= “+b);
[Link](“c= “+c);
[Link](“d= “+d);
}}
Conditional Operator
 ?: is a conditional operator.
 It is also called as ternary operator. Syntax: exp1? exp2:exp3;
 This operator replaces the if-then-else statement.

Java Ternary Operator Example:


public class OperatorExample{
public static void main(String args[]){ Output:
int a=2; 2
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Bitwise Operators
 The bitwise operators are used for testing the bits, or shifting them to the right or left.
 Bit wise operator can’t apply to float and double.
Ex: [Link](x<<2);

OPERATOR MEANING
~ One’s complement
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right with zero fill
<< Shift left

Ex:
a=13;
b=25;
binary numbers are:
a = 00001101
b = 00011001
a&b = 00001001
a|b = 00011101
a^b = 00010100
a=8;
a>>2;
17
a=00001000>>2 = 00000010 = 2
a<<2;
a=00001000<<2 = 00100000 = 32

 Shift right with zero fill is similar to shift right for positive numbers.
 The different arises when we dealing with negative numbers. The negative numbers have the higher-order
bit set to 1. The right shift operator preserves the higher order bit as 1. The shift right zero fill shifts zero
into all upperbits including higher order bit
SPECIAL OPERATORS
 Some special operators are:
 Instance operator
 Dot operator
 New operator
Instance operator:
 The instance operator tests whether an instance derives from a particular class or interface.
 The return type is Boolean.
 The general form is: Person instanceof student
Dot operator:
 The member variable and member methods can be accessed through the member selection operator or dot
operator (.)
 The general form is [Link] // reference to the variable age
[Link]() // reference to the method salary()

Expressions – Evaluation of Expressions


7. Discuss Expressions with its types. (PART B/C)
 Expressions are essential building blocks of any Java program. They are built using values, variables,
operators, and method calls.
 In programming, an expression is any legal combination of symbols that represents a value.
A) Arithmetic Expressions:
 It is a combination of variables, constants, and operators arranged as per the syntax of the language.
B) Evaluation of Expressions:
 The expressions are evaluated using an assignment statement.
Syntax:
 variable = expression;
 In the above syntax variable is any valid Java variable name. When the statement is encountered, the
expression is evaluated first and then result is assigned to the left-hand side.
Example: x = a – b / c + d; y = a * b - c;
C) Precedence of Arithmetic Operators:
 An arithmetic expression without any parenthesis will be evaluated from left to right using the precedence
of operators.
 High Priority * / %
 Low Priority + -
Example 1: x = a – b / 3 + c * 2 - 1 when a = 9, b = 12, and c = 3
 Step 1 : x = 9 - 4 + 3 * 2 - 1 (12 / 3 evaluated)
 Step 2 : x = 9 – 4 + 6 - 1 (3 * 2 evaluated)
 Step 3 : x = 5 + 6 - 1 (9 - 4 evaluated)
 Step 4 : x = 11 - 1 (5 + 6 evaluated)
 Step 5 : x = 10 (11 - 1 evaluated)
 The order of evaluation can be changed by introducing parenthesis into an expression. When the parenthesis
is used, the expressions within parenthesis assume highest priority.
Example 2: x = a – b / (3 + c) * (2 – 1) when a = 9, b = 12, and c = 3
 Step 1 : x = 9 – 12 / 6 * (2 -1)
 Step 2 : x = 9 - 12 / 6 * 1
 Step 3 : x = 9 - 2 * 1
 Step 4 : x = 9 - 2
 Step 5 : x = 7
18
DECISION MAKING AND BRANCHING STATEMENTS-
Introduction
8. Explain about decision making statement with suitable example. (PART B/C)
 When a program breaks the sequential flow and jump to another part of the code, it is called branching.
When the branching is based on a particular condition, it is known as conditional branching. If branching
takes place without any decision, it is known as unconditional branching.
 Java support control or decision making statements.
1. If statement
2. Switch statement
3. Conditional operation statement
Decision Making With If Statement
 The if statement is a powerful decision making statement and is used to control the flow of execution of
statements.
 Simple if statement
 If…else statement
 Nested if…else statement
 Else if ladder
Simple If Statement
Syntax:
if (test expression)
{
Statement block;
} Statement-x;
 The statement block may be single statement or a group of statements.
 If the test expression is true then statement block will be executed otherwise statement block will be skipped
and execution will jump to statement x.
Example program:
import [Link].*;
class first Output:
{
public static void main(String args[ ]) Largest value is a: 55
{ int a=55, b= 32;
if (a>b)
{
[Link] (“Largest value is a:”, +a);
}
}
}
The If…Else Statement
Syntax:
if(test expression)
{
Statement block (true);
}
else
{ Statement block (false);
}
Statement-x;
 The if-else statement is an extension of simple if statement.
 If the test expression is true, then the statement block true immediately following the if statement is
executed; otherwise the statement block false are executed.
Example program:
import [Link].*;
class first1
{
Output:
19
Largest value is b: 32
public static void main(String args[ ])
{
int a=25, b= 32
if (a>b)
{
[Link](“Largest value is a: ” , +a);
}
else
{
[Link](“Largest value is b: ” , +b);
}
}
}
Nesting Of If-Else Statement
 When series of decisions are involved, we may have to use more then one if….else statement in nested form
as follows:
 Syntax:
if test condition 1
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
 If the Condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second
test.
 If the Condition-2 true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and
then the control is transferred to the statement-.
Example program:
import [Link].*;
class Large
{ public static void main(String args[])
{
int a=325, b=712, c=478;
[Link](“Largest value is:”);
if(a>b)
{ if(a>c)
{
[Link](a);
} Output:
else
{ Largest value is: 712
[Link](c);
}
}
else
{ if(c>b)
20
{
[Link](c);
}
else
{
[Link](b);
}
}
}
}
The Else-If Ladder
 This is another way of putting ifs together when multipath decisions are involved.
 A multipath decision is a chain of ifs in which the statement associated with each else is an if.
Syntax:
if (condition1)
statement-1;
else if(condition2)
statement-2;
……
……
else if(condition n)
statement-n;
else
default-statement;
statement-x;
 The conditions are evaluated from the top downwards. As soon as the true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x.
 When all the conditions becomes false, then the final else containing default-statement will be executed.
Example program:
import [Link].*;
class Second
{
public static void main(String args[]) Output:
{ 100 distinction
introllnumber [] = {100, 101, 102, 103}; 101 Ist class
int marks[] = {81, 72, 43, 48}; 102 Fail
for (int i =0; i<rollnumber; i++) 103 2nd class
{
if(marks [i]> 75)
[Link](rollnumber[i] +”” distinction );
else if(marks[i] > 55)
[Link](rollnumber[i] +”” Ist class);
else if(marks[i] > 45)
[Link](rollnumber[i] +”” 2nd class);
else
[Link](rollnumber[i] +”fail”);
}
}
}
The Switch Statement
9. Write about switch statement with suitable example. (PART B)
 Java has a built-in multiway decision statement known as switch.
 The switch statement tests the value of a given variable(or expression)against a list of case values and when
a match is found, a block of statements associated with that case is executed.
Syntax:
switch (expression)
21
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
……
default:
default-block;
break;
}
Statement-x;
 The expression is an integer expression or characters. Value-1, Value-2… are constants or constant
expressions and are known as case labels.
 Block1, Block-2… are statement list and may contain zero or more statements. All case labels are end with
colon(:).
 When the switch is executed, the value of the expression is successively compared against the values value-
1, value-2…..
 If a case is found whose value matches with the value of the expression, then the block of statements follows
the case are executed.
 The default is an optional case.
 The break statement at the end of each block signals the end of a particular case and cause an exit from the
switch statement, transferring control to the statement-x following the switch.
Important points:
 The case variables can be int, short, byte, char, or enumeration.
 String type is also supported since version 7 of Java
 Cases cannot be duplicate
 Default statement is executed when any of the case doesn't match the value of expression. It is optional.
 Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next
case is executed.
 While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
Example program:
import [Link].*;
class letter
{
public static void main(String args[])
{
char letter;
switch (letter) Output:
{ The given alphabet is a vowel
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’:
case ‘u’: [Link](“The given alphabet is a vowel”);
break:
default: [Link](“the given alphabet is not a vowel”);
}
}
}
The? : (conditional) operator
10. Write short notes on ?: operator (PART B)
 The ?: is a conditional operator.
 It is also called as ternary operator.
22
 General form: (Boolean-expression) ? (expression1) : (expression2)
 The exp1 is evaluated first. If it is true, then the expression exp2 is evaluated and its value becomes the
value of the conditional expression.
 If exp1 is false, exp3 is evaluated and its value becomes the value of the conditional expression.
 Example:
If(x<0)
flag = 0;  flag = (x<0) ? 0 : 1 ;
else
flag = 1;
DECISION MAKING AND LOOPING
Introduction
11. Explain iteration statements in detail / Explain about the following (i) for (ii) do...while. (PART C)
 Sequences of statements are executed until some conditions for termination of the loop are satisfied.
 A program loop consists of two segments:
1. Body of the loop
2. Control statement
 The control statement tests certain conditions and then directs the repeated execution of the statements
contained in the body of the loop.
 Depending on the position of the control statements in the loop, a control structure may classify in to two
types.
1. Entry-controlled loop
2. Exit-controlled loop
Entry-controlled loop:
 The control conditions are tested before the start of
the loop execution.
 If the conditions are not satisfied, then the body of
the loop will not be executed. Otherwise it is called
as pre-test loop. Eg: while loop.
Exit-controlled loop:
 The test is performed at end of the body of the loop
and therefore the body is executed unconditionally
for the first time. Another name for Exit-controlled
loop is post-test loop.
Eg: do while.
Iteration Statement:
 The process of repeatedly executing a block of
statements is known as looping (or) iteration.
 The Java language provides for three constructs for
performaing loop operations.
 The while statement
 The do… while statement
 The for statement

The While Statement

 The simplest of all the looping structures in Java is the while statement.
Syntax:
Initialization;
while(test condition)
{
body of the loop;
}
 The while is an entry-controlled loop statement.

23
 The test condition is evaluated and if the condition is true, then the body of the loop is executed. After
execution of the body, the test condition is once again evaluated and if it is true, the body is executed once
again.
Example program:
import [Link].*;
class a
{
public static void main(String args[])
{ j=1; Output:
while(j <4) 123
{ [Link] (j);
j= j + 1;
}
}}
The Do Statement
 In some situations we can execute the body of the loop before the test is performed.
 Such situations can be handled with the help of do statement.
 Syntax:
Initialization;
do
{
body of the loop;
} while(test condition);
 At the end of the loop, the test condition in the while statement is evaluated, if the condition is true, the
program continues to evaluate the body of the loop once again.
 This process continues as long as the condition is true.
 When the condition becomes false, the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
 Since the test condition is evaluated at the bottom of the loop,the do-while construct provides an exit
controlled loop and therefore the body of the loop is always executed at least once.
Example program:
import [Link].*;
class a1
{
public static void main (String args[])
{
j=1:
do
{ Output:
[Link] (j); 1234
j= j + 1;
} while(j <4);
}
}

Difference between while and do while

while do-while
It is a looping construct that will execute only if the It is a looping construct that will execute at least once
test condition is true. even if the test condition is false.
It is an entry controlled loop. It is an exit controlled loop.

The For Statement


 The for loop is another entry-controlled loop that provides a more concise loop structure.
 Syntax:
for(initialization; test condition; increment)
24
{
body of the loop;
}
 The execution of the for loop is as follows
 Initialization of the control variables is done first.
 The value of the control varaible is tested using the test condition.
 The test condition is relational expression.
 When the body of the loop is executed, the control is transferred back to the for statement after evaluating
the last statement in the loop. Now ther control variable got the increment.
 This process continues till the value of the control variable fails to satisfy the test condition.
Example:
Output:
import [Link].*;
Number 10
class Forcls
Number 9
{
Number 8
public static void main (String args[])
Number 7
{
Number 6
int n;
Number 5
for(n=10;n>0;n--)
Number 4
[Link](“Number”+n);
Number 3
}
Number 2
}
Number 1

Additional Features of FOR Loop


 More than one variable can be initialized at a time in the for atatement.
Ex: for(int p=1, int n=1;n<10;n++)
 Like initialization increment section may also have more than one part.
Ex; for(int n=1;int p=1;n<m;n=n+1,p=p+1)
 The third feature is that the test condition may have any compound relation.
EX: for(int i=1; i<20 && sum<100;++i)
Nesting of for loops
 Nesting of loop,that is one for statement within another for statement,is allowed in java.
 EX: for(i=1;i<10;i++)
{ ……..
……..
for(j=1;j<=5;++j)
{ …….
……
}
………
}
The Enhanced For Loop
 The enhanced for loop, also called for each loop is an extended language feature introduced with the J2SE
5.0 release. This feature helps us to retrieve the array of elements efficiently rather than using array indexes.
for (Type Identifier: Expression)
{
// statements;
}
 where Type represents the data type or object used; Identifier refers to the name of a variable; and
Expression is an instance of the [Link] interface or an array.
 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as
the base type of the array, followed by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed array element.
 It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Limitations of for-each loop:
25
 For-each loops are not appropriate when you want to modify the array:
 For-each loops do not keep track of index. So we can not obtain array index using For-Each loop
 For-each only iterates forward over the array in single steps
 For-each cannot process two decision making statements at once
 For-each also has some performance overhead over simple iteration
Break
12. Discuss Jumps in loops.(PART B)
Jumping out of a loop - Skipping a part of a loop
 Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition
 Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a loop.
Break statement: (Jumping out of a loop)
 The break statement is used for exit from a loop. It is used within while, do or for loops.
 As the name suggests, the break statementis used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in
the case of the nested loop. The break statement cannot be used independently in the Java program, i.e., it
can only be written inside the loop or switch statement.
 Syntax: break;
Example: I=0;
while(I<=10)
{
I=I+1;
if(I==5)
break;
[Link](I);
}
Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Java Break Statement with Labeled For Loop
We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop
in Java now whether it is outer or inner loop.
LABELLED LOOPS
 In Java, we can give a label to a block of statements. A label is any valid java variable name.
 To give a label to a loop, place it before the loop.
 Example:
loop1: for(int i=0;i<=10; i++)
{
loop2: while(x<100)
{
y=i*x;
if(y>500)
break loop1;
}
}
Continue statement: (Skipping a part of a loop)
 This statement causes the loop to be continued with the next iteration after skipping any statement in
between.
 Syntax: continue;
Example: I=0;
while(I<=10)
{
I=I+1;
if(I==5)
continue;
[Link](I);
}
ARRAYS
26
Introduction
 An array is a group of contiguous or related data items that share a common name.
 A particular value is indicated by writing a number called index number or subscript in brackets after the
array name.
 Example: salary[10] , It represent the salary of the 10th employee.
 The individual values in an array are called elements. Arrays can be of any variable type.
 The ability to use a single name to represent a collection of items and refer to an item by specifying the item
number enables us to develop concise and efficient programs.
 Two types of Arrays are avaialble
(i) One-Dimensional Array
(ii) Multi-Dimensional Array

ONE-DIMENSIONAL ARRAY
13. Write about one dimensional array. (PART B)
 A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or one-dimensional array.
 Ex: int number[]=new int[5];
 Java subscripts start with the value 0.
 The computer reserves five storage locations as shown below:
number[0]
number[1]
number[2]
number[3]
number[4]
 The values to the array elements can be assigned as follows:
number[0]=20;
number[1]=30;
number[2]=40;
number[3]=50;
number[4]=60;
 This would cause the array number to store the values shown as follows:
number[0] 20
number[1] 30
number[2] 40
number[3] 50
number[4] 60
CREATING AN ARRAY
14. How to create an array in java. (PART B)
 Creation of an array involves three steps.
1. Declare the array.
2. Create memory locations.
3. Initialization of Arrays.
Declaration of Arrays:
 Arrays in java can be declared in two forms.
Form1: type array_name[];
Form2: type[] array_name;
 Ex: int a[];
int[] a;
 Remember, we do not enter the size of the arrays in the declaration.
Creation of Arrays:
 After declaring an array, we need to create it in the memory.
array_name=new type[size];
 Ex: a =new int[20];
 It is possible to combine the two steps – declaration and creation
int a[] = new int[20];
Initialization of Arrays
27
 The final step is put values into the array created. This process is known as initialization.
 Syntax: arrayname[subscript] = value;
 Ex: a[0]=25; a[1]=24; ...a[19]=400;
 Java creates arrays starting with the script of 0 and ends with a value one less than the size specified.
 Jave protects arrays from overruns and underruns. Trying to access an array bound beyond its boundaries
will generare an error message.
 We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared.
 Syntax: type arrayname[]={list of values};
 Ex: int a[]={20,40,50,60};
Example Program:
class first
{
public static void main(String args[])
{
int x[]={21,25,30,48};
[Link]("Numbers are ... ");
for(int i=0;i<4;i++)
[Link]("\t"+x[i]);
}
}
ARRAY PROCESSING
15. Explain about processing of array. (PART B)
 In java, all arrays store the allocated size in a variable named length. We can obtain the length of the array
‘a’ using [Link].
Example: int asize = [Link];
 The information will be useful in the manipulation of arrays when their sizes are not known.
Example:
import [Link].*;
class numbersort
{ public static void main(String args[])
{
int a[]={55,40,80,65,71; OUTPUT:
int n=[Link]; Given List: 55 40 80 65 71
int i,j; Ascending Order
[Link](“Given List: “); **************
for (i=0;i<n;i++) 40
[Link](“ “+a[i]);; 55
for(i=0;i<n;i++) 65
{ 71
for(j=i+1;j<n;j++) 80
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
[Link]("\n\nAscending Order");
[Link]("*****************");
for(i=0;i<n;i++)
[Link](a[i]);
}
}
28
Two-Dimensional Arrays
 We may create a two-dimensional array as
intmyarray[][]; myarray=new int[3][4];
OR
intmyarray[][]=new int[3][4];
 This will create a table that can store 12 integer values, four across and three down.
 Like one dimensional array two dimensional arrays must be initialized by following their declaration with a
list of initial values enclosed in braces.
Ex:inttable[2][3]={1,2,3,9,8,7};
 It initializes the element of the first row to zero and second row to one.
 The initialization is done row by row.
 The above statement is equivalently written as:
int table[][] = { {1, 2, 3}, {9, 8, 7} };
 We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[][] = {
{1, 2, 3},
{9, 8, 7}
};
Variable size arrays
 Java treats multidimensional array as “arrays of arrays”.
 It is possible to declare a two-dimensional array as follows:
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
 These statements create a two-dimensional array as having different lengths for each row.
x[0][1]

x[1][3]

x[2][2]

MULTI-DIMENSIONAL ARRAY
16. Explain about Multi-dimensional array. (PART B)
 Multi-dimensional arrays are defined as arrays of arrays.
 To declare a multi-dimensional array variable specify each additional index using other set of square
brackets.
 Example: int a[] [] = new int [4] [5]

Example:
import [Link].*;
class sample
{ public static void main(String args[])
{
int a[] [] = {0, 1, 1, 3}; Output:
inti,j; 0 1
for(i=0;i<2;i++) 1 3
{ for(j=0;j<2;j++)
{
[Link](a[i][j]);
}
[Link](“”);
}}}
VECTORS
17. Explain vectors in detail. (PART B)
29
 Vector implements a dynamic array.
 [Link] package contains the vector class.
 This class can be used to create a generic dynamic array known as vector that can hold objects of any type
and any number.
 Arrays can be easily implemented as vectors.
Vector intVect=new Vector (); // Declaring without size
Vector list=new Vector (3); // Declaring with size.

 Vectors possess a number of advantages over arrays.


1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.
Example program:
String listArray[]=new String[size];
[Link].*;
[Link](listArray);
import [Link].*;
[Link]("list of languages");
[Link].*;
for(int i=0;i<size;i++)
class vet
[Link](listArray[i]);
{
}
public static void main(String args[])
}
{
Output
Vector list=new Vector();
Z:\>java vet Ada basic C++ FORTRAN java
intleng=[Link];
list of languages
for(int i=0;i<leng;i++)
Ada
{
basic
[Link](args[i]);
COBOL
}
C++
[Link]("COBOL",2);
FORTRAN
int size=[Link]();
java
Vector Methods
METHODS TASKS
[Link](item) Adds the item specified to the list at the list at the end
[Link](10) Gives the name of the 10th object
[Link]( ) Gives the number of objects present
[Link](item) Removes the specified item from the list
[Link](n) Removes the item stored in the nth position of the list
[Link]( ) Removes all the elements in the list
[Link](array) Copies all items from list to array
[Link](item, n) Inserts the item at nth position

ARRAY LIST
18. Discuss Array list in Java. (PART B)
 Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. Elements can be added or removed at anytime. So, it is much more flexible than the traditional array.
It is found in the [Link] package. It is like the Vector in C++.
 The ArrayList in Java can have the duplicate elements also. It implements the List interface. The ArrayList
maintains the insertion order internally.
 It inherits the AbstractList class and implements List interface.
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because the array works on an index basis.
 In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.
 We cannot create an array list of the primitive types, such as int, float, char, etc. It is required to use the
required wrapper class in such cases.
Methods of ArrayList
30
 void add(int index, E element) - It is used to insert the specified element at the specified position in a list.
 boolean isEmpty() - It returns true if the list is empty, otherwise false
 void clear() - It is used to remove all of the elements from this list.
 Example:
import [Link].*;
public class ArrayListExample1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
[Link]("Mango"); //Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
[Link](list); //Printing the arraylist object
}
}

ADVANTAGES OF ARRAY LIST OVER ARRAY


19. List Out The Benefits Of Array List (PART B)
Benefits of ArrayList
 The fact that ArrayList is dynamic in size is one of its main advantages. We can increase and decrease the
size of ArrayList dynamically.
 ArrayList has various predefined methods which help to manipulate the stored objects.
 In ArrayList, we can randomly insert and delete elements.
 We can add different types of objects into the ArrayList.
 In ArrayList, listIterator() allows us to traverse in both directions.
WRAPPER CLASSES
20. Explain about wrapper classes. (PART B)
 Vectors cannot handle primitive data types like int, float, long, short, byte and double.
 Primitive data type may be converted into object types by using the wrapper classes contained in the [Link]
package.
 Simple data types and their corresponding wrapper class types.

Primitive Type Wrapper Class


boolean Boolean
 Below is wrapper class char Character hierarchy as per java API.
double Double
float Float
int Integer
long Long

Object

Number Character Boolean

Byte Short Integer Long Float Double

 The wrapper classes have a number of unique methods for handling primitive data types and objects. They are
listed in the following tables.
1. Converting primitive numbers to Object numbers using constructor methods.
Constructor calling Conversion Action
Integer IntVal = new Integer(i); Primitive integer to Integer object.
Float FloatVal = new Float(f); Primitive float to Float object.
Double DoubleVal = new Double(d); Primitive double to Double object.
31
Long LongVal = new LongVal(l); Primitive long to Long object.
2. Converting Object Numbers to Primitive Numbers using typeValue() method.
Method calling Conversion Action
int i = [Link](); Object to primitive integer.
float f = [Link](); Object to primitive float.
long l = [Link](); Object to primitive long.
double d = [Link](); Object to primitive double.
3. Converting Numbers to String using to String() method.
Method calling Conversion Action
str = [Link](); Primitive integer to string.
str = [Link](); Primitive float to string.
str = [Link](); Primitive double to string.
str = [Link](); primitive long to string.
4. Converting String Objects to Numeric Objects using the static method ValuesOf()
Method calling Conversion Action
Double Val = [Link](str) Converts string to Double object.
Float Val = [Link](str) Converts string to Float object.
Int Val = [Link](str) Converts string to Integer object.
Long Val = [Link](str) Converts string to Long object.

5. Converting Numeric Strings to Primitive Numbers using Parsing Methods.


Method calling Conversion Action
int i = [Link](str); Converts string to Primitive integer.
long l = [Link](str); Converts string to Primitive long.
Example:
classWrapDemo
{
public static void main(String arg[])
{
int mark = 20;
float price = 80.6f;
double rate = 50.5;
Integer m = new Integer(mark);
Float p = new Float(price);
Double r = new Double(rate);
[Link](“Value of wrapper Objects”);

[Link](“Integer Object M =”+m+


”\n Float Object P=”+p+”\n Double Object R=”+r);
int i = [Link]();
float f = [Link]();
double d = [Link]();
[Link](“Unwrapper Values”);
[Link](“int i =”+i+”\n float f=”+f+”\n double d”+d);
}
}

OUTPUT:
Value of Wrapper objects
Integer Object M = 20
Float Object P= 80.6
Double Object R=50.5
Unwrapped Values
int i = 20
float f = 80.6
double d = 50.5
32
Referred in:
1. E. Balagurusamy, ―Programming with Java‖, TataMc-Graw Hill, 5th Edition.
2. Sagayaraj, Denis, Karthick and Gajalakshmi, ―”Java Programming for Core and advanced learners”,
Universities Press (INDIA) Private Limited 2018.
3. Herbert Schildt, ―The complete reference Java‖, TataMc-Graw Hill, 7th Edition.

*****UNIT – II COMPLETED****

33

You might also like