Vous êtes sur la page 1sur 14

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. ii. Java is popular because it is an object oriented programming language like C++. 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. v. Thus robustness is the essential criteria for the java programs. 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 powerful and 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 Cs 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 (its 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 doesnt 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) 1 In object oriented programming approach there is a collection of objects. This is a bottom up programming approach. The main focus is on objects.

Procedural Programming Language The procedural programming language executes series of procedures sequentially. This is a top down programming approach. The major focus is on procedures or functions. Data reusability is not possible.

Data reusability is one of the important feature of OOP.

Data binding can be done by making it Data binding is not possible. private. 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 stamped out 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)Abstraction
Abstraction - 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) Encapsulation Encapsulation means the detailed implementation of a component which can be hidden from rest of the system. Encapsulation means binding of data and method together in a entity called class. The data inside that class is accessible by the function 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 of

old classes. The old classes are referred as base classes and the new classes are referred as derived classes. That means the derived classes inherit the properties of base 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 class square.

e) Polymorphism Polymorphism is the ability to take more than one form and refers to an operation exhibiting different behavior instances. Object oriented programs use polymorphism to carry out the same operation in a manner customized to the object. Without polymorphism, you should have to create separate module names for a each method. For example the method clean is used to clean a Dish object, one that cleans a 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 Section
The 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 Statement
The next thing after a package statement (but before any class definitions) may be a number of import 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 Statements
An 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 Definitions
A 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 Class


Since 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 digit c). 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.

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

byte :- This is in fact smallest integer type of data types. Its width is of 8-bits with the 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 with a width of 16-bits and having a range from -32768 to 32767. Syntax to declare variable 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 to 2,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 is used. 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 32bit and 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. Its width is 64-bit having the range 4.9e-324 to 1.8e+308.Syntax to declare variable as byte is as double 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 byte char 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 DoWhileDemo 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 is for(initialization expression; test condition; update expressions) { statement1; statement2; } The for statement starts with the for keyword. This statement has three elements enclosed within parentheses. 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 10 class 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 resumes the 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.

Vous aimerez peut-être aussi