Java Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

SYLLABUUS)

PROGRAMMINGIN JAVA
B.C.A. PART-II
M.M. : 80
UNIT 1. Introduction:Genesis of Java, Importance to the Internet, Overview of
features. 0OP :00P teatures, Dat types, Control Structures,
Arrays,
Methods and classes, Nested and inner classes, String and string buffer
class, Wrapper class, Yectors.
UNIT 2. Operators : Arithmetic Operators, Relational Operators, Logical
Operators, Bit wise Operators, Conditional Operators, New operator,
and instance of operator. Control Statement; Java's Selection state
ment, Iteration Statement, Jump Statement, Array : Declaring Array
variables, Constructing an Array, Initializing an Array, Multidimen
sional Arrays, Anonymous Arrays.
UNIT 3. Introducing Classes : Class Fundamentals, Declaring object, Assign-
ing object reference variable,Defining methods, Method overloading,
Using objects as parameter, Constructors, Garbage collection, finalize
() method. Inheritance; Inheritance basic, method overloading, object
reference this andsuper,Chainingconstructor using this () and super (),
Member accessibility modifier; public, protected, default accessibility of
member, private protected, private.
UNIT 4. Packages : Define package, CLASSPATH, Importing packages, Inter-
face : Define an interface, implementing interface, extending interface,
variable in interface. Overview of nested class; Top level nested class
and interface, Non static inner class, Local class.
Exception Handling: Fundamental: Exception types, Using try and
catch, Throwing exceptions, Defined exceptions.
UNIT5. Multithreaded Programming:Javaspread model, Creating threads
and threadpriorities,Synchronization, Suspending, resuming and stop-
ping threads. Input/Output: Basic Streams, Byte and character stream,
Predefined streams, reading and writing from console and files. Using
standard Java Packages (lang. util,io), JDBC: Setting the JDBC con
nectivity with backend database.
PRACTICAL WORK
1. Scheme of Examination: Practical examination will be of 3 hours
duration. The distribution of practical marks will be as follows:
Programme 1 20
Programme 2 20
Programme 3 20
Viva 25
Practical copy +Internal record] 15
Total 100
In every program there should be comment for each coded line or block of
code.
3. Practical file should contain printed programs with name of author, date,
path of program, unit number and printed output.
All the following programs or a similar type of programs should be pre-
pared.
26
7. Explain string buffer class. Write a program to generate output:
"was" to generate the
"Raipur is part of CG" then replace word "is" by
the use of string buffer class.
sentence"Raipur was part of CG", by
QUESTITONS Write a program for addition of two-dimensional array. 26
18.
Or, Write a Java program to add any two matrix.
Write a Program to Search the element in one dimensional array. 27
19.
28
20. Write a Java program for prime number or not of any given number.
PROGRAMMING N JAVA WAP in Java to sort element of one dimensional array in ascending order. 29
21.
=

B.C.A. PART-II Unit I


