+ All Categories
Home > Documents > Assignments Java Kuvempu University

Assignments Java Kuvempu University

Date post: 08-Nov-2014
Category:
Upload: arindam-d-hearthackr
View: 125 times
Download: 2 times
Share this document with a friend
Description:
it is all about java assignments
Popular Tags:
19
Assignments for B.Sc.(IT) Courses Subject: JAVA Programming Subject Code: BSIT - 42 Assignment: TA (Compulsory) (1) Explain basic features of Java. Answer :- Various features of java programming language are as given below- Java is very simple programming language. Even though you have no programming background you can learn this language comfortably. i. Java is popular because it is an object oriented programming language like C++. ii. Platform independence is the most exciting feature of java. That means programs in java can be executed on variety of systems. This feature is based on the goal “write once , run anywhere and at anytime, forever”. iii. Java supports multithreaded programming which allows a programmer to write such a program that can be perform many tasks simultaneously. iv. Thus robustness is the essential criteria for the java programs. v. Java is designed for distributed systems. Hence two different objects on different computer can communicate with each other. This can be achieved by RMI (Remote Method Invocation) .
Transcript

Assignments for B.Sc.(IT) Courses

Subject: JAVA Programming

Subject Code: BSIT - 42

Assignment: TA (Compulsory)

(1) Explain basic features of Java.

Answer :- Various features of java programming language are as given below-

Java is very simple programming language. Even though you have no

programming background you can learn this language comfortably.

i. Java is popular because it is an object oriented programming language like C++.

ii. Platform independence is the most exciting feature of java. That means programs in

java can be executed on variety of systems. This feature is based on the goal “write

once , run anywhere and at anytime, forever”.

iii. Java supports multithreaded programming which allows a programmer to write such

a program that can be perform many tasks simultaneously.

iv. Thus robustness is the essential criteria for the java programs.

v. Java is designed for distributed systems. Hence two different objects on different

computer can communicate with each other. This can be achieved by RMI (Remote

Method Invocation) .

(2) Explain how Java differs from C and C++.

Answer :- Java was improved on C++. It has changed and improved upon the powerfuland difficult C++ features. The following are the differences from C and C++ that exist in Java:

Java does not have a preprocessor, and as such, does not have macros like #define. Constants

can be created by using the final modifier when declaring class and instance variables.

Java does not have template classes as in C++. Java does not include C’s const keyword or the ability to pass by const

reference explicitly. Java classes are singly inherited, with some multiple-inheritance features provided through interfaces.

All functions must be methods. There are no functions that are not tied to classes.

The go to keyword does not exist in Java (it’s a reserved word, but currently unimplemented).

You can, however, use labeled breaks and continues to break out of and continue executing

complex switch or loop constructs. Java does not use pointers Java doesn’t contain the data types: struct, union, enum.

(3)What is the difference between object oriented and procedure oriented programming ?

Answer :-

Sr Object Oriented Programming Language(OOP)

Procedural Programming Language

1 In object oriented programmingapproach there is a collection ofobjects.

The procedural programming language executes series ofprocedures sequentially.

2 This is a bottom up programmingapproach.

This is a top down programmingapproach.

3 The main focus is on objects. The major focus is on proceduresor functions.

4 Data reusability is one of the importantfeature of OOP.

Data reusability is not possible.

5 Data binding can be done by making itprivate.

Data binding is not possible.

6 It is complex to implement. It is simple to implement.

(4)Explain the following OOPs concept.

a) object and classes.

b) Abstraction.

c) Encapsulation.

d) Inheritance.

e) Polymorphism.

f) Message passing.

Answer :-

a)Objects and Classes :-Object is a physical entity which represents a person, vehicle or a conceptual entity (thing in existence) like bank account, company etc.A set of variables and functions used to describe an object is a “class”. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class, as if it were stampedout of a mould in the shape of a class. A class is a logical construct, an object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables.

b)AbstractionAbstraction - the act or process of leaving out of consideration one or more qualities of a complex object so as to attend to others. Solving a problem with objects requires you to build the objects tailored to your solution. We choose to ignore its inessential details, dealing instead with the generalized and idealized model of the object.

c) EncapsulationEncapsulation means the detailed implementation of a component which can behidden from rest of the system. Encapsulation means binding of data and methodtogether in a entity called class. The data inside that class is accessible by thefunction in the same class. It is normally not accessible from the outside of the

component.

d) Inheritance Inheritance is a property by which the new classes are created using the old classes.In other words the new classes can be developed using some of the properties ofold classes. The old classes are referred as base classes and the new classes arereferred as derived classes. That means the derived classes inherit the properties ofbase class. As shown below example the shape is a base class from which the circle,line, and rectangle are the derived classes. These classes inherit the functionality draw() and resize(). Similarly, the rectangle is a base class for the derived classsquare.

