Java Programming (9113)

You might also like

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

LIST OF EXPERIMENTS AND RECORD OF PROGRESSIVE ASSESSMENT

Date of Assess Sign. of


Expt Title of Experiment Page Perforrnan Date of ment Teacher
No. No. Submission Max. and
ce Marks 10 Remarks
01 Know your Laboratory work of Java
Programming.
To implement simple programs based
02 on operators, loop, decision
statements, and type casting.
03 To implement programs to define a
Class and instantiate its object.
04 To implement programs based on
Constructor and Method Overloadit}g.
To implement programs using
05 Wrapper Classes and Command Line
Arguments
06 To implement programs using String
Class and StrinRBuffer Class.
07 To implement programs based on
Arrays.
08 To implement programs using Vector
Class.
To implement programs based on
09 Single Level and Multilevel
Inheritance
10 To implement programs to
demonstrate the use of interfaces.
11 To implement programs based on
Method Overriding.
12 To implement programs based on
Exception Handling
To implement programs based on
13 Multithreading and Synchronization.
To implement a program based on
14 and User-Defined and Pre-Defined
Packages.
To implement programs to design a
15 simple applet.
To implement programs to design an
16 applet using Graphics class.
To implement programs to
17 demonstrate the use of 110 Streams.
18 Min i-Project. c
Total Marks ........ a ••••
Average marks out of
10 ............ * To be transferred to proforma A-2 of CIAAN - 2006

(The curriculum of this subject is referred and the above list of experiments is finalized to achieve the desired objectives)

EXPERIMENT No. 1

Know your Laboratory work of Java Programming.

1.0 Title:

2.0 Prior Concepts:

Concepts of Object-Oriented Programming.

3.0 New Concepts:

Proposition 1: Laboratory Experiments

Laboratory Experiments are expected to develop intellectual skills, motor skills and attitudes in students.

Concept Structure:

Laboratory
Experiments
Develop

! ~ !
Intellectual Motor Attitudes
Skills Skills Proposition 2: Logical Thinking

Logical Thinking is developed in students through systems approach, content analysis and sequential planning of laboratory work.

Concept Structure:

Lead to

Logical Thinking

4.0 Learning Objectives:

Intellectual Skills:

1. To understand the concept of Java programming.

2. To understand the various features of Java.

3. To understand the use of different jdk tools.

4. To understand the structure of Java program.

5. To understand editing and execution of Java program.

Motor Skills:

1. Ability to handle computer peripherals properly.

2. Ability to use jdk tools.

5.0 Stepwise Procedure:

/0 Read the learning overview carefully.

• Usten to the lecture given by the teacher about importance of subject, curriculum philosophy, graphical structure, skills to be developed, information about computers and its peripherals, devices, information about writing programs, compiling and executing programs, and method of continuous assessment and tentative plan of work in laboratory.

III Visit the lab, read the contents on your PC, open any text editor(ex. Notepad, JCreator, etc) to write the java programs, check the type of operating system of your pc and folder in which JDK is installed, and then set the path of JDK.

E.g. Steps for editing and executing java program:

1. Run notepad.

2. Write java source code in notepad.

3. Save the file as filename.java and filename should be same as classname having

main method.

4. Then, in C:\Program Files\java~dk1.3\bin\ path save the file.

5. Open MS-Dos prompt.

6. Specify the path of filename such as C:\Program Files~ava\jdk1.3\bjn\ at the dos prompt.

7. For compilation, type javac filename.java at the dos prompt.

8. Then, for execution, type java filename at dos prompt

Experiment No.1

6.0 Observations:

Read the options provided by different jdk tools. Ex:

Write the options provided by jdk tool (java) java:

7.0 Conclusion:

Understood the use and read the options provided by ..

... (javac I java I javap I jdb I javadocl javah) jdk tools.

expenment NO.·\

8.0 Questions:

Write answers to Q ..... Q ..... Q ..... (Teacher shall allot questions)

1. Describe bytecode and JVM.

2. State two points about the importance of java programming language w.r.t. platform

independence, portability, security and internet programming.

3. State the different tools available in JDK.

4. Why Java is called truly object-oriented?

5. "Different platforms required to have different type of JVM. ?"YES or NO? Give reason.

6. List the different versions of JDK available in market

7. Compare Java and C++ w.r.t pointers and multiple inheritance.

8. State the use of automatic garbage collection in Java.

9. Compare JVM and JIT(write two parameters).

10. How java programs can ensure "Write-Once Run-Anywhere" (WORA) philosophy?

11. What is API? Explain.

12. State the process of implementing and executing java program.

13. Describe the history of java.

14. State the different applications of java.

15. Describe JSL.

(Space for Answers)