30
Explain operator with example.
What do you undestand by control statement in Java ? (Pt. R.S.S.U. 2021) 31
P. No. 2.
Unitwise QuestionS or, What are iteration statements 7 Explain with example. (Sci. Coll. 2021)
Q.No. 37
What do you understand by array?
Unit I What is multidimensional arrays ? Explain. 38
JAVA is popular in intermet ? What is Anonymous array in Java? (Sci. Coll. 2021) 39
1. What is JAVA ? Explain why Pt. R.S.S.U. 2021) Write a Java program to sort the element of one dimensional Array in desce-
? Discuss the genesis of Java. .
Or, What is Java
for each other? nding order. (Pt R.S.S.U. 2021) 39
2. How and intermet necessary
are java Java is important to the internet. Or, Write a Java program to sort the inputted numbers in descending order
Or, Define Java, Explain why (Sci. Coll. 2021)
using array. (Sci. ColL. 2021)
How is it different from the procedure 7. a Java program to check that the given string is palindrome or not. 40
What is object orient rogramming ? 8 Write
oriented programming ? (Pt. R.S.S.U. 2021)
oriented programming (OOP) ? Describe the
mean by object
Or, What do you
importance of Java.
of 0OP.
(Pt. R.S.S.U. 2021)
What is class ? Explain.
Unit 111
Or, Discuss the overview and features form 1.
in brief. Give the full
Explain the features of Java programming language . What is object explain with example.
following abbreviations: (i) JDK, (ii) JVM, (ii) J2EE,
(iv) J2ME, 2
of the What is Method ? Explain.
(v) J2SE. 12 Explain difference between method overloading and method overriding
Write the compression between Java and C++. +3
(Sei. Coll. 2021) 12 suitable example.
0. Explain various data types in Java. Or, What is method overriding ? Explain method overriding with suitable
What are control structure ? Explain with suitable examples.
5 example.
What is an array ? Explain the different types of array.
7 Or, What is method overloading ? Write a Java program to illustrate method
with example.
9. What is class and method in Java ? Explain (Pt. R.S.S.U. 2021)
18 overloading.
10. What is an object ? Write-the features of Java. . Define constructor with example. (Sci. Coll. 2021)
Write the difference between nested class
and inner class with suitable
11. 18 6. Explain Garbage collection with example. (Pt. R.S.S.U. 2021) 46
example. What is finalize () method in Java and how to override it ? (Sci. Coll. 2021) 47
classes with example.
Or, Explain inner classes and nested 19 3. What is an inheritance ? Explain with example. 47
Java. lang string bufer.
12. Compare the class Java. lang. string and Or, What is inheritance? What are the basic types of inheritance ?
Explain with example any one method from each following classes
of the 9. Explain the different types of inheritance supported by Java with suitable
(i) Java lang. Math, (ii) Java awt.Graphics, (ii) Java lang. Character, (iv) Java 48
util staring Tokenizer, (v) Java lang. Integer. programming example.
10. Explain "this" and "super" keyword in Java. 50
Or, Explain the string and string buffer class with suitable example. 11. What is constructor chaining in Java ? 51
(Pt RS.S.U. 2021)
12. What is access modifier in Java ? 52
mean
& inner class with2
13. What do you by wrapper class ? Differentiate nested
Or, Discuss the member accessibility modifier.
example. (PL R.S.S.U. 2021; Sci. Coll. 2021)
Or, What are Wrapper Classes ? Explain. (Sci. Coll.2021)
4. Explain the utility of Vector with suitable example. 23
15. terms of the following series using do while 24 Unit IV
WAP in Java to print first n What is package ? Write the importance of package. Explain with a program. 54
loop:0, 1, 1, 2, 3, 5, 8..
What is an array ? How is it declared and accessed? Write a program to gen Or, What is the use of package in Java ? Explain with suitable example.
16.
erate the following multi-dimensional anray. 25 Or, What is packages ? Write the working and uses of packages.
2. 55
0 How to import packages in Java?
Describe the implementation of interface. 56
Or, What is the requirement of interface in Java programming?
9 Or, What is interface ? Write the procedure for implementing interface.
interface in Java with example.
4. Write the difference between class and
(Sci. Coll. 2021) 58
Nested classes in Java ? (Pt. R.S.S.U. 2021) 58
Explain UNIT I
class. (Sci. Coll. 2021)
Or, Write a brief note on nested and inner
59
6. Explain Types of Nested classes.
62 Q.1. What is JAVA ? Explain why JAVA is popular in internet?
7. Differentiate regular class and static nested class.
What do you mean by exception? Explain exception handling in java.
Or, What is Java ? Discuss the genesis of Java.
8. 62
is high
(Pt. R.S.S.U. 2021) Ans. Java general purpose, programming language developed by Sun
level
Microsystems. A small team of engineers, know as Green Team initiated the language in
Or, What is exception? Explain the different type of exception.
1991. Java was originally called OAK and was designed for handheld devices and
Explain the use of try, throw, catch and finally blocks with example code. 53 set-top
boxes. On January 23" 1996, JDK 1-0 version was released.
Or, Write short notes on try and catch blocks.
Java is an object oriented language similar to C++, but
10 What is package ? Write a JAVA program for create a package and simplified to eliminate lan-
64
guage features that cause common programming errors. Java source code files are compiled
one package witl import another package. (Pt. R.S.S.U. 2021) into a format called bytecode which can then be executed by a Java
11. What is an exception ? Write a Java program to handle user defined interpreter. Compiled
Java code can run on most computers because Java interpreters and runtime
exception. (Sci. Coll. 2021) 65 environments,
known as Java Virtual Machine (JVM), exist for most operating systems
Macintosh OS and Windows.
including UNIX,
Unit V Java is a programming language
1. What co you mean by thread ? (Sci. Coll. 2021) 66 expressly designed for use in the distributed environ
ment of internet. Java can be used to create
Or, Write about different threads states. complete applications that may run on a single
computer or be distributed among servers and clients in a network. It can also be used to
Or, Describe the complete life cycle of thread. How do we set priorities for
it
build a small application module or applet for use as part of web make
thread? possible for a web page user to interact with the page.
page. Applets
2. What is thread ? How can we set the priority ofthread? 69
Based on the goal of application, it needs to perform
Or, Explain the thread priority with giving suitable example. input/output operations, access
the internet and perform networking tasks, access. The database and
What is synchronization ? Explain with example. 70 many other tasks. This
means the Java application is
4 How can suspending, resuming and stopping a thread ? 72 accessing the services of other applications like operating
systems IO programs, networking programs and the DBMS. How Java does this ?
Or, Write a Java program for suspending, resuming and stopping threads.
Java in addition to providing a
(Pt. R.S.S.U. 2021) language, has provideda means to communicate with
73
other independent applications whose services are must for the Java
What is stream ? Explain Input/Output stream. application to run. The
Or, What is stream ? Explain File Input Stream and File Output Stream.
contract that exist between the Java language and the other
applications is called as Applica-
Or, Write about tream classes using in JAVA.
tion Programming Interface (AP). Java has numerous APIs. All these
factors make Java
Or, Explain the input stream classes and its methods. popular to work on internet.
Or, Write a Java program to illustrate byte and character stream.
Q.2. How are java and internet necessary for each other?
(Pt. R.S.S.U. 2021) Or, Define Java, Explain why Java is important to the internet.
Or, Describe the byte and character stream with example. (Sci. Coll. 2021) Ans. For Definition of Java : Refer Q. No. 1.
Java is
6. What are Predefined Streams ? Explain. 76 strongly associated with the internet because of the fact that the first applica-
. Explain reading Console input. Write a program to read characters from the
tion program written in java was Hot
77 Java, a web browser to run applets on internet. Internet
users can use java to create
console using.Buffered Reader class. applet program and run them locally using a Java enabled
8. Explain writing text files and binary file in Java 77 browser such as Hot Java. They can also use Java-enable browser to download an applet
Explain JDBC with example. (Pt. R.S.S.U. 2021) 79
located ona computer anywhere in the intermet
and run it on his local computer.
Or, Write the steps for setting the JDBC connectivity with database.
(Sci. Coll. 2021)
10. Write a steps to connect java with 81
oracle Remote computer
Or, Write steps to connect Oracle/SQL with Java give suitable example.
Or, Explain how you connect the backend database in Java.
11. WAP in java to create a file using byte and character stream. 83
12. WAP in java to create I/O stream to read and write content of disc file. 83
13. WAP that will count the number of character in file. 84
14. WAP that display a default message dialog box with the message, 35
"Have a nice day".
15. What is thread ? Write a Java program to
Intemet
implement multi threading. 36
(Sci. Coll. 2021) Remote Applet
Practical Portion
(87-104)
Local computer

