You are on page 1of 14

SUBJECT

:

JAVA PROGRAMMING

SUBJECT CODE :– BSIT:42 PART-A 1. How platform independence is achieved in JAVA ? Ans:- Java is known as platform-neutral language because Java‟s byte codes are designed to be read, interpreted, and executed in exactly the same manner on any computer hardware or operating system that supports a Java run-time. 2. list any three features of JAVA. Ans.:- The Features of JAVA 1) Simple 2) Object-Oriented 3) Distributed 3. What is Java C, Javadoc and Jdbc? Ans. :- Java C – JavaC is a compiler translates java source code to byte code. Javadoc – Javadoc is used for creates html format documentation from java source file. Jdbc – A programming interface that lets Java applications access a database via the SQL language. Since Java interpreters (Java Virtual Machines) are available for all major client platforms, this allows a platform-independent database application to be written. 4. List different features of OOP. Ans :- The features of OOP. 1) Objects and classes 2) Abstraction 3) Encapsulation 4) Information hiding 5) Inheritance 6) Polymorphism 5. Name different types of Java tokens. Ans. :- The different types of Java tokens are :1) Reserved Keywords 2) Identifiers 3) Literals 4) Operators 6. What is the task of the main method in Java program ? Ans.:- After we specify the keywords for declaring the main() method, you specify a String array as parameter of the main() method. The String array represents command line arguments. It is compulsory for a user to specify the parameter to the main() method in all Java programs unlike in C

:-Inheritance in object oriented programming means that a class of objects can inherit properties from another class of objects.used to initialize the objects of the class and has the same name as that of its class. PART – B 1.Keywords are an essential part of a language definition. Write an equivalence of switch statement and if statement. 10. which is again a part of the vehicle as: Vehicle Attributes: Model: Make .:. 9. This is necessary because the main() method is called by the Java interpreter before any objects are created.:. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. Ans. Java language has reserved 60 words as keywords. For example.out. 8. When Inheritance occurs. a) What is inheritance and how one can achieve code reusability? Explain with an example. one class is then referred to as the „parent class? or super class? or „base class?. you specify the void keyword.equivalence of switch statement is if and the equivalence of if statement is if else. inheritance can mean just reusing code . so you cannot use them as names for variables. Ans. the main() method does not return a value. These keywords have specific meaning in Java. Why main method in Java is declared as static ? Ans.:.The keyword static helps to specify that the main() method can be called without instantiating an object of a class. They implement specific features of the language. Why can?t we use a keyword as a variable name ? Ans. or can mean that you have used a whole class of object with all its variables and functions For ex. public static void main (String args[]) {//code} After specifying the keyword static.println (“Hello”) } } 7. This keyword indicates to the compiler that. Constructor is_____________.and C++. the bike is a part of the class two wheelers. Ans.:. Class class1 { public static void main (String args[]) { System.

An instance variable is declared within the class definition in the usual way.The difference between the do-while statement and the while statement is that in the while statement. the loop body is executed only when the condition stated in the statement is true. that is.we might define a motorcycle class that describes the features of all motorcycles . Ans. 2. with a type name and a variable name.Class is a template that defines a particular type of object.Two Wheeler Attributes: No.:. A given class will only have one copy of each of its class variables. test condition and increment/decrement are .:. regardless of the condition evaluating to true or false. Each object will have its own values for each instance variable. and not just instances of that class. They belong to the class.In the for loop. Classes contain all the features of a particular set of objects. In the do-while loop. of wheels Four Wheeler Attributes: No. The name „instance variable‟ originates from the fact that an object is an „instance‟ or an occurrence of a class and the values stored in the instance variables for the object differentiate the object from others of the same class type. We can use the class definition to create objects of that of class type. the loop body is executed at least once.we should have a concrete instance of that motorcycle. The class variables exist even if no objects of the class have been created. Each object of the class will have its own copy of each of the instance variables that appear in the class definition. a) Compare in terms of their functions and semantics the following pairs of statements: i) do while and while Ans. ii) while and for Ans. and they can be referenced by any object or class. three sections. to create objects that incorporate all the features belonging to that class. The while loop is also called the top tested loop whereas the do-while loop is also called the bottom tested loop. of wheels Bike Attributes: Scooter Attributes: Car Attributes Van Attributes b) What is a class? How does it accomplish data hiding? Explain with example. and can have an initial value specified. the motorcycle class serves as an abstract model for the concept of a motorcycle-to interact with each type of motorcycle.:. initialization. and these will be shared between all the objects of the class. Ex:.