.JdVd rilJ~tCiuuunly \::::J ~ I~}

Experiment No.1

(Space for Answers)

Signature of Teacher:

Marks:

EXPERIMENT No. 2

1.0 Title:

To implement simple programs based on Operators, Loop Control Structures,Decision Control Structures and Type Casting.

»> if-else for (lype)

instanceOI do-while switch expression

2.0 Prior concepts:

® Class, variables, constants, keywords, data types. • Operators and loops of C++.

3.0 New Concepts:

Proposition 1: Data Types in Java

Every data in Java is associated with a data type which is known at compile time. It helps data to work with related types.

Data types in Java are of two kinds:

1. Primitive(built-in) Data type :

There are eight primitive data types in java language and can be classified as:

• Boolean data type: boolean

• Numeric data type: i. Integer data type: byte, short, long, int Ii. Floating data type: float, double

• Character data type: char

2. Non Primitive(reference) Data type:

• Arrays

• Classes

It Interfaces

Concept Structure:

Primitive (built-in) Data Type Non-Primitive(reference) Data Type

Primitive Data Types Storage
byte 1 byte • Arrays
short 2 bytes
int 4 bytes • Classes
long 8 bytes
float 4 bytes • Interfaces
double 8 bytes
char 2 bytes
boolean 1 bit cxperunem I'W.':

Proposition 2: Structure of java program

Structure of Java program consists of different sections which forms the definition of java program.

Concept Structure:

Documentation
<I/--
Package statements
Import statements
Interface statements ,,-
Class definitions
Main method class
{ ...--
main method definition
} Suggested

-+- Optional

Essential

where

Documentation Package Statement - Import Statement Interface

Class Definitions Main Method Class

A set of comment lines.

A set of classes are defined. Similar to # include of C++ .

It includes group of method declaration. Primary elements of Java program. Every java stand-alone program.

Proposition 3: Main Method Class Definition

Syntax: class class-name

{

[data-type member-name;]

[return-type method1 (parameter-list) {

/lstatements;

}]

public static void main(String args[]) {

Ilstatements;

}

}
where class is a keyword
class-name is a name of the class
data--type is Primitive or Non Primitive type
member-name is a name of a variable
return type is data-type of a returned value.
method1 is name of a method
parameter list is a list of parameter cxpenrnent NO.L

Proposition 4: Operators in Java

An "Operator" is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables.

Java supports two new operators as compared to C++ such as:

1. Bitwise unsigned right shift operatorp->»):

Bitwise unsigned right shift operatorfills vacated bits with zeros while the Bitwise signed right shift (») operator fills vacated bits with signed bit.

Ex. a=2 I 0 I 0 I 0 I 0 I 0 I 0 11 I 0 I

a»>21 0 I 0 I 0 I o! 0 I 0 I oj 0 I

Ex. a= -2 11 11 Ii! 1! 1111 11 0 ! a»>2 I o! 0 1111 11 11 11 11 I

2. instanceOf operator:

instanceOf operator returns true if object belongs to classnarne,

Syntax: .i' . . ,i

booleanb=ioblectinsta nceOfclE!~snam~;

'~ ."

Concept Structure:

e.xpenrnem 1'10.':::

Proposition 5: Decision Control Structures

Decision Control Structure is a structure which executes a set of instructions depending on certain conditions. The different types of decision control structures are:

1. if statement:-

if(test expressions-f) {

staternent-t ; }

statement-x:

Syntax:

2. if -else statement:-

Syntax:

if(test expressions-1) {

}

else

{

statement-1 ;

statement-2;

}

3. switch statement:

switch(expression) .