Fig. Downloading of applet via internet


Programming in JAVA |9
Navbodh B.C.A. Part-I Saral Adhyayan
8|
a true extension of the storage system of the local
the internet
Java applet have made
Shape
computer. applet that could be used by draw ( )
Internet user can also setup their website containing java
to hit a ride on the
information has
user ofinternet. The ability of java applets
other remote as internet
for the internet. Java is properly known
made unique programming language
language. to be
www (world wide web)
is an open-ended information retrieval system designed
contains what are known as web
environment. This system
used in the internet's distributed Triangle object
both information & controls.
Circle object Box object
page that provide Draw (circle)J Draw (box) Draw (triangle)
? How is it different from the pro-
Q.3. What is Object riented Programming Polymarphism
cedure orientedprogramming ? code to be
? Describe the to the linking of a procedure call to the
Or, What do you mean by object oriented programming (0OP) Dynamic Binding: Binding refers means that the code associated with a
importance of Java. executed in response to the call. Dynamic binding with
until the time of the call at runtime. It is associated
Or, Discuss the overview and features of O0P. given procedure call is not known call associated with a polymorphic references
oriented is a term, which is inter-
Ans. Object Oriented Programming : Object polymorphism and inheritance. A procedure
to understand some of the on the dynamic type of that reference.
preted differently by different people. It is therefore necessary depends Oriented Program consists of a set of objects
concepts used extensively in Object
Oriented Programming. There are the general concepts Message Communication: An Object in an object oriented language,
that communicate with each other. The process of progranmming
of OOP which form the heart of Java language. in an Object Oriented system. therefore, involves the following basic steps:
Object and Class: Object are the basic runtime entities and their behaviour.
a person, a place, a bank-account, a table of data or any item that the (1) Creating classes that define objects
They may represent definitions.
program may handle. (2) Creating objects from class communicate with one another
contain different
Class is a collectiod ofvariables and method. A class is a unit that may (3) Establishing communication among objects. Objectsas
same way people pass messages to one
function. Once a class has been defined, we can create any number of objects by sending and receiving information much the
variable and
another.
belonging to that class. and methods into a
Data Abstraction and Encapsulation The wrapping up of data
:
It is the most striking features of a class.
single unit (called class) is known as encapsulation. Objects 1
The data is not accessible to the outside world and only those method which are wrapped in

the class, can access it.

Data Information "out"


Information "in" &
Method Objects 2
Objects S
Encapsulation
to
Abstraction refers the act of representing essential feature without including the
background details or explanations. Classes use the concept of abstraction and are defined
as a list ofabstract attributes such as size, that on
weight and cost, that
operate
and methods
to be
these
attributes. They encapsulate all the essential are
properties of the objects created.
Inheritance : Înheritance is the process by which of one Objects4 Objects 3
objects class acquire the
properties of objects another class. Inheritance supports the concept of hierarchical
classification.
For example, the bird robin is a partofthe class flying bird, which is again a part of the Flg. Network of object communlcatng betcen them
class bird. an is a
therefore will
A message for object request for execution of a procedure and
Polymorphism: Another important OOPconcept is polymorphism. Polymorphism in
invoke a method in receiving object that generate the desired result as shown fig.
means the ability to take more than one form. For example, an operation may exhibit different
behaviour-in different instances. The behaviour depends upon the type of data used in the Message
operation. For example, consider the operation of addition for two numbers, the operation Sending Method 0 Receiving
will objects
generate a sum, if the operation are strings, then the operation would a third string by
concatenation.
Fig. Message trigger a method
Progranmming in JA

10 Navbodh B.C.A. Part-1l Saral Adhyayan brief. Give the full


language in
the features of Java programming
and the Q.4. Explain
the method (message) abbreviations:
involvespecifying the name of form of the following J2SE.
Message passing consider the statement. J2EE, (iv) J2ME, (V)
information to be sent. For examnple () JDK, (i) JVM, (ii) language developed by
purpose,
Ans. Java is a general
object oriented programming language is that it 1s a
feature ofthis
Employeesalary (name); in 1991. The most important
Sun micro system of USA that is not depend to any
1" programming language
natural language. Java is the execute anywhere
platform develop in Java can be
hardware or operating system program
particular
on any system.
Features Java with the following attributes:
of Java :
1. Compiled and interpreted,
Objects Information Platform independent & portable
Message 3. Object Oriented

life Communication with 4. Robust and Secure