Ans. For example. When a break statement is encountered inside the loop. . In the for loop.ctr<=n.calculate(num).parseInt(a[0]).:. more than one variable can be initialized. more readable If you omit the break between two switch cases. Ans. With if else you‟d need a go to (which is not very nice to your readers … if the language supports go to at all. iii) nested if and switch Ans. When the current iteration of a loop stops.:.placed in the same line whereas in the while loop. object.+ 1/n. } System. int num=Integer. } } 3.out. iv) break and continue. } public static void main(String a[]) { Series object=new Series().DATA TYPES IN JAVA byte: It is the smallest integer type.ctr++) { total=total+1/ctr. tested and incremented at a time. b) Write a program to find sum of the following harmonic series for a given value of n 1+ 1/2 + 1/3 + . Ans. .The continue statement stops the current iteration of a loop and immediately starts the next iteration of the same loop. all three sections are placed in three different places in a program. the following declaration declares two variables B and C of type byte.:. This is a signed 8-bit type and has a range from -128 to 127. the statements after the continue statement in the loop are not executed.:-The difference between nested if and switch statement is if allows complex expressions in the condition while switch wants a constant we can‟t accidentally forget the break between ifs but you can forget the else (especially during cut‟n'paste) switch is usually more compact than lots of nested if else and therefore.println(“Sum of harmonic series: “+total). bypassing the conditional expression and any remaining code in the body of the loop.public class Series { double total. public void calculate(int n) { for(double ctr=1. . you can fall through to the next case in many C-like languages. the loop is terminated and program control resumes the next statement following the loop. a) Explain different data types in Java with example. . The break statement immediately terminates the loop.

the following declaration declares variable K of type short. For example. long: This is signed 64-bit type and has a range from -263 to 263 -1. c1 =84. R =3.483. float x. For example. Methods of a class operate on the data members of .c2.8. For example. int: It is a signed 32-bit type and has a range from -2.768 to 32. b =2. short k. x = -1111. flag= false. k = 2. c = -114. Classes contain data members and methods.767. se =ds * 24 * 60 * 60.14215. P = 10. For example. char: this data type is used to store characters. boolean flag. double: It uses 64 bits to store a value. double P. true or false. For example.483. Ans.147.147. c2 =‟g'. R. float: It uses 32 bits to store a value. b) Describe the structure of a typical Java program. For example. long ds = 1000. long se. char c1. :.c. For example. Int score. Score=90. For example. short: It is a signed 16-bit type and has a range from -32.648 to 2.A Java program may contain many classes of which only one class defines a main method. It is 16-bit type and has a range from 0 to 65. int x = 10. int j = 98.647.536. int : It uses 32 bits to store a value.byte b. boolean: it can have only one of two possible values.

Methods may contain data type declarations and executable statements. Class Definitions A Java program may contain multiple class definitions. a) What is JVM ? How does it help to achieve platform independence? If JVM is available for windows then can we run program written on Unix platform ? Comment. Import Statement The next thing after a package statement (but before any class definitions) may be a number of import statements. Classes are the primary and essential elements of a Java program. Example: import student.the class. the author and other details.:-Java compiler produces an intermediate code known as byte code for a machine that does not . Ans. Example: package student. Java also uses the comment /**…*/ known as documentation comment. A Java program may contain one or more sections as shown in the following figure: Documentation Section Suggested Package Statement Optional Import Statements Optional Interface Statements Optional Class Definitions Essential Main Method class { Main Method Definition } Essential General Structure Of a Java program Documentation Section The documentation section comprises a set of comment lines giving the name of the program. This statement instructs the interpreter to load the test class contained in the package student. This statement declares a package name and informs the compiler that the classes defined here belong to this package. This is similar to the #include statement in C++. we first define classes and then put them together.test. 4. To write a Java program. Interface Statements An interface is like a class but includes a group of method declarations. Package Statement The first statement allowed in a Java file is a package statement. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.

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. . these elements are called the members of the class. Yes. Collectively.exist . In turn. one class is then referred as the „parent class‟ or „super class‟ or „base class‟. as if it were stamped out of a mould in the shape of a class. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result. and executed in exactly the same manner on any computer hardware or operating system that supports a Java run-time. . Inheritance can mean just reusing code. Java‟s program units.:. Java is known as platform-neutral language because Java‟s byte codes are designed to be read. Dynamic binding is also needed when the compiler determines that there is more than one possible method that can be executed by a particular call. ii) Inheritance and polymorphism. The lengthy link-and-load step required by third-generation programming languages is eliminated. Specifically. When we create a class. The code that operates on that data is referred to as member methods or just methods. When inheritance occurs. A class defines the structure and behavior (data and method) that will be shared by a set of objects. which define the use of the member variables. An object has physical reality. run anywhere. morph means change (or „form‟).:. interpreted. Ans. 5. these serve as a pattern for a „derived class‟ or „subclass‟. regardless of where the original code was developed b) How are data and method organized in an object oriented program ? Illustrate the same for car object. Each object of a given class contains the structure and behavior defined by the class. Based on the class of the object. are loaded dynamically (when needed) by the Java run-time system. a set of variables and functions used to describe an object constitutes a “class”. a) Distinguish between the following terms: i) Dynamic binding and message passing. or can mean that you have used a whole class of object with all its variables and functions. Ans.Dynamic binding in java is the mechanism by which compiler cannot determine which method implementation to use in advance. the data defined by the class are referred to as member variables or instance variables. Ans.:.In an object-oriented program. Polymorphism: It is a key concept in object-oriented programming. the runtime system selects the appropriate method at runtime. Loaded classes are then dynamically linked with existing classes to form an integrated unit.” This means that Java source code can run on any platform for which a JVM exists. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. classes. Poly means many.Inheritance in object-oriented programming means that a class of objects can inherit properties from another class of objects. you will specify the code and data that will constitute that class. this machine is called JAVA VIRTUAL MACHINE (JVM). One of the fundamental principles of Java is “write once. A class is a logical construct.