{ . .

. . caseexpressiorlst:statemel1t -1;

. ···.».\i. ...•.... ··.·..break·i> .•

. case!3xpressi9ns2:.~tate~ent-2;

.•. ··ii<i· .•• ·•·· . break; ..

. . "." ''-':'. ,,:.~.-:- .

-:... 4"'"

,". -.: :-\"",': ..... :-. ",' ~ ',: ., .:, :;:.:.:>, .. ,':-::::,\-:,-,.::<"

. ca ... #~tirll~~jITn .••..•. n .••.•.. ·.· •... • •. · .•.. ·s:· .• ·t •.. tat.rta .•. e.Je.a.em··.·~.··.·.e;. en •.•. · .•.••• t·.n ...•.•.. , .. '] ••. - .....•.... ". 'N

·defaUlt· .. •.... •

Concept structure:

Decision Control Structures

switch statement

if-else statement

experiment NO.L

Proposition 6: Loop Control Structures

Loop Control Structures are used when it is necessary sometimes to execute some statements repeatedly and also sometimes, it requires to skip execution of statements.

The different loop control structures are:

1. for Loop:

for loop is used to execute a set of statement number of times .

• }or(initialization;Coijnt(?fCOndition; ·incrementlgecrement counter)

.{ .

statement-n;

2. while Loop:

while loop executes condition before executing any of statements in its body.

statement-1; . statement-2;

Syntax:

initialize loop counter while(test counter)

{

statement-n;

increment loop counter;

}

3. do-while Loop:

do-while loop executes the condition after execution of statements in its body.

Concept Structure:

Do-while Loop

Proposition 7: Type Casting.

Type casting is used for converting value of one type of variable to another type. Type casting can be used to round-off a given value to an integer which retains the fractional part of result. The process of converting one data type to another is called as type casting.

Syntax: (type-name )expression

type variable= (type) variable 2

where, type-name is one of standard data types.

int b,c;

float a=(float)b/c;

4.0 learning Objectives:

Intellectual Skills:

1. To understand java program structure and various operators available in java.

2. To understand various decision and loop control structures in java.

3. To analyze the problem, decide and evaluate conditions.

4. To understand concept of type casting.

5. To identify syntax for given program.

6. To select appropriate control statements.

7. To study different errors. Motor Skills:

1. Ability to handle computer peripherals properly.

2. Ability to edit and debug programs.

5.0Sample Program:

Implement a program to illustrate the use of java operators and display its result.

class ExpressWrap

{

int a,b,c,d,e; float x,y;

ExpressWrap(int p, int q, int r, int s, int t, float u, float v) {

INariable declaration

a=p; ,

I::xpenment No.2

b=q;

c=r; d=s; e=t; X=U; y=V;

}

void checkt) {

int ans1=a * b + c /d; int ans2=a * (b + c) / d float ans3=a / c;

float ans4= (float)a / c; float ans5=a / y;

int ans6=a % c; IIModulo Operations

float ans7= x % y;

boolean bool1 =a > b && c > d ; ilLogical Operations

boolean bool2=a < b && c > d ;

boolean bool3=a < b \I c > d ;

boolean booI4=!(a - b = = c);

System.out.println(UOrder of Evaluation"); System.out.println("a * b + c / d ="+ans1); System.out.println("a * (b + c) / d ="+ans2); System.out.println(UType Conversions"); System.out.println("a I c ="+ans3); System.out.println("(float)a / c ="+ans4); System.out.println("a I y ="+ans5); System.out.println("Modulo Operations"); System.out.println(Ua % c ="+ans6);

System.out.println("x % y ="+ans7); System.out.println("LogicaIOperations"); System.out.printin("a> b && .c > d ="+booI1); System.out.println("a < b && c> d ="+booI2); System.out.println("a < b II c > d ="+booI3); System.out.println("!(a - b = = c )="+booI4);

System .out.println("Bitwise Operations"); System.out.println(Ud«2="+d«2); System.out.println("e»2="+e»2); System.out.println("e»>2="+e»>2);}

IIOrder of Evaluation

IIType Conversions

}

public static void main(String args[]) {

liMa in method

ExpressWrap e = new ExpressWrap{1 ,5,4,2,6,3.0,8.0);

e.checkt): //Invoke check method

}

}

cxpenmern 1'10.':

Output: Students should write the output

6.0 Implementation:

A] Attempt the following programs.

1. Define a class having three numbers as data members. Initialize and display the greatest of the three numbers.

2. Define a class having one number, N as a data member. Initialize and display prime numbers from 1 to N.

3. Define a class having one 3-digit number, num as data member. Initialize and display reverse of that number.

Result: Students should attach printouts of the program code taken on A-4 sheet.

B] Teacher can allot practice programs to students. (These programs should not be included for assessment)

1.

2.

t:::xpenment NO.L

7.0 Conclusion:

Implemented programs based on operators ..

(arithmetic / bitwise! instanceOf ! relational/logical! increment! decrement) and decision

control structures (if / if-else / switch),

loop control structures , (for/ while/do-while)

to display: 1 .

2 .

3 .

8.0 Laboratory Exercise:

Students shall execute the following code and write the answers for the same during lab hours.

Sr.no. Question Answers
01 Find error in the following code & rectify it.
int a=5;
if(a>O)
int b=a-B;
System.out.println(b);
02 What will be the output of following code
segment?
int i=20;
int j=55;
int z=O:
z=i<j?i:j;
System. out. println ("the value is" +z):
03 How many times the string "hi" will be
printed in the following list of statements?
Explain.
short c= 11 ;
for(c++;c++!=O;c++)
System.out.println("hi");
04 Find error in the following code & rectify it.
long x=1;
switch (x)
{
case1: System.out.println("1 ");
case2: System.outprintln("2");
case3: System.out.println("3");
} cxpenrneru 1'10.'<:

9.0 Questions:

Write answers to Q ..... Q" ... Q ..... (Teacher shall allot questions)

1. How to declare symbolic constants in java?

2. What are labelled loops?

3. State the rules for the naming conventions of identifiers in java.

4. State the main difference between » and »> operator.

5. What are the default values of different primitive types?

6. Explain why main method is declared as public and static.

7. State the use of instanceOf operator. Specify its precedence and associativity.

8. What is a literal? State the different types of literals in java.

9. Differentiate between the following two statements i. Student s1;

ii. Student s2=new Studentf);

where Student is a class

10. Give different scope of variables.

11. What is token? List the different types of tokens.

12. Is 'void' a data type in java?Justify.

13. Differentiate between the following two statements i. boolean b=(100 > 5) II (6 * 8 > 5);

ll. boolean b=(1 00> 5) I (6 * 8 > 5);

14. What is type casting? When it is used? Give its syntax.

15. What is type conversion? Give its syntax.

(Space for answers)

y:dVd rIVSl~dllJlI1UI~ ~t}. I OJ/

expenmern NO.':

(Space for answers)

Signature of Teacher:

Marks:

cxpenmeru I~O.')

EXPERIMENT No. 3

1.0 Title:

To implement programs to define a class and instantiate its object.

variable declaration

Class definition

2.0 Prior Concepts:

1P Class, variables, and methods. I) Data Types in Java.

• Operators and Control Statements in Java.

method declaration

'---"--"~

3.0 New Concepts:

Proposition 1: Class

A class is a user-defined data type which groups data members and its associated functions together. Data is encapsulated in a class by placing data fields and methods inside body of class definition.

Proposition 2: Static Members

Static Members are referred to as class members which define a member common to all the objects or instances of the class and accessed without using a particular object of the class. Static variables and static methods are also known as class variables and class methods as these members are associated with class itself rather than objects of the class. Static methods are called using only class name. Static methods call only other static methods and access only static data.

expenfnem I'IIU.'}

static return_type method_name(parameters}

{

IIstatic method

Ex.: class class_name

{

static data_type member1_name;

IIstatic variable

I/statements;

}

}

Proposition 3: Creating Objects

"Creating an object" is referred to as instantiating an object and objects of specific class are created using new operator which returns reference to that object. An object in Java is a variable which is assigned a object reference. Classes create objects and objects use methods to communicate between them.

Example e;

Ex.:

~

e=new ExampleO;

Proposition 4: Constructor

Constructor is a special type of method which enables to intialize an object when it is first created. It has the same name as the class in which it is declared. It does not specify a return type not even void.

..)QVd rluylclltllJliU!a \~, I.)}

I::xpenmem NO . .)

General Concept Structure:

Class definitions
variable declaration;
lIinstance variable
Ilstatic variable
method declaration;
Ilconstructor method
Ilstatic method 4.0 learning Objectives:

Intellectual Skills:

1. To understand declaration of class and creating objects of class.

2. To understand the use of static members.

3. To understand concept of constructor method.

4. To identify the syntax for given programs.

5. To study different errors and write programs for given problem statement. Motor Skills:

1. Ability to handle computer peripherals properly.

2. Ability to edit and debug programs.

5.0 Sample Program:

Program to define a class Rectangle having data members length and breadth. Initialize and display data for two objects of class Rectangle and calculate and display area of Rectangle.

import java.lang. *; class Rectangle

Ilimport language package

{

int length ,breadth; static int count=O; RectangleO

{

Ilinstance variable

Ilclass variable to count no. of objects created Ildefault constructor

length=breath=O;

t:xpenrllem 1'110 . ..)

}

Rectangle(int X, int y) {

Ilparameterized constructor

length=x; breadth=y; count++;

}

void display() {

Ifmethod to display length and breadth

System.out.println("Length of Rectangle="+ length); System.out.println("Breadth of Rectangle="+ breadth);

}

int rectAreaO

{

Ifmethod to calculate area of rectangle

int area=length*breadth; return(area);

}

public static void main(String args[]) {

flmain method

Rectangle r1 =new Rectangle( 10,20); Rectangle r2=new RectangleO;

r l.displayt);

int area1 =rt.rectxreat);

System.out.println("Area1 of Rectangle="+ area1); r2.length=15;

r2.breadth=25;

int area2= r2.length* r2.breadth; System.out.println("Area2 of Rectangle="+ area2); System.out.println("Object count="+ count);

}

}

Output: Students should write the output.

expenment NO.;:!

6.0 Implementation:

A] Attempt the following programs:

1. Define a class Student with four data members such as name, roll no.,sub1, and sub2.

Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