Object have a cycle. They can be created and destroyed.
an object is feasible as long as it is alive. 5. Distributed
Procedure Oriented Programming: Conventional programming using a high level small
6. Familiar, simple and
Oriented & interactive
language such as COBOL, FORTRAN and C is commonly knowm as Procedure 7. Multi-thread
the is viewed as a sequence of
Programming. In the procedure oriented approach, problem 8. High performance
things to be done,such as reading, calculating and printing. Anumber offunctions are writen 9. Dynamic & extensible.
for general purpose standalone application.
to accomplish these task. The primary focus on function. A typical programming structure Java will also become the premier language is either compiled or
: a computer language
for procedure program1ming are shown in fig. 1. Compiled and interpreted Usually
these approach thus making Java a two- way system. Java

Main function interpreted. Java combines both instruction. code is not a machine code
into byte code Byte
compiler translate source code machine code that can be directly
translate byte code into
and the I I step Java interpreter
Java program. So we can say that Java is both com-
execute by machine that is running the
piled& interpreted language. moved from
: Java programs can be easily
2. Plateform Independent & portable in
time changes and updation operating
one computer system to another, anywhere, any
Function-1 Function-2 Function-3 resource will not force any changes
in Java program.
system. Processor and system
Java ensure portability in two ways. First Java compiler generates byte code instruc-
the size of primitive datatype are
tion that can be implemented on any machine. Secondly
machine independent
in Java is an
3. Object-oriented: Java is a true object oriented language. Everything
Function 4 Function-5 within & classes.
object. All program code & data reside object
to ensure
4. Robust and Secure : Java is robust language. It provides safeguards
is
time and run time checking for datatype. It designed as a
reliable code. It has compile
garbage collection language.
on
Function-66 Security become an important issue for a language that is used for programing
Function-7 Function-8 internent. Threat of virus & abuse of resource in everywhere.
Fig. Typical structure of procedure oriented programming 5. Distributed: Java is designed as a distributed language for creating application on
The technique of hierarchical decomposition has been used to access
completed in order to solve a problem. specify the task to be network. It has the ability to share both data &program. Java application can open &
remote object on internet as easily as they can do in a local system.
Procedure-oriented programming basically consist
the computer to follow and of writing a list of instruction for 6. Simple, small and familiar : Java is a small & simple language. Many features of
Some characteristics
organized the instruction into group known as function. C &C+ are include in Java. Java does not use pointer, preprocessor header files, goto
Oriented
of Procedure Programming:
Emphasis is on doing things. statement & many other. It also eliminate operator ovedading & multiple inheritance.
7. Muld-thread & Interactive : Multi-thread means handle multiple task. Java sup
Largeprogram are divided into smaller programs knqwn as function.
Most of the function shared
global data. port multi-thread programs. This means that we need not wait for application to finish one
task before beginning another.
to
Data move openly
around the system from function
Function transforms data from are ffom to another. function.
Employs top-down approach in program design.
Programming in JAVA |13

code units
in the
used for
character type char,
Part-l Saral Adhyayan One is the truth values.
B.C.A. number types.
Navbodh floating-point boolean type for Negative
language are a fractional parts.
12 for an interpreted scheme and o n e is without
is impressive to c encoding
Unicode are
Java performance is fast compare for numbers
performance: Sun, Java speed the integer types
8. High According to Integer Types:
intermediate byte code. 1, integer types.
of for dynamic provides the four
due to the u s e Java is capable values a r e allowed. Java Range
&C+. Extensible : Java is a
dynamic language. Storage
9. Dynamic& C++. These Type
requirement
n e w class libraries,
method & object.in other language such as C & -2,147,483,648to 2,147,483,647
linking in function written at runtime.
Java program support linked dynamically 4 bytes
method are int
method. Native -32,768 to 32,767
as native 854,775, 807
function are known
2 bytes - 9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 8
to 9,223,372,036,
following: Short
Full form ofthe
Java Development
Kit 8 bytes
(1) JDK: long -128 to 127 we
Java Virtual Machine o n the
machine o n which
(2)JVM: byte 1 bytes types do
not depend
Platform Enterprise Edition integer results on all machines, same
(3) J2EE: Java 2 Under Java, the ranges of the must with the run
Platform Machine Enterprise Java programs
(4) J2ME: Java 2 the Java code.
Platform Standard Edition. will be running a r e fixed.
Java 2 with fractional
(5) J2SE: the for the various types denoted numbers
between Java and C++. ranges
Q.5. Write comparison Types: The floating-point types
between Java and C++. 2. Floating-Point used in Java.
are
Ans. Comparison
C++ two floating-point types
parts. The Range
JAVA Storage requirement
A p p r o x i m a t e l y + _ 3 . 4 0 2 8 2 3 4 7 E + 3 8 F

Explicit forward referencing required. | Type