each of which representation an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships. a) Define programming. UNSTRUCTURED PROGRAMMING In an unstructured programming the main program directly operates on global data. It is a method of implementation in which programs are organized as co-operative collection of objects. PROCEDURAL PROGRAMMING With procedural programming we are able to combine returning sequence of statements into one single place . Polymorphism encourages something we call „extendibility‟. MODULAR PROGRAMMING With modular programming procedures of a common functionality are grouped together into separate modules.a programming is a specific set of ordered operations for a computer to perform . What are the types of programming? Explain. OPERATOR USE OPERATION >> Op1 >> op2 Shift bits of op1 right by distance op2 << Op1 << op2 Shift bits of op1 left by distance op2 >>> Op1>>> op2 Shift bits of op1 right by distance op2 Each shift operator shifts the bits of the left-hand operand over by the number of positions indicated .:. A program therefore no longer consists of only one single part. OBJECT-ORIENTED PROGRAMMING In object oriented programming.:.:6. Ans.Polymorphism is simply a name given to an action that is performed by similar objects. Ans. an object or a class can have its uses extended. b) What are the difference between C and Java ?How Java and C++ are similar? Ans. a complex system is decomposed in accordance to the key abstractions of the problem. a procedure call is used to invoke the procedure.Programming:. b) Explain bitwise operators in Java with example. Polymorphism allows a common data-gathering message to be sent to each class and allows each subclass object to respond to a message format in an appropriate manner to its own properties. In other words.BITWISE OPERATORS SHIFT AND LOGICAL OPERATORS A shift operator allows you to perform bit manipulation on data.

The “and” .hand operand. the “and” function sets the resulting bit of 1 if both operands are 1 . The result of the shift operations is 1101 shifted to the right by one position -1106 or 6 in decimal. The java programming language also provides these four operators that perform logical functions on their operands :OPERATOR USE OPERATION & Op1 & op2 Bitwise and | Op1 | op2 Bitwise or ^ Op1 ^ op2 Bitwise x or ~ Op1 ~ op2 Bitwise complement The & operation performs the logical “and” function on each parallel pair of bits in each operand . – 13 >> 1 The binary representation of the number 13 is 1101.by the right. Op1 Op2 RESULT 0 0 0 0 0 0 1 0 0 1 1 1 Suppose we were to “and” the values 12 and 13 12 & 13 The result of this operation is 12. Because the binary representation of 13 is 1101. Ex.