2. Define a class Circle having data members pi and radius. Initialize and display values of data members also calculate area of Circle and display it.

Result: Students should attach printouts of the program code taken on A-4 sheet.

B] Teacher shall allot practice programs to students. (These programs should not be included for assessment.)

1 , .

2 .

6.0 Conclusion:

Implemented programs based on class and instantiating its object to display:

1 .. total marks: and percentage: , scored by student ..

2 .

(Ex: total marks)

7.0 Laboratory Exercise:

Students shall execute following code and write answers for same during lab hours.

S.N. Question Answers
01 What will be the output of following code
segment?
class StaticMember
{
static int m=O;
static int n=O;
public static void main(String args[])
{
int m=1 0;
int x=20;
System.out.printtnf'm+n=r+rn+n):
x=rn+n;
System.out.println("x="+x);
}} expenmem NO."

02 Find error in the following code and rectify it

class Book

{

int book_no;

String book_name; Book(jnt x, String y) {

book jio=x; book_name=y;

}

void displayf) {

System.out.println("Name of Book ="+ book_name);

System.out.println("No. of Books ="+ book_no);

}

public static void main(String argsl]) {

Book b1=new Book (20,"Balguru"); b1. Display ( );

}

}

03 Find error in the following code and rectify it

class Arithmetic

{

int add(int x, int y) {

returnix+v):

}