Noforward referencing required 4 bytes Approximately+_1.797693 13486231570E+308
Heavy reliance on preprocessor. float
Nopreprocessor. Comma operator. double 8 bytes Most
individual characters.
No comma operator is used to describe
Variable length parameter list. The char Type : The char type a character constant with
Novariable length parameter list. 3. character c o n s t a n t s .
For example, 'A' is
Optional method parameters. be
No optional method parameters. commonly, these will character
different from "A", a string containing a single
value 65. It is
Nogoto Goto Name
Unicode value
No Labels on break and continuue. Escape Sequence
Labels on break and continue. Backspace
lu0008
value. b
Main method cannot return a value. Main function can return a lu0009
t Tab
No globalvariables. global variables. u000a
Hybrid between procedural and object Linefeed
Pure object oriented language.
Carriage return u000d
oriented.
Double quote
lu0022
All methods (functions) are part of class. Can have stand alone functions. "
lu0027
No multiple inheritances. Multiple inheritances. Single quote
Backslash lu00sc
Noparameterized type. Templates as parameterizedtype.
No operator overloading Operator overloading. true and false. It is used for
4.The boolean Type: The boolean type has two values, values.
All nonprimitive types are object. Separate types of structs, union, enumns convert between integers and boolean
evaluating logical conditions. We cannot
andarrays. boolean done;
Boolean data type primitive. No explicit Boolean data types. Here done can be assigned to true or false.
with suitable examples.
Variables are automatically initialized. Q.7. What are control structures/statements ? Explain executed sequentially
are
No automatically initialization
of variables. Ans. A Java program is a set of statements which normally
No pointer arithmetic. Pointers. in the order in which they appear.
of the code. It is
Automatic garbage collection. No automatic garbage collection. When program breaks the sequential flow and jump to another part
is based on a particular condition it is known as
Support multithreading. Nomultithreading. called branching. When the branching
conditional If branching takes place without any decision it is known as uncon-
branching.
Q.6. Explain various data types in Java. ditional branching.
Ans. Java is a Java language process such decision making capabilities and support. The following
must
strongly typed language. This means that every variable have
declared type. There are eight statements are known as control structures or statements:
primitive types in Java. Four of them are integer types. Two
Programming in JAVA|15
14 | Navbodh B.C.A. Part-l Saral Adhyayan

(1) If statement
(2) Switch statement statementx; whenmulti-path
is another way putting if together
of
(3) Conditional operator statement. 4. The else if ladder: There the statement associated
Decision Making with if Statement: The if statement is a powerful
decision making decision is a chain of in which
statement and is used to control the flow of execution of statement. It take the following decision are involved. A multi-path
form:
with cach else. It take following general
form: if(condition)
If (Test expression) statement 1;
It allows the computer to evaluate the expression first and then depending on value of else if (condition 2)
expression is true or false, it transfer the control to particular statement. statcment2;
The ifstatement may be implemented in different form depending on the complexity clse if (condition 3)
of conditions to be tested statement 3;
(1) Simple ifstatement else if (condition n)
else statement statementn;
(2)If.
(3) Nestedif.. else statement else
(4) Else if ladder defaultstatement;
(5) Switch statement. statement x;
1. Simple If Statement : The general form ofa simple if statement is : to red ce the complexity of if-else if
5. Switch statement: Switch statement are used
if (test expression) statement known as a switch. The switch
statement. Java has a built-in multi-way decision
match is
statement test the value of a given variable against a list of case value and when a
statementt statement associated with that case is execute. The general form of switch
found, a block of
statement is:
statermentx; Switch (xpression)
2. The If. Else Statement : The if ...else statement is an extension ofsimple if
statement the general form is:
case value 1;
if(test expression) block 1

True block statement;


