Java - Notes - Unit I & II
Java - Notes - Unit I & II
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
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.
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.
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.
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.
*****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
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
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.
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()
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);
}
}
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.
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.
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
}
}
Object
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.
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