int sub(int x, int y) {

return(x-y);

}public static void main(String argsO) {

System.out.println(add(10,20»; System.out.ptintln(sub(20, 1 0»;

expenrnent I'IO.S

04 Write the output and also specify the value of count.

class BookDemo

{

int bjd;

String b_name;

static int count; BookDemo(int i, String n) {

b jd=l; b_name=n; count++;

}

void showt) {

System.out.println("Name of Book ="+ b_name);

System.out.println("No. of Books ="+ b jo): }

public static void main(String args[]) {

BookDemo b1=new BookDemo(10,"Java"); BookDemo b2=new BookDemo( 11,"OS"); BookDemo b3=new BookDemo(10,"WTj; BookDemo b4=new BookDemo(10,"NM"); BookDemo b5=new BookDemo(10,"WD"); b t.showt);

oz.showt):

b3.showO;

b4.showO;

b5.showO;

System. out. println("Object count=" +count);

} }

cxpenrneru l'1U.,)

8.0 Questions:

Write answers to Q ... " Q ..... Q ... " (Teacher shall allot questions)

1. Define static member. Give its syntax.

2. What is access specifier? State the different types of access specifier.

3. What are objects? How are they created from the class.

4. When do we declare a member as static?

5. "A static member method can access only static members". Justify.

6. Specify the use of public and private access specifiers.

7. Explain why main method is declared as public and static?

8. Differentiate between the following two statements: i. Student s 1 ;

ii. Student s2=new Studentt);

where Student is a class 9. Give different scope of variables.

10. Illustrate the use of 'this' keyword w.r.t Instance variable hiding.

11. What is the use of new operator? Is it neccesary to be used whenever object of the class is created? Why?

12. How to invoke methods by using objects of the class? Justify.

(Space for answers)

t:xpenment NO.j

(Space for answers)

cxpenrneru I'IU.,)

(Space for answers)

Signature of Teacher:

Marks:

experiment 1'10."1

EXPERIMENT No.4

1.0 Title:

To implement programs based on Method and Constructor Overloading.

class XYl int add(int.int)

( in! a; float add(float.ftoat)

XYl()

{}

XYZ(intx)

(aA; ) )

2.0 Prior Concepts:

III Class definition.

It Object Creation in java.

* Method and Constructor definition in Java.

3.0 New Concepts:

Proposition 1: Overloading

Overloading means having more than one form. Overloading refers to the use of the same thing for different purposes. Java allows Method Overloading and Constructor Overloading.

Concept Structure:

Proposition 2: Method Overloading

"Method Overloading" means to define different methods with the same name but different parameter lists and different definitions. It is used when objects are required to perform similar task but using different input parameters that may vary either in number or type of arguments.

Ex.: int add(int a, int b)

/lprototype 1

int add(int a, int b, int c) IIprototype 2

double add(doublex, double y) IIprototype 3

(double X, double y)

Note: Method's return type does not play any role in overloading.

Proposition 3: Constructor Overloading

"Constructor Overloading" means to define various constructors but with different signatures. A class can have more than one constructor (overloaded, not overridden).When an object is created, one of the constructors is executed depending on the order, number and type

of arguments used in definitions.

t:;/(penrTlem 1'11004

Ex.: class Simple
{
int x;
Simple{)
{
x=O:
}
Simple(int a)
{
x=a;
}
Simple{Simple s)
{
x=s.x;
}
} ffDefault Constructor

IIParameterized Constructor

ffCopy Constructor

4.0 Learning Objectives:

Intellectual Skills:

1. To understand the concept of Overloading and Method Overloading.

2. To implement Constructor Overloading and concept of constructor.

3. To identify the syntax for given program.

4. To select control statement and study different errors.

5. To write program for given problem statement.

Motor Skills:

1. Ability to handle computer peripherals properly.

2. Ability to edit and debug programs.

5.0 Sample Program:

Implement a program to illustrate the use of Constructor Overloading.

import java.lang.*; class Sample

/lim port language package

{

int a.b; SampleO {

IIdata members declaration

IIdefault constructor initialized to zero

a=b=O;

t:xpenment NO.4

Sample(int X, int y)

IIparameterized constructor

{

a=x;

b=y:

}

void displayt) {

Ilmethod to display the value of variables

System.out.println{"a="+ a + "b="+b);

}

public static void main(String argsI]) {

IImain method

Sample s1 =new SampleO; Sample s2=new Sample(1 0,20); s l.displayt);

s2.displayO;

IIcall default constructor

Ilcall parameterized constructor

}

}

Output: Students should write the output.

6.0 Implementation:

Attempt the following programs:

1. Define a class Shape having overloaded static member function areat) to calculate and display area of Square and Rectangle.

2. Define a class Fraction having data members numerator and denominator. Initialize three objects using different constructors and display its fractional value.

Result: Students shall attach printouts of the program code taken on A-4 sheet.

.,rdVd rHJ!:JldIiUI1l11~ \::;, ll")}

expenmem L'IO.'l

7.0 Conclusion:

Implemented programs based on:

1 (method I constructor overloading) to display

2 (method / constructor overloading) to display

8.0 Laboratory Exercise:

Students shall execute the following code and write answers for same during lab hours.

Sr. Question Answers
no.
D1 Find error in the following code and rectify
it.
class Figure
{
String name;
private FigureO
{
System.outprintln("No Figure");
}
private Figure(String s);
{
name=s;
System.out.println("Figure is ="+s);
}
public static void main(String am
{
new Figure();
new Figure("Box'\
}
}
02 Write the output of following code segment?
class Number
{
int x;
Number(int y);
{
x=y--;
}
Number(Number n)
{
x=n.x++;
}
public static void main(String am
{
Number n 1 =new N umber(O);
Number n2=new Number(n1);
System.ouLprintln("x="+n1.x);
System.out.println("x="+n2.x);
}
} expenment No.4

8.0 Questions:

Write answers to Q ..... Q ..... Q ..... (Teacher shall allot questions)

1. Can we declare constructor as private? Yes or No? Give reason.

2. Define constructor. Give its special properties.

3. Why constructors do not have return type?

4. How do we invoke a constructor?

5. How does Java support the concept of destructor?

6. Explain the need of overloaded constructors.

7. Give the steps to specify how the compiler compiles overloaded methods.

8. Is constructor overloading same as method overloading? Yes or No? Explain.

9. If a 1 and a2 are objects of class Abc, then differentiate between following two statements:

L Abc az=new Abc(a1); it Abc az=a 1 ;

10. When does the compiler supply a default constructor for a class?

11. What is copy constructor? When should it be used?

12. State the main differance between constructor overloading and method overloading.

13. State the purpose of constructor overloading.

14. State the applications of method overloading.

15. Give one real world example of method overloading.

(Space for answers)

cxpeumern I~O,<+

(Space for answers)

cxpenmem I'lOA

(Space for answers)

Signature of Teacher:

Marks:

I

cxperunem rsc.o

EXPERIMENT No.5

To implement programs using Command Line Arguments and Wrapper Classes.

- -=-
IIIJIi""" II"'" ""'lIIIIII
int Integer
float Float
char Character
byte Byte
-
- -- - 1.0 Title:

2.0 Prior Concepts: e Class definition.

" Object Creation in java.

3.0 New Concepts:

Proposition 1: Wrapper Classes

A Wrapper Class is an instance that encapsulates a single value of its corresponding type is a class which creates strings of fixed length. It is an immutable object Many built-in Java classes work with objects and not on primitive data types. Therefore, Wrapper Classes are provided which have methods to convert primitive data types to objects and vice-versa.

There are eight Wrapper Classes in Java where six Wrapper Classes are subclasses of abstract class Number and other two Wrapper Classes are Character and Boolean.

Concept Structure:

cxperunent I'I!O.O

Proposition 2: Use of Wrapper Classes

The need of Wrapper Classes is due to fact that Primitive Data Types are always passed by value and cannot be directly passed by reference. To pass by reference, we need to create an object for one of primitive data types. Java provides classes that correspond to each Primitive Data Types. Concept Structure:

Primitive Type Wrapper Class
int Integer
byte Byte
long Long
short Short
float Float
double Double
char Character
boolean Boolean Proposition 3: Methods of Wrapper Classes

Wrapper Classes provide methods for converting String to the various data types and vice-versa. Many of methods of Wrapper Classes are static and therefore, those can be invoked using class name. The details of methods of Wrapper Classes are available in any Java language documentation or reference books as well as syntax of methods are specified in

Proposition 4: Command line Arguments

These are parameters that are supplied to the application program at the time of invoking it for execution. An input can be provided at the time of execution. We can write Java programs that can receive and use the arguments provided in Command Line. Signature of main 0 method, public static void main (String args[]) is used to accept the arguments where args is declared as array of strings. Any arguments passed in the Command Line can simply access the array elements and use them in the program.

ar9s[1] args[2] args[3]

C++ Java Cobol

Ex: Consider the Command Line to interpret a program Testjava: java Test C C++ Java Cobol

The arguments such as C,C++, Java, Cobol are assigned to the array args as follows:

args[O] C

expenmem 1'10.0

Proposition 5: Use of BufferedReader Class to accept input data BufferedReader Class from java.io package is used to accept input data from the user. To accept input data, an object of BufferedReader Class is created.

readl.inet) method should be enclosed within try-catch block to handle IOException if any or

throws 10Exception.

Note: For more information about exception handling refers experiment no.12

Ex: String s= in.readlinet):

int a =Integer.parselnt(s); lito accept any integer value from user using Integer IIwrapper Class to convert String to Integer

4.0 Learning Objectives:

Intellectual Skills:

1. To understand the use of Wrapper Classes.

2. To use Command Line Arguments to accept input at the time of execution.

3. To use BufferedReader Class to accept input data from the user.

4. To identify the syntax for the given program.

5. To select control statement, built in classes and study different errors.

6. To write program for given problem statement.

Motor Skills:

1. Ability to handle computer peripherals properly.

2. Ability to edit and debug programs.

5.0 Sample Program:

Program to define a class Employee to accept ernp jd, emp_name, basic_salary from the user and display the gross_salary.

import java.lang.*; import java. io. *; class Employee

{

!limport Language package lIimport 1/0 package to accept data

intemp_id;

String emp_name;

IIdata member declaration

experiment I'IU. 0

float basic_salary; Employee(int a,String s,float f) {

Ilconstructor to initialize data members

ernp jd=a: emp_name=s; basic_salary=f;

}

void dlsplayf) {

Ilmethod to calculate gross salary

float da= basic_salary*15/1 00; float hra= basic_salary*1 0/100;

float gross_salary == basic_salary+da+hra;

System.out.printlnl'Emp-ld ::= " + emp jd + "Gross salary ::=" + gross_salary);

}

public static void main(String args[))throws IOException {

BufferedReader in =new BufferedReader(new InputStreamReader(System.in»; System.out.println("Enter ernp jd :");

int x ==lnteger.parselnt(in.readLine{)); System.out.println(" Enter emp_name:");

String n=in.readl.inet):

System.out.println(" Enter basic_salary:");

float f == Float.parseFloat(in.readLine()); I/converting String to float

!/converting string to int

Employee e=new Employee(x,n,f);

e.dlsplayt): //invoke display method of Employee

} }

Output: Students should write the output.

cxpenment reo.o

6.0 Implementation:

Attempt the following programs:

1. To implement a program to accept principal amount, rate of interest, no. of years from the user and display the simple interest.

2. To implement a program to accept a string from the console and count number of vowels, constants, digits, tabs and blank spaces in a string.

Result: Students shall attach printouts of the program code taken on A-4 sheet.

7.0 Conclusion:

Implemented programs based on Wrapper class to display:

1 .

2 .

3 .

8.0 Laboratory Exercise:

Students shall execute following code and write answers for same during lab hours.

Sr.
Question Answers
no.
:
01 Write the output of following code segment
class Example -,
{
public static void main(String am
{
Long I=new Long(2);
Integer i=new Integer(2);
System. out. println(l.equals(i);
}
}
02 Will output of above code segment change
if I.equals(i) is replaced by
I. toStringO. equals(i. toStringO);? Justify
,
i .Jd.Vd rluYI(.1ltltllU I~ \:;i' I l.:J)

expenrnern I~O.D

03 The code given below converts a given string to Hexadecimal value. Identify error(s) if any and rectify it.

class Convert

{

public static void main(String[] a) {

Stri ng s=" ";

int i=lnteger.parselnt(s,27); System.out.println("Hex value of

:"+s+"="+i);

} }

04 Write the output of following code segment.

Double d2=new Double("-S.5");

Double d3=new Double("-5.5"); System.out.println(d2==d3); System.out.println(d2.equals(d3»; System. out. println( d2. compare T o( d3»;

8.0 Questions:

Write answers to Q ... ." Q ..... , Q ..... (Teacher shall allot the questions)

1. List the different Wrapper Classes in Java.

2. Give the use of Wrapper Classes and name of package in which they are contained.

3. State the method of Integer Class to Convert an integer value into String.

4. State the method of Integer Class to Convert a string into integer value ..

5. Illustrate how to convert an integer value to a I nteger object

6. Give the use of islntlnitet) and isNanO methods of Float class.

7. List the constants defined by Float and Double Classes.

8. List the methods of Character Class.

9. List the methods of Long Class.

10. Give the use of equalsO and compareToO methods.

11. Give the use of valueOfO method of Double class.

12. Give the use of substring{) and replacer) method of String class.

13. List the constructor methods of Integer class.

14. List the constructor method of Character class.

Wrapper Classes in Java

Wrapper: Float
Constructors:
1. Float(float f) 2. Float(double d) 3. Float(String str)throws
NumberFormatException
Methods:
1. byte byteValue( ) 7. int compareTo(Float f) 13. static float parseFloat
(String str)throws
NumberFormatException
2. lnt intValue( ) 8. boolean equals(Object f) 14. static Float valueOf
(String str)throws
. NumberFormatException
3. short shortValue( ) 9. boolean islnfinite( ) 15. String toString( )
4. long lonpvaluet ) 10. static Boolean islnfinite 16. static String toString
(float num) (float num)
5. float floatValue( ) 11. boolean isNaNJ )
6. double doubleValue() 12. static boolean isNaN
(float num) Wrapper: Double
Constructors :
1. Double(double d) 2. Double(String str)throws NumberFormatException
Methods:
1. int compareTo(Double 5. boolean isNan( ) 8. static Double valueOf(String
d) str) throws
NumberFormatException
2. boolean equals 6. static boolean isNaN 9. String toString( )
(Object d) (double num)
3. boolean islnfinite( ) 7. static double 10. static String toString
parseDouble(String str) (double num) -
throws
NumberFormatException
4. static boolean
islnfinite(double num) Wrapper: Byte
Constructors:
1. Byte(byte num} 2. 8yte(String str}throws NumberFormatException
Methods:
1. int compareTo(Byte b} 5. boolean isNan( ) 8. static Byte valueOf(String
str) throws
Num berFormatException
2. boolean equals 6. static boolean isNaN 9. String toString( )
(Object b) (byte num)
3. boolean islnfinite( ) 7. static byte 10. static String toString
parseByte(String str) (byte num)
throws
NumberFormatException
4. static boolean islnfinite
(byte num) Wrapper: Short
Constructors:
1. Short(short s) 2. Short(String str)throws NurnberForrnatException
Methods:
1. int compareTo(Short 3. static short 5. String toString( )
s) parseShort(String str)
throws
. NurnberForrnatExce(2tion
2. boolean equals 4. static Short valueOf 6. static String toString(short
(Object s) (String str) throws nurn)
NurnberForrnatException

Wrapper: Inteaer
Constructors :
1. Integer(int num) 2. Integer(String str)throws NurnberForrnatException
Methods:
1. int cornpareTo(lnteger 4. static Integer valueOf 7. static String toBineryString
i) (String str) throws (int num)
N urn berF ormatException
2. boolean equals 5. static int 8. static String toHexString (int
(Object i) parsel nteger( Stri ng nurn)
str) throws
N urnberF orrnatException
3. String toString( ) 6. static String toString(int 9. static String toOctalString
nurn) (lnt nurn)

Wrapper: long
Constructors:
1. Long(long nurn) 2. Long(String str)throws NumberForrnatException
Methods:
1. lnt cornpareTo(Long I) 4. static long parseLong 7. static String toBineryString
(String str) throws (long num)
NurnberForrnatException
2. boolean equals 5. static Long 8. static String toHexString
(Object I) valueOf(String (long nurn)
str) throws
NurnberFormatException
3. String toString( ) 6. static String toString(long 9. static String toOctalString
nurn) (long nurn)

Wrapper: Boolean
Constructors:
1. Boolean(boolean b) 2. Boolean(String str)
Methods:
1. boolean booleanValue 3. String toString( ) 5. static boolean valueOf
() (String str)
2. boolean equals 4. static String toString 6. static String valueOf
(Object b) (boolean b) (boolean b) cxpenrnern 1'>10.0

(Space for answers)

Signature of Teacher:

Marks:

You might also like