break;
case value 2;
block 2
else
{ break
*********

false block statement;


************

statement-x; default;
Ifthe test expression is true then the true block statement is execute default- block
otherwise false
statement is execute. break;
3. Nested
if. .
ese Statement: The general from is Nestedif... else Statement are :
statement x;
if(test expression)
The expression is an integer expression or character value 1, value constant
2..are
if(test cond2) or constant expression are known as case labels each of these vaue is unique within a switch
statement, block 1, block 2.... are statement list and may contain zero or more statement.
statement1; Q.8. What is an array ? Explain the different types ofarray.
Ans. An array is a collection of similar datatype that share a common name. For
else example we can define an array name salary to represent a set of salaries of a group of
employee. Aparticular value is indicated by writing a number called index number or sub-
F statement 2; script. For example:
Salary [10]
Represent the salary of 10h employee. While the complete set of values is referred to
else as an array. The individual value are called elements. Arrays can be of any variable type.
The ability to use a single name to represent a collection ofitems & to refer to an item
statement 3;
by specifying the item number enables us to develop concise & eficient program.
Programaing in JAVA|17
16 | Navbodh B.C.A. Part-I Saral Adhyayan

Types of Array Memory Representation of 2D Array;


int a = new int [2] [2]:
1. ONE-DIMENSIONAL ARRAY: A list of items can be given one variable name
called single subscript variable or one-di
using only one subscript and such a variable is 0 1 2
mensional array.
o (0,0 (0,1 (0,2)
For example:
x[1], x [2]. [n]
int number []= new int [5] 1(1,0 (1,1) (1,2)
Memory representation ofone-dimensionalarray: 2
(2,0) 2,1) (2.2)
number [0] method in Java Explain with example.
?
Q.9. What is class and allows the data to be
data and its associated function. It
umber [1] Ans. A class is a way to find abstract
When defining a class we are aeating a new
from external use.

umber [2
hidden. If necessary like any other built-in-datatype.
datatype that can be treated together a group of logically related
Class provide
for
convenient method packing
In Java the data items called field and function
number[3] data items and function that work
on them.
are called method.
define datatype with a tempiate that serves to
number [4] DEFININGA CLASS: Aclass is a definition
user
is
define its properties. of class
The basic form
Class class-name [extends superclass name]
-

Initialization of one-dimensional array: The step put values into the array. This
[Variable declaration];
process is known as initialization. This is doneusing
the array subscript as shown:
[Methoddeclaration];
Array name [subscript]=value
Ex keyword e x
Here class-name & super class-name
is any valid Java identifiers. The
Number [0]=35; name class are extended to the class name

Number [1]-40; tends indicate that the properties of superclass


-

class. This concept is known as inheritance.


METHOD: A class with only data fields
has no life. The object created by such a
declared inside the body of class but
respond
class can't to any message. Methods are
Number [4]-19; immediately after the declaration of
variable. The general form of method
declaration:
Java creates arrays starting with 0 and end with a value one less than the size specified.
name> (parameter-list)
Other way to initialization of array: type< method
Typearray name []={ list ofvalue};
Ex method body;
intn= {35, 40, 1, 2, 51}
Method declaration have four basic part:
2. TWO-DIMENSIONAL ARRAY: Alist
of item can be using two subscript (1) The name of method
called two-dimensional array Creating two-dimensional array we must follow the same step (2) The type of the value the method returna
ofsimple array. For example.:
(3) A list of parameter
int A[][]
A=new int [3]14]; (4) The body of method.
Or Ex.
intA[][]=new int [3]I4); Class rect
This statement createa table that can store 12 integer values.
Initialization of two-dimensional array: intlength;
int width ;
int table [ ][]={{0,0,0},
We can also initialize two-dimensional
{1,1,1}} void get data (int x, int y) / method of class
array in
inttable []]= { length=x;
(0,0,0 width=y
{1,1,13
Programming in JAVA|19
18 Navbodh B.C.A. Part-I Saral Adhyayan
buffer. Explain
Q.10. What is an object? Write the features of Java. Java. lang. string and Java. lang string
entities in an object- oriented system. Q.12. Compare the class classes: () Java lang.
Math
Ans. Object: Object are the basic runtime with example any one method from each of the following Java util staring Tokenizer
a table of data or any item that the Character (iv)
They may represent a person, a place, a bank-account, Java lang.
user-dcfined datatypes such as vectors and (ii) Java awt. Graphics (ii)
program may handle. They may also represent
lists. Any programming problem is analyzed in terms of object and the nature of communi
(v) Java lang. Integer. and string buffer class with
suitable erample.
Or, Explain the string characters. The casiest way to
cation between them. Program objects should be choosen such that they match closely with Ans. STRINGS : Strings represent a sequence of

the real-world objects. in java is by using a character array.


representa sequence ofcharacter
When a program is executed, the objects interact by sending message to one another.
Once a class has been defined, we can create any number of objects belonging to that class. x [0] 0]
Each object is associated with the data of type class with which they are created.
A class is thus a collection of objects of similar type. For example, Mango, Apple,
Orange are members of the class fruit. Classes are user defined datatypes and behave like [O]
the built-in types of a programming language. For example, if fruit has been defined as a
class, then the statement -x[1] [3]
Fruit mango; x [1]
will create an object mango belonging to the class fruit:
Features of JAVA: (See the Q.No. 4)

example.
Q.11. Write the difference between nested class and inner class with suitable
x2
Or, Explain inner classes and nested classes with example.
Ans. 1. Anon-static class within another class is called inner class. [2] [2]
A static class within another class is called nested class or static inner class.
Fig. Variable size arrays
For example:
Class outer Char Char Array []=new char [4]
Class inner Char Array [0]= 'T;
Char Array [1]= 'a';
Char Array [2]= 'v';
Static class nested Char Array [3] 'a";=

: In Java, strings are class objects and implemented using


two
STRING BUFFER
classes, namely, string and string buffer. A Java string is an instantiated object ofthe string
reliable and predictable. This is
class. Java strings, as compared to C strings, are more
2. Inner class object must be created is not a character array and is not
using outer class object. basically due to C's lack of bounds, checking. AJava string
Nested class object is created without using other class String may be declared and created as follows
object. NULL terminated.
For example String string Name;
public class program
String Name New string ( "string ")
=
;

public static void main Example:


{ String first name;
public static void main (String args[]) First name =New string ( "Anil") ;
This two statements may be combined as follows:
Outer 0 new outer 0: String first name = New string ("Anil");
Outer.Inner i-0.new Inner O; STRING METHODS :The string class defines a number of method that
allow us to
Outer.nested n=new outer.nested 0; tasks.
accomplish a variety of string manipulation
In below table some of the most commonly used methods are shown:
Method call Task Performed
3. Inner class object holds the
reference of Convert the string Sl to all lowercase
Nested class object donot hold reference outer class object that has created it. s2 S1.toLowerCase;
and stored.1 of outer class object. Unless explicitly passed s2 S1.toUpperCase; Convert the string S1 to all uppercase

s2 Sl.replace ("X', 'Y") Replace all appearances of X with Y.


Programming in JAVA|21
20 | Navbodh B.C.A. Part-1I Saral Adhyayan
While string
buffer is a peer class of string.
For example: STRING BUFFER CLASS : String that can be
length, string buffer creates strings of flexible length
Prog strings of fixed in the
-

insert characters and sub-string


creates
We can
classstringsorting modified in terms of both length and content.to the end.
middle ofa append another string
string, or
shown in the
used in string manipulations are
static String name [ ] =("Bombay", "Chennai", "Raipur", "Jagdalpur", Some of the methods that are frequently

Bhilai"; below table Task


public static void main(String arg[|) Method
S1.setchar At (n, 'x')Modifies ther"
character to x.

end.
S1.append ($2) Appends the string S2 to S! at the
int 1=name.length; Insert the string S2 at the position n of
S1.insert (n,$2)
String t=null; the string S1.
for(int i =0;i<=l;it+) SI.setLength (n) sets the length of string SI to n, ifn<S1.
length() Si is truncated. If n>S1.length()
for(intj-0j<=1-1;j++ Sl is truncated. If n>Si.length(O zero are
{ added to SI.
if(namej+1].compareTo(name D])*0)
For example: Manipulation of strings:
class StringMain
tname[i;
name[j]=name[j+1]; public static void main(String arg)
namelj+ 1]= t
StringBuffer str
=

new stringBuffer("Object language")


System.out.printin("Original string," + str);

IInserting a string in the middlee


System.out.printin("Sorted string areln"); intpos str.indexOff"language"]:
str.insert(pos,"oriented");
for(int i=0;i<1;i++) System.out.println("Modified string;" +str);
IModifying characters
System.out.println(namefi);
str.setcharAt(6, '-);
System.out.println("String now'"+str);
WAppending a string at the end
str.append("Improvessecurity");
System.out.printdn("Appended string" str)
+

E1WINDOWsisystem32icmd.exe
E:neujavac StringDeno -java
Differentiate nested & inner class
E:neujaua StringDeno Q.13. What do you mean by wrapper class ?
Original String:0bject language
Length of string 15 with example.
character at position:1is0 Or, What are Wrapper Classes ? Explain.
Character a t p o s i t ion:2isb
haracter at position:3isj
Ans. WrapPper classes: Wrapper classes used for conerting primitive
are datatypes
haracter at position:4ise
Vectors can not handle
haracter at posit ion :5isc
haracter at position:6istt
into object types. Wrapper classes contained in Java.lang package.
haracter at position:7is
primitive datatypes like int, float, long, char and double.
haracter aE position:8isl
haracter at position:9isa Wrapper classes for converting simple types:
character at position:10isn
Character at poSition:11isg Simple types Wrapper class
E a r a C t e r at posit ion:12 isu
character at posit ion:13isa boolean Boolean
Character at position:14is4
char Character
character atposition:15ise
Hodified string: Ohject Orientedlanguage
nOU:Object-OPientedi alanguage double Double
Anpended string: Qbiect-Orientedlanguage float Float
innroves secUritu.
int Integer
long Long
Programming in
JAVA |23

22 Navbodh B.C.A. Part-M Saral Adhyayan


return sum;
Example:
Wrapper class: static void printline)
import java.io.";
class invest
for(int i- 1;i<
=
30;1+ +)
public static void main(String arg[])
System.out.println("=");
Float pa=new Float(0);
Floatinsnew Float(0); System.out.println (" ");
int numyear = 0;

try

DatalnputStream in = new DataInputStream(System.in); OUTPUT:


System.out.println("Enterthe principal amount");
System.out.fush0; TE:WINDOWStsystem32\cmd.exe X
String ps=in.readlLine); Eneujavac sinple1.jaua
pa =Float.valueOf{ps);
System.out println("Enter the interest rate");
System.out.fush);
E:neujava sinple1 5080 34
simple intrest600
String intrest=in.readLine0;
ins-Float.valueOfintrest); ENnew
System.out.println("Enter the no ofyear");
System.out.fush);
String yearString=in.readLine);
numyear= integer parselnt(yearString);

catch1OException e)
Note: For difference, see the Q. No. 11.
Q.14. Explain the utility of Vector with suitable example.
System.out.println("7O Error");
System.exit(1); Ans. C and C++ programmers will know that generic utility function with variable
situation.
arguments can be used to pass differ ent arguments depending upon the calling
float value= Java does not support the concept of variable arguments toa function. This feature can be
loan(pa.floatValue),ins.float Value),numyear); achieved in Java through the use of"Vector class.contained in Java util package This class
PrintineO;
can be used to create a generic dynamic array known as vector that can hold object of any
System.out.printin("Final value ="+value);
PrintineO; type & any number. The object do not have to be homogenous. Array can be easily imple-
mented as vectors. Vectors are created like arTay as follows
static float loan(float p,float r, int n) Vector intvect=new Vector (): || declare without size
Vector list = new Vector (3 ):| declare with size
int year = 1; Vector contain a number of advantage over aray.
float sum=p; (1) Itis convenient to use vectors to store objects.
whileyear=n) (2) A vector can be used to store a list of objects that may vary in size.
(3) We can add and delete object from the list.
sum sum(1+r); Amajor constraint in using vector is that we can't directly store simple data type in
a vector we can only store object. Therefore we need to convert simple types to objects. This
year= year+1;
can be done by using wrapper class.
JAVA |25
Programming in
24 Navbodh B.C.A. Part-1 Saral Adhyayaa
Important vector methods
OUTPUT
importjavautil E:WINDOWSIsystem32icmd.exe
Ciass vect