e) Polymorphism Polymorphism is the ability to take more than one form and refers to an operationexhibiting different behavior instances. Object oriented programs usepolymorphism to carry out the same operation in a manner customized to theobject. Without polymorphism, you should have to create separate module namesfor a each method. For example the method clean is used to clean a Dish object, one that cleansa car object, and one that cleans a vegetable object. With polymorphism, you create a single “clean” method and apply it for

different objects.

f)Message passing :-In an object based world the only way for anything to happen is by objects communicating with each other and acting on the results. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result.

(5) What are the advantages of object oriented programming?

Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear.

 

Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.

Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.

 

Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.

  

Maintainability: objects can be maintained separately, making locating and fixing problems easier.

(6) Explain the structure of a Java program.

Answer :- The fundamental structure of Java program like:

Documentation SectionThe documentation section comprises a set of comment lines giving the name of the program , the author and other details. Java also uses comment /**…*/ known as documentation comment.

Package Statement

The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package.Eg : package student;

Import StatementThe next thing after a package statement (but before any class definitions) may be a number ofimport statements. This is similar to the #include statement in C. Example : Import student . test;This statement instructs the interpreter to load the test class contained in the package student.

Interface StatementsAn interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.

Class DefinitionsA Java program may contain multiple class definitions. Classes are the primary and essential elements of a Java program.Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declarations and executable statements. To write a Java program, we first define classes and then put them together.Main Method ClassSince every Java stand-alone program requires a main method as its starting point, this class is the essential part of a Java program. A simple Java program may contain only this part. The main method creates objects of various classes and establishes communications between them.A Java program may contain many classes of which only one class defines a main method.

(7) With an example explain Java tokens.

Answer :- In a Java program, all characters are grouped into symbols called tokens. we write one simple rule that captures this structure:

token <= identifier | keyword | operator | literal

The different types of Tokens are:

1.Identifiers: names the programmer chooses Identifiers are used for naming classes, methods, variables,

objects, labels, package and interfaces in a program. Java identifiers follow the following rules:a). They can have alphabets, digits, and the underscore and dollar sign characters.b). They must not begin with a digitc). Uppercase and lowercase letters are distinct.d). They can be of any length.Examples : Average, sum, Batch_strength

2.Keywords: names already in the programming language

3Operators: symbols that operate on arguments and produce results

4Literals (specified by their type):- Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are :

Interger literals Floating_point literals

Character literals String literals Boolean literals

(8) With an example explain different data types in Java.

Answer :- Various data types used in java are byte, short, long, char, float, double, int, Boolean

byte :- This is in fact smallest integer type of data types. Its width is of 8-bits withthe range -128 to 127.Syntax to declare variable as byte is as byte i,j;short:- This data type is also used for defining the signed numerical variables witha width of 16-bits and having a range from -32768 to 32767. Syntax to declarevariable as short is as short a,b;

int:- This is the most commonly used data type for defining the numerical data.The width of this data type is 32-bit having a range of -2,147,483,648 to2,417,483,647. Syntax to declare variable as int is as int I,j;  long:- Sometimes when int is not sufficient for declaring some data then long isused. The range of long is really very long and it is -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807. The declaration can be long x,y;

float:- To represent the real number float data type can be used. The width is 32bitand range of this data type is 1.4e-045 to 3.4e+038. Syntax to declare variable as float is as float p,q;

double:-To represent the real number of large range the double data type is used. Itswidth is 64-bit having the range 4.9e-324 to 1.8e+308.Syntax to declare variable as byte is asdouble a,b;

char:-This data type is used to represent the character type of data. The width of this data type is 16-bit and its range is 0 to 65,536. Syntax to declare variable as bytechar a;

Boolean:- Boolean is a simple data type which denotes a value to be either true or false.

(9). With an example explain all the operators in Java.

Answer :-

(10) With an example explain the following statements in Java.

a. simple if

b. if..else

c. nested if

d. else..if ladder

Simple if:

Simple if execute when the condition is TRUE:

class If1{    public static void main(String args[]){      int i = 11;      int j = 20;

      if(i>j) 

// if i > j this statement executes         System.out.println(" i > j"); 

// if i <= j controls goes to this statement and // continues; this is what happens with the above values of i and j.      System.out.println(" i <= j ");    }}

If..else:

If you want several statements to execute after if or/and else, use blocks of statements

  class If2{    public static void main(String args[]){      int i = 11;      int j = 20;

      if(i>j) //if i > j this whole block executes        {           System.out.println(" i = "+i+" j= "+j);            System.out.println(" i > j");        }

      else // if i <= j this block will execute       

{        System.out.println(" i = "+i+" j= "+j);         System.out.println(" i <= j ");        }    }}

Nested if:

If there is more than two condition is present in the program and they are depend on each other then we are using Nested if.

