Java Unit 1
Java Unit 1
Java Unit 1
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.
=
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
(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
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
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
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";=
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
=
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
try
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
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 + +)
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];
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)
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");
}