public static void main (String args{]) Eneujavac sort no.java


inti; Enewjava sort no
Vector list new Vector 0
int 1 - args. length;
for(i 0; i=l;it+)
list addElement(args[i]):

list.insertElementAt("cobol", 2);
int size= list. size0; E:new
String listATayl=new String[size]
list.capyinto(listArray);
System.outprintin (List ofLanguages");
fori 0 ; i <= size;i + +)

System.out.printin(listArrayli]); declared and accessed ? Write a program to


Q.16. What is an array ? How is it
multi-dimensional array.
generate the following

Output:
Java vect cc++vbjava vb.net htnl 6 9
Lis ofLanguages Ans. Array: See Q. No. 8.

Program:
class pattern
Cobol
Java {
Eiml public static void main (String args [)
Q.15. WAP in Jsva to print firt n termsofthe following series using do while loop: int patt [1 0= new int [4] 0:
Ams. Class fibo
1,1,2,3,5,8 patt [0]= new int [1];
patt [1] = new int [2];

public satic void main(String args) patt |= new int [3];


patt (3]= new int [4];
int i- 1, a=0, b= 1,c; int ij.k= 0;
for (i-0; i<=4; it+)
System.out.println("Fibonacci series are:"); for G-0; j=i;jt)
System.out.printin(a);
System.outprintin(b);
wihilei10) patt i] ]=k;
kt
Catb
System.outprintin (¢); for (i-0; i<=4; it+)
b
as for (-0; j=it1;jt+)
i-i+1; System.out.println (patt [il G+ "**"):
System.out.printn 0
26 NavbodhB.C.A. Part-l Saral Adhyayan Programing in JAVA|27

Output: System.out.println ("*" +a[i] G]);