the do-while statement is a lopp statement provided by java. The statement helps to perform certain repetitive actions depending on a condition. the resulting bit is 0. Ans. otherwise. .function sets the resulting bit to 1 if both to 1 if both operand bits are 1.out. the condition is enclosed within parentheses. While (n <= num) { System. a) List and explain different types of loops in Java. Syntax: While (test condition) { Body of the loop True }. 7. Int num = 5. :. The major difference between the do-while statement and the while statement is that in the while statement.Class numbers { Public state void main(String args[]) { Int n = 0 . continue and break statement THE WHILE LOOP The while statement contains a condition and a loop body.println(n). N++ } } } DO STATEMENT Similar to the while statement. Condition Statement Ex. The values of the variables used in the condition must be changed in the loop body. All the variables used in the condition of the while statement must be initialized before the while loop. the condition may always remain true and the loop may never terminate. Otherwise.Loops in java (I) While loop (II) Do loop (III) For loop . the loop body is executed only when the condition stated in the statement is true.

The syntax of the for statement is For(initialization expression. The statement creates to loop in which a set of statements is repeatedly executed until the specified condition becomes false. } While(n<=5). .out. Do { System. } } FOR STATEMENTS To manage iterative actions. N++. java provides the for statement as an efficient alternative to the while statement.println(n). test condition. Program to print the numbers from 1 to 5 Class numbers { Public static void main (string args[]) { Syntax: While (test condition) { do Body of the loop }. Int num = 5. False True While Condition Statement Int n=0. update expressions) { Statement1. b) What is polymorphism? Explain method overriding with example and prove that it is a polymorphism.We can use the do-while loop in situations where an action must be performed at least once without evaluating the condition. } The for statement starts with the for keyword. Statement2.

A parameterized constructor in java is just a constructor which take some kind of parameter (variable) when is invoked.println( “Book id is “ +id). class MyClass { //this is a normal constructor public MyClass() . } public static void main(String args[ ] ) { Book1 x = new Book1( ).a stack (which is a last-in. and one for characters. then the method in the subclass is said to override the method in superclass. METHOD OVERRIDING In the class hierarchy. The specific action is determined by the exact nature of the situation. System.println( “The author name is “ +author). System.java and compile. when a method in a subclass has the same name and type signature as method in the superclass. One stack is used for integer values.show(). Ans:..out.out.:. int id = “34567”. You might have a program that requires three types of stacks. Ex.Polymorphism (from the Greek.println( “Book id is “ +id). For example.out. x.println( “Book name is “ +name). first-out list).println( “Book name is “ +name). } } Save this file as book.out. void show ( ) { System. void show ( ) { System. meaning “many forms”) is a feature that allows one interface to be used for a general class of actions.Ans. class Book { //super class defined String name = “JAVA PROGRAMMING” . This is our Base Class class Book1 extends Book { // This is the subclass String author = “micheal janson”. one for floating-point values. System. } } 8.out. a) What is a parameterized constructor? Explain its usage with an example.

toLowerCase().concat(str2).out.println (str).println (str). } } ii) substring The subString method is used to create new instances of the class String from existing instances.{ //do something } //this is a parameterized constructor public MyClass(int var) { //do something } //this is another parameterized constructor public MyClass(String var. „i‟). // str now equals “HELLOjava” System. // str now equals “HELLO java” System.println (str).toUpperCase().// java str = str.out.out. str = str.println (str). // str = “jivi” System.trim(). :.out. class altStr{ public static void main (String args[ ]) { String str = “Hello”.println (str2). str = str. String str2 = “Java”.substring (5. // HELLO System. It has the general form String trim ( ).out.replace („a‟. Integer var2){ //do something } } b) Explain the methods (i) Trim Ans. str = str.str. str = str.println (str).The trim method returns a copy of the invoking string from which any leading and trailing white space has been removed. str2 = str2. The new string is specified by giving the required index range within the existing string.length()). . System.out. // str = “java” System.

String substring(int start Index. // false System.println (str. To obtain this value call a length method.println (str.println (str. i. char is position 0 System. System. // a negative number.out.out. String str2 = “Java”.charAt(0)).e.equals(str2)).compareTo(str2)). iii) length The length of a string is the number of characters that it contains.length() + str2.String substring(int startIndex) This returns the sub string that starts at startIndex and runs to the end of the invoking string.out.length()). i. int length().println (str. // H.out. int endIndex) This returns the substring that starts at startindex and runs through endIndex-1. class strCmp { public static void main (String args[ ]) { String str = “Hello”.e. str is less than str2 System. // 5 + 4 = 9 } } .