  class If3{    public static void main(String args[]){      int i = 29;      int j = 20;

      if(i==29){        if(j<20) System.out.println(" i = 29 and j < 20");        if(j>20) System.out.println(" i = 29 and j > 20");

// this else is associated with if(j>20) above        else System.out.println(" i = 29 and j not greater than 20");      }

// this else statement which is outside the block// is associated with if(i==29)        else System.out.println("i is not equal to 29");

        System.out.println("control goes to this statement and continues");   }}

Else if ladder:

if statements are executed downwards and as soon as one of the conditions is true the statement associated with that if is executed and the rest of the if statements is bypassed. If none of the conditions is true the final else is executed.

  class Test{    public static void main(String args[]){      int grade = 71;

      if(grade >= 90)System.out.println("grade A");      else if(grade >= 80) System.out.println("grade B");      else if(grade >= 70) System.out.println("grade C");      else if(grade >=60 ) System.out.println("grade D");      else System.out.println("grade F");      System.out.println("proram continues here");   }}(11)With an example explain the switch statement in Java. Answer :- A switch statement allows you to test the value of an expression and, depending on that value, to jump to some location within the switch statement. The expression must be either integer-valued or character-valued. It cannot be a String or a real number. The positions that you can jump to are marked with “case labels” that take the form: “case constant” This marks the position the computer jumps to when the expression evaluates to the given constant. As the final case in a switch statement you can, optionally, use the label “default:”, which provides a default jump point that is used when the value of the expression is not listed in any case label.

A switch statement has the form: switch (expression) { case 1: statements-1 break; case 2:

statements-2 break; . . // (more cases) . case N: statements-N break; default: // optional default case } // end of switch statement

The break statements are technically optional. The effect of a break is to make the computer jump to the end of the switch statement. If you leave out the break statement, the computer will just forge ahead after completing one case and will execute the statements associated with the next case label. This is rarely what you want, but it is legal. However, that inside a subroutine, the break statement is sometimes replaced by a return statement.

Here is a simple example that uses a switch statement:class SampleSwitch { public static void main(String args[]) { for(int i=0; i<6; i++)switch(i) { case 0:System.out.println("i is zero.");break; case 1:System.out.println("i is one.");break;case 2:System.out.println("i is two.");break; case 3:System.out.println("i is three.");break; default:System.out.println("i is greater than 3.");} }

}

(12) Compare while and do..while statements in Java.

The difference between do-while and while is that do-while evaluates its expression at the

bottom of the loop instead of the top. Therefore, the statements within the do block are always

executed at least once, as shown in the following DoWhileDem o program:

class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); }}

(13)With an example explain for statement in Java.

Answer :- To manage iterative actions, Java provides the for statement as an efficient alternative to the while statement. The for statement creates a loop in which a set of statements is repeatedly executed until the specified condition becomes false. The syntax of the for statement isfor(initialization expression; test condition; update expressions){statement1;statement2;}

The for statement starts with the for keyword. This statement has three elements enclosed withinparentheses.The first element of the for statement is initialization expressions. The initialization expressions element is an assignment statement. The assignment is done only once before the for statement begins execution. The second element, test condition, is evaluated before each iteration of the for statement. This element determines whether the execution of the for loop should continue or terminate. Update expressions is the third element in the for statement. This element changes the values of the variables used in the test condition. Update expressions are executed at the end of each iteration after the loop body is executed. The elements of a for statement are separated by semicolons.Example ://the program display a number form 2 to 10class displaynumber {

public static void main(stsring args[ ]) { for ( j = 2; j <= 10; j++ ) system.print(output,"i = %d",j); } }

(14)With the help of an example program explain break and continue statements in Java.

Answer :-

Break statement in Java:By using break, we can force immediate termination of loop, by passing the Conditional expression and any remaining code in the body of the loop. When a Break statement is encountered inside the loop, the loop is terminated and program control resumesthe next statement following the loop.Class Breakloop{ public static void main(string args[ ]) { for(int i=0; i<00; i++) { if (i == 10) break; system.out.println(“i =:”+i); } }

system.out.prinln(“loop complete”);}

The break statement forces the control to come out from a: switch statement while loop do-while loop for loop

Continue statement in Java:-

The continue statement stops the current iteration of a loop and immediately starts the next iteration of the same loop. When the current iteration of a loop stops, the statements after the continue statement in the loop are not executed. The continue statement is written as continue;.

You can use the continue statement in the while, do-while, and for statements but not in the switch statement. Use of continue statements is illustrated in the following program.

The continue statement causes the flow of control to move to the condition part of the while and do-while loops. In the case of the for statement, the continue statement causes the flow of control to move to the update expressions part of the for statement before moving to the test condition part.


Recommended