2
System.out.println (" ");

Q.17. Explain string buffer class. Write a program to generate output: "Raipur System.out.println ("Matrix B'");
is part of cG" then replace word "is" by "was" to generate the sentence "Raipur was for(inti= 0; i<=2;i++)
part of CG", by the use of string buffer class.
Ans. String Buffer Class : (See Q. No. 12) for(intj =

0;j< =2;j++)
Class string modify {
System.out.println ("*"+b[i] G]):
public static void main (String args [)
c[O] [o] =0
string arg "Raipur is a part of CG"; for (int i= 0; i<=2; i++)
string search="is";
string sub= "was"; for (intj =0,;j < =2;j ++)
string result="";|
int i, [il G]=alil i]+ b [i] ül:
do
{
Systemout.println (org);
i-org.index of (search); System.out.println ("Matrix C")
if(il=-1) for (inti =0;i<=2;it)

result-org.substring (0,); for (intj = 0;j< =2;j++)


result-result+sub; {
result result+org. substring System.out.printin ("* "+cfi] G):
(i+search.length 0);
argTesult;
System.out.println (" *);
while (il=-1);
Q.19. Write a Program to Search the element in one dimensional array.
Output: Raipur is a part of CG Ans. Package com.naveen;
Raipur was a part of CG Import java.util.Scanner;
Q.18. Write a program for addition of Public class LinearSearch
two-dimensional array.
Or, Write a Java program to add any two matrix.
Ans. public static void main (string[] args)
class matadd
{ int n, key, pos;
public static void main (String arg [ 1) int a[]=new int [100]:
Scanner S=new Scanner (System.in);
inta[][]={ {1,3}, {4, 5}}; System.out.println ("Enter values ofn");
int b[][]={ {4, 6}, {7,9}}; n-Integer.parseint (s.next() );
int c [][]=new int [2] System.out.println ("Enter" +a+"values");
System.out.print In (Matrix for (int i-0; i<n; it+)
for (inti=0; i<=2;i++) A");
ali] s.nextInt ();
for (intj 0;j<-2;j ++)
System.out.printin ("Enter the no. to be searched");
key-Integer.parseInt (s.next () );
Programming in JAVA |29
28 | Navbodh B.C.A. Part-I Saral Adhyayan
in ascending order
pos-linears (key,n,a); Q.21. WAPin Java to sort element of one dimensional array
If (pos-0) Ans. Class sortele

System.out.printin ("search unsuccessful"); public static void main(String args[})

int a[ ] ={5,6,1,1,15,16,20),
else
int 1,ij;
at"+pos); System.out.println("Element of array'");
System.out.printin ("key found position for(i 0;i<-a.length;i+ +)

System.out.println(a[i]);
private static int linear (int key int n,int []a)
for(i 0 ;i=a.length;i+ +)
for (int i-0; isn, it+)
forgi=i+ 1;j<=a.lengthj+ )
if(a [i]=key)
ifalil>aj])
return i+1;
inttemp=a [i]:
ali]= a 0

Return 0;
aj]= temp:

Enter value of n
}
Output System.out.println("After sorting element of array);
for(i =03 i<=a.length; i+ +)
Enter 5 values
17 29 600 201 310 System.out.printin(a[i]);
Enter the no. to be searched
600
Key found position at 3.
Q.20. Write a Java program for prime number or not of any given number. OUTPUT:
Ans. Import java. io.";
class test prime No.
T E:WINDOWSlsystem32\cmd.exe
public static oid main (string args[)
E:neujavac sort no.java
int prime-0, i, no; E: neujava sort no
DatalnputStream in= new DataInputStream (System.in);
system.out.print ("Input Any Number:");
no-Integer.parselnt (in.readLine0)
for(i-2; i<no; it+)
if(noli= 0)
prime=
} E:new>
if(prime==0)
system.out.printin ("Number is Prime");
else
system.out.printin ("Number is not Prime");
}

You might also like