(UCS41) Java Programming Unit-1 Introduction to Java

Size: px
Start display at page:

Download "(UCS41) Java Programming Unit-1 Introduction to Java"

Transcription

1 ACADEMIC YEAR: REGULATION CBCS (UCS41) Java Programming Unit-1 Introduction to Java Type: 100% Theory Question & Answers 1. Define Java. (April/May 2014). PART A QUESTIONS (2 Marks) Java is a general purpose, object oriented programming language. We can develop two types of programs: Stand-alone applications Web applets 2. What is the functions of Java Virtual Machine? (April/May 2014). Ans: It is a program that interprets the intermediate java byte code and generates the desired output. It is because of byte code and JVM concepts that programs written in Java are highly portable. 3. How Java Differ from C++? (Nov 2014). Ans: (i) Java does not use pointers. (ii) Java has replaced the destructor function with a finalize() function. 4. What is System.Out.Println? Ans: A print "statement" is actually a call to the print or println method of the System.out object. The print method takes exactly one argument; the println method takes one argument or no arguments. However, the one argument may be a String which you create using the string concatenation operator +. If you ask to print an object, the print and println methods call that object's tostring() method to get a printable string. Example int x = 3; int y = 5; System.out.println(x + " and " + y + " is " + (x + y)); Result 3 and 5 is 8 RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 1 of 29

2 ACADEMIC YEAR: REGULATION CBCS int x = 3; int y = 5; System.out.println(x + " and " + y + " is " + x + y); Result 3 and 5 is 35 Anything concatenated ("added") to a string is first converted to a string itself. In the second example above, the x is concatenated with the string, then the y is concatenated. 5. How OOPs differs from procedural programming? (April 2015). (i) Java does not include the C unique statement keywords sizeof, and typedef. (ii) Java does not contain the data types struct and union. Procedural Object Oriented i) procedure method ii) record object iii) module class iv) procedural call message 6. What are java Objects? Ans: Objects are the basic run time entities in an object oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program may handle. They may also represent user-defined data types such as vectors and lists. Any programming problem may be analyzed in terms of objects and the nature of communication between them. Program objects should be chosen such that they match closely with the real world objects. 7. List any four features of Java.(NOV/Dec 2016) Ans: The features of Java are as follows: (i) Compiled and Interpreted (ii) Platform-Independent and Portable (iii) Object Oriented (iv) Robust and Secure RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 2 of 29

3 ACADEMIC YEAR: REGULATION CBCS What is meant by control statement? (Nov 2012) Ans: Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements; Selection statements: if, if-else and switch. Loop statements: while, do-while and for. Transfer statements: break, continue, return, try-catch-finally and assert. We use control statements when we want to change the default sequential order of execution. Depending upon the position of the control statement in the loop, a control structure may be classified either as entry-controlled loop or as exit-controlled loop. 9. What is Java Bytecode? (Nov 2012) Ans: All language compilers translate source code into machine code for a specific computer. Java compiler also does the same thing. The Java Compiler produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java Virtual Machine. 10. What is an Arrary? (April 2012) Ans: Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1,..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and...numbers[99] to represent individual variables. The different types of arrays are as follows: Single Dimensional Array Two Dimensional Array Multi-dimensional Array 11. List content of a Java Devlopment Kit. (April/May 2013) Ans: Java environment includes a large number of development tools and hundreds of classes and methods. The development tools are the part of the system known as Java RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 3 of 29

4 ACADEMIC YEAR: REGULATION CBCS Development Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface. 12. Define the term Variable with example. (April/May 2013) Ans: A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = ; // declares and assigns a value of PI. char a = 'a'; // the char variable a iis initialized with value 'a' 13. Write about evolution of Java Ans: Java is a general purpose; object oriented programming language developed by Sun Microsystems of USA in Originally called Oak by James Gosling, one of the inventors of the language, Java was designed for the development for software for consumer electronic devices like TVs, VCRs, toasters and such other electronic devices. The goal had a strong impact on the development team to make the language simple, portable and highly reliable. 14. What is meant by Operator? Ans: An operator is a symbol that takes one or more arguments and operators on them to produce a result. Operators are of many types. They are as follows: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Conditional Operators Increment / Decrement Operators Bitwise Operators Special Operators 15. What is Scanner Class? Ans: The java.util.scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.following are the important points about Scanner: RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 4 of 29

5 ACADEMIC YEAR: REGULATION CBCS A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. A scanning operation may block waiting for input. A Scanner is not safe for multithreaded use without external synchronization. 16. What is Encapsulation? Ans: The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of the class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. 17. Mention any four data types in Java. In java, there are two types of data types primitive data types int short boolean byte float non-primitive data types 18. List out the special Operator in Java.?: []. (type) New instanceof 19. Mention any two applications of OOPS. Ans: The application of OOP includes: RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 5 of 29

6 ACADEMIC YEAR: REGULATION CBCS Real-time systems Simulation and modeling Object-Oriented Databases 20. What is Servlet? A servlet is a small Java program that runs within a Web server.servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. PART B QUESTIONS (5 Marks) 1. What is Reserved word? Give example. (April/May 2014) Java reserved words are keywords that are reserved by Java for particular uses and cannot be used as identifiers (e.g., variable names, function names, classnames). The list of reserved words in Java is provided below. The table below lists all the words that are reserved: abstract assert boolean break byte case catch char class const* continue default double do else enum extends false final finally float for goto* if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while 2. Why String is an Object. How? (April/May 2014) String is one of the widely used java classes. It is special in java as it has some special characteristics than a usual java class. Let s explore java String in this article and this page aims to serve you as a single point reference for all your queries on Java String. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 6 of 29

7 ACADEMIC YEAR: REGULATION CBCS Though you might know most of the things, this will help you to recall them and I am sure you will find one or two new things. I recommend you to take your time and read through this completely as java String is a basic building block of your java programs. Immutable Java String: Java String is a immutable object. For an immutable object you cannot modify any of its attribute s values. Once you have created a java String object it cannot be modified to some other object or a different String. References to a java String instance are mutable. There are multiple ways to make an object immutable. Simple and straight forward way is to make all the attributes of that class as final. Java String has all attributes marked as final except hash field. Java String is final. I am not able to nail down the exact reason behind it. But my guess is, implementers of String didn t wany anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String. We all know java String is immutable but do we know why java String is immutable? Main reason behind it is for better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily created by pointing to already existing String. This saves valuable primary memory. Using String as a key for Hashtable guarantees that there will be no need for re hashing because of object change. Using java String in multithreaded environment is safe by itself and we need not take any precautionary measures. Java String Instantiation: In continuation with above discussion of immutability of java String we shall see how that property is used for instantiating a Sting instance. JVM maintains a memory pool for String. When you create a String, first this memory pool is scanned. If the instance already exists then this new instance is mapped to the already existing instance. If not, a new java String instance is created in the memory pool. This approach of creating a java String instance is in sync with the immutable property. When you use new to instantiate a String, you will force JVM to store this new instance is fresh memory location thus bypassing the memory map scan. Inside a String class what you have got is a char array which holds the characters in the String you create. Following are some of the ways to instantiate a java String String str1 = "javapapers"; String str2 = new String("Apple"); String str3 = new String(char []); String str4 = new String(byte []); RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 7 of 29

8 ACADEMIC YEAR: REGULATION CBCS String str5 = new String(StringBuffer); String str6 = new String(StringBuilder); We have an empty constructor for String. It is odd, java String is immutable and you have an empty constructur which does nothing but create a empty String. I don t see any use for this constructor, because after you create a String you cannot modify it. 3. Why Java is more popular? (Nov 2014) Java is object-oriented and class-based. Developers adopt and use Java because code can be run securely on nearly any other platform, regardless of the operating system or architecture of the device, as long as the device has ajava Runtime Environment (JRE) installed. Exceptions Garbage collection and memory management Interfaces Object oriented Threads GUI Built-in networking support Strong typing and specified widening/casting extensively specified operator precedence/evaluation order Extensive libraries included as part of the language cross-platform portability primitive type sizes are specified and platform-independent primitive type conversions in expressions are specified by the language 4. How to create and compile simple java program? (April/May 2015) Writing a Simple Java Program (hello world) Open a simple text editor program such as Notepad and type the following content: public class HelloWorld public static void main(string[] args) System.out.println("Hello world!"); RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 8 of 29

9 ACADEMIC YEAR: REGULATION CBCS Save the file as HelloWorld.java (note that the extension is.java) under a directory, let s say, C:\Java. Every Java program starts from the main() method. This program simply prints Hello world to screen. Compiling it Now let s compile our first program in the HelloWorld.java file using javac tool. Type the following command to change the current directory to the one where the source file is stored: cd C:\Java And type the following command: javac HelloWorld.java That invokes the Java compiler to compile code in the HelloWorld.java file into bytecode. Note that the file name ends with.java extension. You would see the following output: If everything is fine (e.g. no error), the Java compiler quits silently, no fuss. After compiling, it generates the HelloWorld.class file which is bytecode form of the HelloWorld.java file. Now try to type dir in the command line, we ll see the.class file: So remember a Java program will be compiled into bytecode form (.class file). Running it It s now ready to run our first Java program. Type the following command: java HelloWorld RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 9 of 29

10 ACADEMIC YEAR: REGULATION CBCS That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no.java or.class extension). You would see the following output: It just prints out Hello world! to the screen and quits. 5. Discuss about java Operator. (April 2012) Ans: An operator is a symbol that takes one or more arguments and operators on them to produce a result. Operators are of many types. They are as follows: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Conditional Operators Increment / Decrement Operators Bitwise Operators Special Operators 1. Arithmetic Operator Ans: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Assume integer variable A holds 10 and variable B holds 20, then: Operator Description Example + Addition Adds values on either side of the operator - Subtraction Subtracts right hand operand from left hand operand * Multiplication Multiplies values on either side of the operator / Division Divides left hand operand by right hand operand % Modulus Divides left hand operand by right hand operand and returns remainder A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 The different types of arithmetic operators are as follows: Integer Arithmetic Real Arithmetic Mixed Mode Arithmetic 2 Assignment Operator RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 10 of 29

11 ACADEMIC YEAR: REGULATION CBCS Ans: The most commonly used operator is the assignment operator. It is denoted by the "=" character and simply assigns the value on the right to the operand on the left. It is also called shorthand assignment operators. 3.Conditional Opertor Ans: Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x = (expression)? value if true : value if false Following is the example: RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 11 of 29

12 ACADEMIC YEAR: REGULATION CBCS public class Test public static void main(string args[]) int a, b; a = 10; b = (a == 1)? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10)? 20: 30; System.out.println( "Value of b is : " + b ); This would produce the following result: Value of b is : 30 Value of b is : Briefly explain about the Nested if else statement with example. Ans: It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax: The syntax for a nested if...else is as follows: if(boolean_expression 1) //Executes when the Boolean expression 1 is true if(boolean_expression 2) //Executes when the Boolean expression 2 is true You can nest else if...else in the similar way as we have nested if statement. Example: public class Test public static void main(string args[]) int x = 30; int y = 10; if( x == 30 ) if( y == 10 ) RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 12 of 29

13 ACADEMIC YEAR: REGULATION CBCS System.out.print("X = 30 and Y = 10"); This would produce the following result: X = 30 and Y = Discuss the various java data types with example. (April/May 2013) Ans: Data type specifies the size and type of values that can be stored in an identifier. The Java language is rich in its data types. Different data types allow you to select the type appropriate to the needs of the application. Data types in Java are classified into two types: Primitive which include Integer, Character, Boolean, and Floating Point. Non-primitive which include Classes, Interfaces, and Arrays. Primitive Data Types 1. Integer: Integer types can hold whole numbers such as 123 and 96. The size of the values that can be stored depends on the integer type that we choose. Type Size Range of values that can be stored byte 1 byte 128 to 127 short 2 bytes to int 4 bytes 2,147,483,648 to 2,147,483,647 long 8 bytes 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807 The range of values is calculated as (2n 1) to (2n 1) 1; where n is the number of bits required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can be stored in the byte data type is (28 1) to (28 1) 1 = 27 to (27) -1 = 128 to 127 RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 13 of 29

14 ACADEMIC YEAR: REGULATION CBCS Floating Point: Floating point data types are used to represent numbers with a fractional part. Single precision floating point numbers occupy 4 bytes and Double precision floating point numbers occupy 8 bytes. There are two subtypes: Type Size Range of values that can be stored float 4 bytes 3.4e 038 to 3.4e+038 double 8 bytes 1.7e 308 to 1.7e Character: It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can hold only a single character because char stores unicode character sets. It has a minimum value of u0000 (or 0) and a maximum value of uffff (or 65,535, inclusive). 4. Boolean: Boolean data types are used to store values with two states: true or false. 7. Explain Object Oriented Concepts. Ans: The object-oriented is a programming paradigm where the program logic and data are weaved. As stated by Phil Ballard, it is a way of conceptualizing a program's data into discrete "things" referred to as objects, each having its own properties and methods. Let's see an example. Suppose your friend is a bank manager and he wants you to help improving their system. The first object you might design is the general-purpose Account. The Account object has properties and methods. For each client your friend's bank have, you would have to create an Account object. Characteristics As follows the most important features of object-oriented programming: Encapsulation. Capability to hide data and instructions inside an object. Inheritance. Ability to create one object from another. Polymorphism. The design of new classes is based on a single class. Message Passing. It is the way objects communicate with each other. Garbage Collection. Automatic memory management that destroys objects that are no longer in use by the program. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 14 of 29

15 ACADEMIC YEAR: REGULATION CBCS Benefits As follows some benefits of using object-oriented programming: Re-usability. You can write a program using a previous developed code. Code Sharing. You are able to standardize the way you are programming with your colleagues. Rapid Modeling. You can prototype the classes and their interaction through a diagram. Drawbacks As follows the disadvantages of using object-oriented programming: Size. Are larger than other programs, consuming more memory and disk space. Effort. Require a lot of work to create, including the diagramming on the planning phase and the coding on the execution phase. Basic Concepts: Class: Basic template that specifies the properties and behaviours of something (real life or abstract). Object: Particular instance of a class that responds consequently to events. Attribute: Characteristics of the class. Often called instance variables. Method: Algorithm associate to a class that represent a thing that the object does. Subclass: Class based on another class. Inheritance: Process where the subclass gets the attributes and methods from its parent class. Interface: Specific template that enforces certain attributes and methods of a class. Package: Namespace that organizes a set of related classes and interfaces. Event: Alert the application when there is a state change of the object. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 15 of 29

16 ACADEMIC YEAR: REGULATION CBCS Explain Logical Operator with example. Ans: A logical operator (sometimes called a Boolean operator ) in Java programming is an operator that returns a Boolean result that s based on the Boolean result of one or two other expressions. Sometimes, expressions that use logical operators are called compound expressions because the effect of the logical operators is to let you combine two or more condition tests into a single expression. PART C QUESTIONS (10 Marks) 1. What are arrays? How to define and access elements? Explain. (April/May 2014). Ans: Normally, array is a collection of similar type of elements that have contiguous memory location. Java array is an object that contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. Array in java is index based; first element of the array is stored at 0 index. Advantages of Java Array: Code Optimization: It makes the code optimized; we can retrieve or sort the data easily. Random access: We can get any data located at any index position. Disadvantage of Java Array: Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 16 of 29

17 ACADEMIC YEAR: REGULATION CBCS Types of Array in java There are two types of array. Single Dimensional Array Multidimensional Array Single Dimensional Array: Syntax to Declare an Array: datatype[] arr; (or) datatype []arr; (or) datatype arr[]; Instantiation of an Array in java arrayrefvar=new datatype[size]; Example of single dimensional java array Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. class Testarray public static void main(string args[]) int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); Output: RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 17 of 29

18 ACADEMIC YEAR: REGULATION CBCS Declaration, Instantiation and Initialization of Java Array We can declare, instantiate and initialize the java array together by: int a[]=33,3,4,5;//declaration, instantiation and initialization Let's see the simple example to print this array. class Testarray1 public static void main(string args[]) int a[]=33,3,4,5;//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); Output: Multidimensional array in java: In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in java: datatype[][] arrayrefvar; (or) datatype [][]arrayrefvar; (or) datatype arrayrefvar[][]; (or) datatype []arrayrefvar[]; Example to instantiate Multidimensional Array in java int[][] arr=new int[3][3];//3 row and 3 column Example to initialize Multidimensional Array in java arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 18 of 29

19 ACADEMIC YEAR: REGULATION CBCS arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; Example of Multidimensional java array: Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array. class Testarray3 public static void main(string args[]) //declaring and initializing 2D array int arr[][]=1,2,3,2,4,5,4,4,5; //printing 2D array for(int i=0;i<3;i++) for(int j=0;j<3;j++) System.out.print(arr[i][j]+" "); System.out.println(); Output: Explain the characterstics of object oriented programming. (April/May 2014) Class definitions Basic building blocks OOP and a single entity which has data and operations on data together Objects The instances of a class which are used in real functionality its variables and operations Abstraction Specifying what to do but not how to do ; a flexible feature for having a overall view of an object s functionality. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 19 of 29

20 ACADEMIC YEAR: REGULATION CBCS Encapsulation Binding data and operations of data together in a single unit A class adhere this feature Encapsulation-is capaturing data and kepping if safly and securely from outside interfaces Inheritance-this is the process by which a class can be derived from a base class with all the features of base class and some of its own.thiincesr code reusability. Polymorphisam-this is the ability to exist invarias forms the best examble of polymorphsm is the operater overloading. Abstraction-the ability to repracent data at a vary conceptual leval without any details.. Jerald jacob What are the various Loop Constructs available in Java? Explain with example(april 2013) Ans: There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times. Syntax: The syntax of a while loop is: while(boolean_expression) //Statements When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 20 of 29

21 ACADEMIC YEAR: REGULATION CBCS Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example: public class Test public static void main(string args[]) int x = 10; while( x < 20 ) System.out.print("value of x : " + x ); x++; System.out.print("\n"); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 The do...while Loop: A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop is: do //Statements while(boolean_expression); RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 21 of 29

22 ACADEMIC YEAR: REGULATION CBCS Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Example: public class Test public static void main(string args[]) int x = 10; do System.out.print("value of x : " + x ); x++; System.out.print("\n"); while( x < 20 ); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax: The syntax of a for loop is: RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 22 of 29

23 ACADEMIC YEAR: REGULATION CBCS for(initialization; Boolean_expression; update) //Statements Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Example: public class Test public static void main(string args[]) for(int x = 10; x < 20; x = x+1) System.out.print("value of x : " + x ); System.out.print("\n"); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 23 of 29

24 ACADEMIC YEAR: REGULATION CBCS value of x : 17 value of x : 18 value of x : 19 Enhanced for loop in Java: Syntax: The syntax of enhanced for loop is: for(declaration : expression) //Statements Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example: public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) System.out.print( x ); System.out.print(","); System.out.print("\n"); String [] names ="James", "Larry", "Tom", "Lacy"; for( String name : names ) System.out.print( name ); System.out.print(","); This would produce the following result: 10,20,30,40,50, James,Larry,Tom,Lacy, RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 24 of 29

25 ACADEMIC YEAR: REGULATION CBCS The break Keyword: The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: The syntax of a break is a single statement inside any loop: break; Example: public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) break; System.out.print( x ); System.out.print("\n"); This would produce the following result: The continue Keyword: The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 25 of 29

26 ACADEMIC YEAR: REGULATION CBCS In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop: continue; Example: public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) continue; System.out.print( x ); System.out.print("\n"); This would produce the following result: Explain the features of Java. (April/May 2013) Ans: There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand. Simple Object-Oriented Platform independent Secured Robust Architecture neutral Portable RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 26 of 29

27 ACADEMIC YEAR: REGULATION CBCS Dynamic Interpreted High Performance Multithreaded Distributed 1) Compiled and Interpreted:- has both Compiled and Interpreter Feature Program of java is First Compiled and Then it is must to Interpret it.first of all The Program of java is Compiled then after Compilation it creates Bytes Codes rather than Machine Language. Then After Bytes Codes are Converted into the Machine Language is Converted into the Machine Language with the help of the Interpreter So For Executing the java Program First of all it is necessary to Compile it then it must be Interpreter 2) Platform Independent:- Java Language is Platform Independent means program of java is Easily transferable because after Compilation of java program bytes code will be created then we have to just transfer the Code of Byte Code to another Computer. This is not necessary for computers having same Operating System in which the code of the java is Created and Executed After Compilation of the Java Program We easily Convert the Program of the java top the another Computer for Execution. 3) Object-Oriented:- We Know that is purely OOP Language that is all the Code of the java Language is Written into the classes and Objects So For This feature java is Most Popular Language because it also Supports Code Reusability, Maintainability etc. 4) Robust and Secure:- The Code of java is Robust and Means of first checks the reliability of the code before Execution When We trying to Convert the Higher data type into the Lower Then it Checks the Demotion of the Code the It Will Warns a User to Not to do this So it is called as Robust Secure: When we convert the Code from One Machine to Another the First Check the Code either it is Effected by the Virus or not or it Checks the Safety of the Code if code contains the Virus then it will never Executed that code on to the Machine. 5) Distributed:- Java is Distributed Language Means because the program of java is compiled onto one machine can be easily transferred to machine and Executes them on another machine because facility of Bytes Codes So java is Specially designed For Internet Users which uses the Remote Computers For Executing their Programs on local machine after transferring the Programs from Remote Computers or either from the internet. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 27 of 29

28 ACADEMIC YEAR: REGULATION CBCS ) Simple Small and Familiar:- is a simple Language Because it contains many features of other Languages like c and C++ and Java Removes Complexity because it doesn t use pointers, Storage Classes and Go to Statements and java Doesn t support Multiple Inheritance 7) Multithreaded and Interactive:- Java uses Multithreaded Techniques For Execution Means Like in other in Structure Languages Code is Divided into the Small Parts Like These Code of java is divided into the Smaller parts those are Executed by java in Sequence and Timing Manner this is Called as Multithreaded In this Program of java is divided into the Small parts those are Executed by Compiler of java itself Java is Called as Interactive because Code of java Supports Also CUI and Also GUI Programs 8) Dynamic and Extensible Code:- Java has Dynamic and Extensible Code Means With the Help of OOPS java Provides Inheritance and With the Help of Inheritance we Reuse the Code that is Pre-defined and Also uses all the built in Functions of java and Classes 9) Distributed:- Java is a distributed language which means that the program can be design to run on computer networks. Java provides an extensive library of classes for communicating, using TCP/IP protocols such as HTTP and FTP. This makes creating network connections much easier than in C/C++. You can read and write objects on the remote sites via URL with the same ease that programmers are used to when read and write data from and to a file. This helps the programmers at remote locations to work together on the same project. 10) Secure: Java was designed with security in mind. As Java is intended to be used in networked/distributor environments so it implements several security mechanisms to protect you against malicious code that might try to invade your file system. For example: The absence of pointers in Java makes it impossible for applications to gain access to memory locations without proper authorization as memory allocation and referencing model is completely opaque to the programmer and controlled entirely by the underlying run-time platform. 11) Architectural Neutral: One of the key features of Java that makes it different from other programming languages is architectural neutral (or platform independent). This means that the programs written on one platform can run on any other platform without having to rewrite or recompile them. In other words, it follows 'Write-once-run-anywhere' approach. Java programs are compiled into byte-code format which does not depend on any machine architecture but can be easily translated into a specific machine by a Java Virtual Machine (JVM) for that machine. This is a significant advantage when developing applets or applications that are downloaded from the Internet and are needed to run on different systems. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 28 of 29

29 ACADEMIC YEAR: REGULATION CBCS ) Portable: The portability actually comes from architecture-neutrality. In C/C++, source code may run slightly differently on different hardware platforms because of how these platforms implement arithmetic operations. In Java, it has been simplified. Unlike C/C++, in Java the size of the primitive data types are machine independent. For example, an int in Java is always a 32-bit integer, and float is always a 32-bit IEEE 754 floating point number. These consistencies make Java programs portable among different platforms such as Windows, UNIX and Mac. 13) Interpreted: Unlike most of the programming languages which are either complied or interpreted, Java is both complied and interpreted The Java compiler translates a java source file to bytecodes and the Java interpreter executes the translated byte codes directly on the system that implements the Java Virtual Machine. These two steps of compilation and interpretation allow extensive code checking and improved security. 14) High performance: Java programs are complied to portable intermediate form know as bytecodes, rather than to native machine level instructions and JVM executes Java bytecode on any machine on which it is installed. This architecture means that Java programs are faster than program or scripts written in purely interpreted languages but slower than C and C++ programs that compiled to native machine languages. Although in the early releases of Java, the interpretation of by bytecode resulted in slow performance but the advance version of JVM uses the adaptive and Just in time (JIT) compilation technique that improves performance by converting Java bytecodes to native machine instructions on the fly. RAAK/CS/ M.USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-1 QB/VER 1.0 Unit 1 Question Bank Page 29 of 29

30 ACADEMIC YEAR: REGULATION CBCS (UCS41) Java Programming Unit-2 Classes, Objects and Methods Question & Answers PART A QUESTIONS (2 Marks) 1. What is Class? Give the general format.(april 2012) Ans: A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object. All class objects should have the basic class properties. Classes are categories, and objects are items within each category. 2. What is a recursion function?(april/may 2015) Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. 3. What are Java Objects? (April/May 2015) An object is a software bundle of variables and related methods. These real-world objects share two characteristics: they all have state and they all have behavior. For example, dogs have state ( name, color, breed, hungry) and dogs have behavior ( barking, fetching, and slobbering on your newly cleaned slacks). RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 1 of 33

31 ACADEMIC YEAR: REGULATION CBCS Define the term constructor. (April 2012,April/May 2016) A constructor is a bit of code that allows you to create objects from a class. You call the constructor by using the keyword new, followed by the name of the class, followed by any necessary parameters. The syntax for a constructor is: access NameOfClass(parameters) initialization code where access is one of public, protected, "package" (default), or private; NameOfClass must be identical to the name of the class in which the constructor is defined; and the initialization code is ordinary Java declarations and statements. 5. What is Static member? (Nov 2012) The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 2 of 33

32 ACADEMIC YEAR: REGULATION CBCS The static can be: variable (also known as class variable) method (also known as class method) block nested class 6. Define String Class. (Nov 2014) The java.lang.string class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc. Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application. Example: String s="sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original) Output: SACHIN sachin Sachin RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 3 of 33

33 ACADEMIC YEAR: REGULATION CBCS Differentiate public and protected. (Nov 2012) Public Members: If members are declared as public inside a class then such members are accessible to the classes which are inside and outside of the package where this class is visible. This is the least restrictive of all the accessibility modifiers. Protected Members:If members are declared as protected then these are accessible to all classes in the package and to all subclasses of its class in any package where this class is visible. 8. Define Wrapper Class.(April/May 2014) In Java, a wrapper class is defined as a class in which a primitive value is wrapped up. These primitive wrapper classes are used to represent primitive data type values as objects. The Java platform provides wrapper classes for each of the primitive data types. For example, Integer wrapper class holds primitive int data type value. Similarly, Float wrapper class contain float primitive values, Character wrapper class holds a char type value, and Boolean wrapper class represents boolean value. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 4 of 33

34 ACADEMIC YEAR: REGULATION CBCS What is the task of main() method in java? (April/May 2013) A Java program needs to start its execution somewhere. It does so in a static method of a class. This method must be named main() and take an array of String's as parameter. When you start a Java program you usually do so via the command line (console). You call the java command that comes with the JRE, and tells it what Java class to execute, and what arguments to pass to the main() method. The Java application is then executed inside the JVM (or by the JVM some would claim). 10. What is the abstract class?(april/may 2016) A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods ( method with body). A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. Example abstract class: abstract class A 11. Define method/function Overloading. If a class has multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. 12. Define Inheritance. Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties and methods of other classes. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 5 of 33

35 ACADEMIC YEAR: REGULATION CBCS A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass. A subclass can have only one superclass, whereas a superclass may have one or more subclasses. 13. Define method of Overriding. If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, if subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding: Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism 14. What is an instance? Instance variables are declared in a class, but outside a method, constructor or any block.. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. 15. Define autoboxing. (April 2013) Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 6 of 33

36 ACADEMIC YEAR: REGULATION CBCS Define superclass and subclass. (Nov 2013) A sub class has an 'is a' relationship with its superclass. This means that a sub class is a special kind of its super class. When we talk in terms of objects, a sub class object can also be treated as a super class object. And hence, we can assign the reference of a sub class object to a super class variable type. 17. What is the difference between this() and super()? class object. The super keyword in java is a reference variable that is used to refer immediate parent Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable. Usage of java super Keyword 1. super is used to refer immediate parent class instance variable. 2. super() is used to invoke immediate parent class constructor. 3. super is used to invoke immediate parent class method. Usage of java this Keyword 1. this keyword can be used to refer current class instance variable. 2. this() can be used to invoke current class constructor. 3. this keyword can be used to invoke current class method (implicitly) 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this keyword can also be used to return the current class instance. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 7 of 33

37 ACADEMIC YEAR: REGULATION CBCS What is dynamic binding? Binding refers to the linking of a procedural call to the code to be executed in response to the call. Dynamic binding means that the code associated with the given procedure call is not known until the time of the call at runtime. It is associated with the polymorphism and inheritance What is finalize method()? finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. The intent is for finalize() to release system resources such as open files or open sockets before getting collected. Syntax of finalize() method: protected void finalize() //finalize code here; 20. What is meant by static binding? The binding which can be resolved at compile time by compiler is known as static or early binding. All the static, private and final methods have always been bonded at compiletime. 21. What are the different types of access modifier used in Java? (Nov 2012) The basic Accessibility Modifiers are of 4 types in Java. They are RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 8 of 33

38 ACADEMIC YEAR: REGULATION CBCS public 2. protected 3. package/default 4. private There are other Modifiers in Java. They are 1. static 2. abstract 3. final 4. synchronized 5. transient 6. native 7. volatile PART B QUESTIONS 1. Define the term static method with an example. (April/May 2015,2016) If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it. Example of static method: //Program of changing the common property of all objects(static field). class Student9 int rollno; String name; static String college = "ITS"; RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 9 of 33

39 ACADEMIC YEAR: REGULATION CBCS static void change() college = "BBDIT"; Student9(int r, String n) rollno = r; name = n; void display ()System.out.println(rollno+" "+name+" "+college); public static void main(string args[]) Student9.change(); Student9 s1 = new Student9 (111,"Karan"); Student9 s2 = new Student9 (222,"Aryan"); Student9 s3 = new Student9 (333,"Sonoo"); s1.display(); s2.display(); s3.display(); Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 10 of 33

40 ACADEMIC YEAR: REGULATION CBCS How the data could be accessed using abstract class? (April/May 2015) Ans: A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods ( method with body). A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. Example abstract class: abstract class A 3. What are Overriding methods? Give an example. (Nov 2014) If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, if subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding: Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism Rules for Java Method Overriding: method must have same name as in the parent class method must have same parameter as in the parent class. must be IS-A relationship (inheritance). Example Refer Q:No:7 RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 11 of 33

41 ACADEMIC YEAR: REGULATION CBCS State and similarities between interfaces and classes. (Nov 2014) methods only. An interface in java is a blueprint of a class. It has static constants and abstract The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class. Why use Java interface? There are mainly three reasons to use interface. They are given below. It is used to achieve fully abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling. Understanding relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. Simple example of Java interface In this example, Printable interface have only one method, its implementation is provided in the A class. interface printable void print(); RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 12 of 33

42 ACADEMIC YEAR: REGULATION CBCS class A6 implements printable public void print()system.out.println("hello"); public static void main(string args[]) A6 obj = new A6(); obj.print(); Test it Now Output:Hello 5. Describe briefly about Wrapper class with example. (April 2013). A variable of primitive data type is by default passed by value and not by reference. Quite often, there might arise the need to consider such variables of primitive data type as reference types. The solution to this lies in the wrapper classes provided by Java. These classes are used to wrap the data in a new object which contains the value of that variable. This object can then be used in a way similar to how other objects are used. For example, we wrap the number 34 in an Integer object in the following way: Integer intobject = new Integer (34); The Integer class is the wrapper class that has been provided for the int data type. Similarly, there are wrapper classes for the other data types too. The following table lists the data types and their corresponding wrapper classes. Data Type byte short Wrapper Class Byte Short RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 13 of 33

43 ACADEMIC YEAR: REGULATION CBCS int long float double char boolean Integer Long Float Double Character Boolean Note that the wrapper classes of all the primitive data types except int and char have the same name as that of the data type. Creating objects of the Wrapper classes: Integer intobject = new Integer (34); Integer intobject = new Integer ( "34"); Similarly, we have methods for the other seven wrapper classes: bytevalue(), shortvalue(), longvalue(), floatvalue(), doublevalue(), charvalue(), booleanvalue(). 6. What is Autoboxing? Compare this with Auto Unboxing. (Nov 2014) Ans: The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn't need to write the conversion code. Advantage of Autoboxing and Unboxing: No need of conversion between primitives and Wrappers manually so less coding is required. Simple Example of Autoboxing in java: class BoxingExample1 RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 14 of 33

44 ACADEMIC YEAR: REGULATION CBCS public static void main(string args[]) int a=50; Integer a2=new Integer(a);//Boxing Integer a3=5;//boxing System.out.println(a2+" "+a3); Output: 50 5 Simple Example of Unboxing in java: The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let's see the example of unboxing: class UnboxingExample1 public static void main(string args[]) Integer i=new Integer(50); int a=i; System.out.println(a); Output: 50 RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 15 of 33

45 ACADEMIC YEAR: REGULATION CBCS Write a program in JAVA to implement Overriding. (Nov 2014) class Bank int getrateofinterest()return 0; class SBI extends Bank int getrateofinterest()return 8; class ICICI extends Bank int getrateofinterest()return 7; class AXIS extends Bank int getrateofinterest()return 9; class Test2 public static void main(string args[]) SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getrateofinterest()); System.out.println("ICICI Rate of Interest: "+i.getrateofinterest()); System.out.println("AXIS Rate of Interest: "+a.getrateofinterest()); Output: SBI Rate of Interest: 8 RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 16 of 33

46 ACADEMIC YEAR: REGULATION CBCS ICICI Rate of Interest: 7 AXIS Rate of Interest: 9 8. Describe Inner Class with example. Ans: Java inner class or nested class is a class i.e. declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the members of outer class including private data members and methods. Syntax of Inner class: class Java_Outer_class... class Java_Inner_class Advantage of java inner classes: There are basically three advantages of inner classes in java. They are as follows: 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 17 of 33

47 ACADEMIC YEAR: REGULATION CBCS ) Code Optimization: It requires less code to write. Example Program: class TestMemberOuter1 private int data=30; class Inner void msg()system.out.println("data is "+data); void display() Inner in=new Inner(); in.msg(); public static void main(string args[]) TestMemberOuter1 obj=new TestMemberOuter1(); obj.display(); Output: data is Describe various String manipulation in Java. Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareto, intern, substring etc. In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example: RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 18 of 33

48 ACADEMIC YEAR: REGULATION CBCS char[] ch='j','a','v','a','t','p','o','i','n','t'; String s=new String(ch); is same as: String s="javatpoint"; Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. String class is used to create string object. There are two ways to create String object: By string literal By new keyword By String Literal: Java String literal is created by using double quotes. For Example: String s="welcome"; For example: String s1="welcome"; String s2="welcome"; //will not create new instance By new keyword: String s=new String("Welcome"); //creates two objects and one reference variable Example: public class StringExample public static void main(string args[]) String s1="java";//creating string by java string literal RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 19 of 33

49 ACADEMIC YEAR: REGULATION CBCS char ch[]='s','t','r','i','n','g','s'; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); Output: java strings example 10. Write a program in java to count the number of characters in a string. import java.io.*; class count void main()throws IOException BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the String"); String s=br.readline(); int i,l,c1=0,c2=0,c3=0,sp=0; char ch; l=s.length(); for(i=0;i<l;i++) RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 20 of 33

50 ACADEMIC YEAR: REGULATION CBCS ch=s.charat(i); if(character.isletter(ch)) ++c1; else if(character.isdigit(ch)) ++c2; else if(ch==' ') ++sp; else ++c3; System.out.println("no of Letter="+c1); System.out.println("no of Digit="+c2); System.out.println("no of Spaces="+sp); System.out.println("no of Symbol="+c3); 11. Explain the constructor with example. Ans: Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Rules for creating java constructor: There are basically two rules defined for the constructor. Constructor name must be same as its class name Constructor must have no explicit return type Types of java constructors: RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 21 of 33

51 ACADEMIC YEAR: REGULATION CBCS There are two types of constructors: Default constructor (no-arg constructor) Parameterized constructor Java Default Constructor: A constructor that have no parameter is known as default constructor. Syntax of default constructor: <class_name>() Example of default constructor class Bike1 Bike1()System.out.println("Bike is created"); public static void main(string args[]) Bike1 b=new Bike1(); Output: Bike is created RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 22 of 33

52 ACADEMIC YEAR: REGULATION CBCS Rule: If there is no constructor in a class, compiler automatically creates a default constructor. Purpose of default constructor: Default constructor provides the default values to the object like 0, null etc. depending on the type. Example of default constructor that displays the default values: class Student3 int id; String name; void display()system.out.println(id+" "+name); public static void main(string args[]) Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); Output: 0 null 0 null RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 23 of 33

53 ACADEMIC YEAR: REGULATION CBCS Explain the concept of recursion with suitable example. Ans: Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is 1 2 3, or 6. Here is how a factorial can be computed by use of a recursive method. Example: class Factorial int fact(int n) int result; if ( n ==1) return 1; result = fact (n-1) * n; return result; class Recursion public static void main (String args[]) Factorial f =new Factorial(); System.out.println( Factorial of 3 is + f.fact(3)); System.out.println( Factorial of 3 is + f.fact(4)); System.out.println( Factorial of 3 is + f.fact(5)); The output from this program is shown here: RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 24 of 33

54 ACADEMIC YEAR: REGULATION CBCS Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is Write a short note on parameterized constructor. Java parameterized constructor: A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects. Example of parameterized constructor: In this example, we have created the constructor of Student class that has two parameters. We can have any number of parameters in the constructor. class Student4 int id; String name; Student4(int i,string n) id = i; name = n; void display()system.out.println(id+" "+name); public static void main(string args[]) Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 25 of 33

55 ACADEMIC YEAR: REGULATION CBCS s2.display(); Output: 111 Karan 222 Aryan PART C QUESTIONS 1. Explain types of Inheritance with example. (April/May 2013). Ans: Inheritance in Java: The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. Why use inheritance in java: For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Syntax of Java Inheritance: class Subclass-name extends Superclass-name RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 26 of 33

56 ACADEMIC YEAR: REGULATION CBCS //methods and fields The extends keyword indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass. Example class Employee float salary=40000; class Programmer extends Employee int bonus=10000; public static void main(string args[]) Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); Programmer salary is: Bonus of programmer is:10000 Types of inheritance in java: On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 27 of 33

57 ACADEMIC YEAR: REGULATION CBCS Types of inheritance in java: Note: Multiple inheritance is not supported in java through class. When a class extends multiple classes i.e. known as multiple inheritance. Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 28 of 33

58 ACADEMIC YEAR: REGULATION CBCS Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now. class A void msg()system.out.println("hello"); class B void msg()system.out.println("welcome"); class C extends A,B//suppose if it were Public Static void main(string args[]) C obj=new C(); obj.msg();//now which msg() method would be invoked? Output: Compile Time Error 2. Explain how the String Class differ from StringBuffer Class. (Nov 2012) String class objects work with complete strings instead of treating them as character arrays. Convert variables of type char to string objects by using gstr = Character.toString(c);. String class objects are immutable (ie. read only). When changes are made to a string, a new object is created and the old one is disused. This causes extraneous garbage collection. Use StringBuffer or StringBuilder instead of String objects when modification is frequent. StringBuffer class: RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 29 of 33

59 ACADEMIC YEAR: REGULATION CBCS The StringBuffer class is used to created mutable ( modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be changed. Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously.so it is safe and will result in an order. Commonly used Constructors of StringBuffer class: StringBuffer(): creates an empty string buffer with the initial capacity of 16. StringBuffer(String str): creates a string buffer with the specified string. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length. 3. What is method overloading? Explain by giving a suitable example. Ans: If a class has multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. Advantage of Method Overloading: Method overloading increases the readability of the program. Different ways to overload the method: There are two ways to overload the method in java By changing number of arguments RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 30 of 33

60 ACADEMIC YEAR: REGULATION CBCS By changing the data type Example of Method Overloading by changing the no. of arguments: class Calculation void sum(int a,int b)system.out.println(a+b); void sum(int a,int b,int c)system.out.println(a+b+c); public static void main(string args[]) Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); Output: Example of Method Overloading by changing data type of argument: In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments. class Calculation2 void sum(int a,int b)system.out.println(a+b); void sum(double a,double b)system.out.println(a+b); public static void main(string args[]) Calculation2 obj=new Calculation2(); RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 31 of 33

61 ACADEMIC YEAR: REGULATION CBCS obj.sum(10.5,10.5); obj.sum(20,20); Output: Explain the Static and Finalize methods with suitable example. The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: variable (also known as class variable) method (also known as class method) block nested class finalize() method The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as: protected void finalize() public class TestGarbage1 public void finalize()system.out.println("object is garbage collected"); RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 32 of 33

62 ACADEMIC YEAR: REGULATION CBCS public static void main(string args[]) TestGarbage1 s1=new TestGarbage1(); TestGarbage1 s2=new TestGarbage1(); s1=null; s2=null; System.gc(); ***** RAAK/CS/ M. USHA/II YEAR/IV Sem/UCS41 /JAVA PROGRAMMING /UNIT-2 QB/VER 2.0 Unit 2 Question and Answer Bank Page 33 of 33

63 Academic Year: Regulation CBCS Define Applet. SCS41 Java Programming Unit-III Question & Answers PART A An applet is a small Internet-based program written in Java, a programming language for the Web, which can be downloaded by any computer. The applet is also able to run in HTML. The applet is usually embedded in an HTML page on a Web site and can be executed from within a browser. 2. Give the meaning for JcheckBox in Java. Nov 12 A JCheckBox is a graphical component that can be in either an on (true) or off (false) state. The class JCheckBox is an implementation of a check box - an item that can be selected or deselected, and which displays its state to the user. 3. Define AWT? Give example. April 11 The Abstract Window Toolkit (AWT) package in Java enables the programmers to create GUI-based applications. It contains a number of classes that help to implement common Window-based tasks, such as manipulating windows, adding scroll bars, buttons, list items, text boxes, etc,. 4. What is the use of JButton class? List its possible constructors. April 13 This class creates a labeled button. The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can have Image also. JButton(). JButton(Action a). JButton(String text). 5. What are the events to be implemented to handle mouse events? April 13 Handling mouse events in Java is split between three different event listeners. The MouseListener interface is used to track when a mouse is entering or leaving the area occupied by a graphical component, and when a mouse button is pressed and released. The MouseMotionListener is used to track the mouse cursor as it is pressed and dragged or just moves around a graphical component's area. Finally, the MouseWheelListener tracks the movement of a mouse wheel. 6. What is meant by Event Listeners? The event listener object contains methods for receiving and processing event notifications sent by the source object. These methods are implemented from the corresponding listener interface contained in the java.awt.event package. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 1 of 26

64 Academic Year: Regulation CBCS What is meant by Event Classes? All the events in Java have corresponding event classes associated with them. Each of these classes is derived from one single super class, i.e., EventObject. It is contained in the java.util package. 8. What is GUI? Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying Operating System also offers GUI via window, frame, Panel, Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. 9. List out some of the GUI based applications. Some of the GUI based applications are: Automated Teller Machine (ATM) Airline Ticketing System Information Kiosks at railway stations Mobile Applications Navigation Systems 10. List out any two advantages of GUI. GUI provides multitasking environment. Using GUI it is easier to control and navigate the operating system which becomes very slow in command user interface. GUI can be easily customized. 11. What is a Frame in AWT? A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and resizing corners. 12. Define event. Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, ect. 13. What is JoptionPane?(April 14) JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something. 14. What is the use of JComboBox?(April 14) A JComboBox component presents the user with to show up menu of choices. The class JComboBox is a component which combines a button or editable field and a drop-down list. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 2 of 26

65 Academic Year: Regulation CBCS How to define JavaTextArea? (April 14) A JTextArea object is a text component that allows for the editing of a multiple lines of text.following is the declaration for javax.swing.jtextarea class, public class JTextArea extends JTextComponent 16. What is adapter class? Nov/Dec 2016 RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 3 of 26

66 Academic Year: Regulation CBCS PART B 1. Briefly explain about the adapter classes in java. Nov 12 o Java provides a special feature, called an adapter class that can simplify the creation of event handlers in certain situations. o An adapter class provides an empty implementation of all methods in an event listener interface. o Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. o You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested. o For example, the MouseMotionAdapter class has two methods, mousedragged() and mousemoved(). o The signatures of these empty methods are exactly as defined in the MouseMotionListener interface. o If you were interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mousedragged(). The empty implementation of mousemoved ( ) would handle the mouse motion events for us. o The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or browser when the mouse is clicked or dragged. o However, all other mouse events are silently ignored. The program has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of MyMouseAdapter and registers that object to receive notifications of mouse events. o It also creates an instance of MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of the constructors take a reference to the applet as an argument. MyMouseAdapter implements the mouseclicked( ) method. o The other mouse events are silently ignoring d by code inherited from the MouseAdapter class. S. No. Adapter Classes Listener Interface ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener o MyMouseMotionAdapter implements the mousedragged( ) method. The other mouse motion event is silently ignored by code inherited from the MouseMotionAdapter class. o Note that both of our event listener classes save a reference to the applet. o This information is provided as an argument to their constructors and is used later to invoke the showstatus( ) method. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 4 of 26

67 Academic Year: Regulation CBCS import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="adapterdemo" width=300 height=100> </applet> */ public class AdapterDemo extends Applet public void init() addmouselistener(new MyMouseAdapter(this)); addmousemotionlistener(new MyMouseMotionAdapter(this)); class MyMouseAdapter extends MouseAdapter AdapterDemo adapterdemo; public MyMouseAdapter(AdapterDemo adapterdemo) this.adapterdemo = adapterdemo; // Handle mouse clicked. public void mouseclicked(mouseevent me) adapterdemo.showstatus("mouse clicked"); class MyMouseMotionAdapter extends MouseMotionAdapter AdapterDemo adapterdemo; public MyMouseMotionAdapter(AdapterDemo adapterdemo) this.adapterdemo = adapterdemo; // Handle mouse dragged. public void mousedragged(mouseevent me) adapterdemo.showstatus("mouse dragged"); 2. Write a note on Mouse Event Handling with example. Nov 12 Java also allows us to listen for mouse events. Essentially, we'd use these events to know where the mouse is, either with respect to a GUI component or in terms of x and y coordinates. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 5 of 26

68 Academic Year: Regulation CBCS Here's how we'll set up this mouse event handling: 1. Add implements MouseListener. 2. Mouse listening is based upon a particular component. For an applet, that's the whole applet. Thus, we only need the call addmouselistener(this);. 3. Finally, we need to write code to handle the event. Class MouseEvent has accessors getx() and gety() that get us the coordinates of where the event occurred. We can store these an use them in other methods. (For example, we could store them and use them in paint() to draw something.) This time, though, there are five different mouse event methods we must implement: o mousepressed(), which is triggered when the mouse is on the component. o mouseclicked(), which is triggered when the mouse is pressed and released on the component. (mousepressed() is called first.) o mousereleased(), which is triggered when the mouse is released on the component. (mousepressed() must have been called first.) o mouseentered(), which is triggered upon entry to the component. o mouseexited(), which is triggered upon leaving the component. o Note that when we implement the MouseListener interface, we must provide all five methods. The full headers look like this: public void mousepressed(mouseevent e) public void mouseclicked(mouseevent e) public void mousereleased(mouseevent e) public void mouseentered(mouseevent e) public void mouseexited(mouseevent e) 3. Explain about five event classes available in java Nov 11, April 12 AWT Event It is the root event class for all AWT events. This class and its subclasses supersede the original java.awt.event class. This class is defined in java.awt package. This class has a method named getid() that can be used to determine the type of event. Following is the declaration for java.awt.awtevent class: public class AWTEvent extends EventObject Following are the fields for java.awt.awtevent class, static int ACTION_FIRST -- The first number in the range of ids used for action events. static long ACTION_EVENT_MASK -- The event mask for selecting action events. static long ADJUSTMENT_EVENT_MASK -- The event mask for selecting adjustment events. static long COMPONENT_EVENT_MASK -- The event mask for selecting component events. Constructors RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 6 of 26

69 Academic Year: Regulation CBCS AWTEvent(Event event) AWTEvent(java.lang.Object source, int id) Methods int getid() Returns the event type. String tostring() Return a String representation of this object. ActionEvent This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked. Class declaration public class ActionEvent extends AWTEvent Fields Following are the fields for java.awt.event.actionevent class: static int ACTION_FIRST -- The first number in the range of ids used for action events. static int ACTION_LAST -- The last number in the range of ids used for action events. static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured. static int ALT_MASK -- The alt modifier. static int CTRL_MASK -- The control modifier. static int META_MASK -- The meta modifier. static int SHIFT_MASK -- The shift modifier. Constructors ActionEvent(Object source, int id, String command) ActionEvent(Object source, int id, String command, int modifiers) Methods String getactioncommand() int getmodifiers() long getwhen() MouseEvent Class This event indicates a mouse action occurred in a component. This low-level event is generated by a component object for Mouse Events and Mouse motion events. a mouse button is pressed a mouse button is released a mouse button is clicked (pressed and released) a mouse cursor enters the unobscured part of component's geometry a mouse cursor exits the unobscured part of component's geometry RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 7 of 26

70 Academic Year: Regulation CBCS a mouse is moved the mouse is dragged Following is the declaration for java.awt.event.mouseevent class: public class MouseEvent extends InputEvent Fields Following are the fields for java.awt.event.mouseevent class, static int BUTTON1 --Indicates mouse button #1; used by getbutton() static int BUTTON2 --Indicates mouse button #2; used by getbutton() static int BUTTON3 --Indicates mouse button #3; used by getbutton() static int MOUSE_CLICKED --The "mouse clicked" event static int MOUSE_DRAGGED --The "mouse dragged" event Constructors MouseEvent(Component source, int id, long when, int modifier, int x, int y, int clickcount, Boolean popuptrigger) MouseEvent(Component source, int id, long when, int modifier, int x, int y, int clickcount, Boolean popuptrigger, int button) Methods int getbutton() point getpoint() int getx() int gety() TextEvent Class The object of this class represents the text events. The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information. Following is the declaration for java.awt.event.textevent class, public class TextEvent extends AWTEvent Fields Following are the fields for java.awt.event.textevent class: static int TEXT_FIRST --The first number in the range of ids used for text events. static int TEXT_LAST --The last number in the range of ids used for text events. static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed. Constructors TextEvent(Object source, int id) Methods String paramstring() RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 8 of 26

71 Academic Year: Regulation CBCS PaintEvent The Class PaintEvent used to ensure that paint/update method calls are serialized along with the other events delivered from the event queue Following is the declaration for java.awt.event.paintevent class, public class PaintEvent extends ComponentEvent Field Following are the fields for java.awt.component class, static int PAINT -- The paint event type. static int PAINT_FIRST -- Marks the first integer id for the range of paint event ids. static int PAINT_LAST -- Marks the last integer id for the range of paint event ids. static int UPDATE -- The update event type. Constructors PaintEvent(Component source, int id, Rectangle updaterect) Methods void setupdaterect(rectangle updaterect) String paramstring() 4. What is an Itemlistener interface? Explain it briefly. Nov 11, April 12, April 14 The class which processes the ItemEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the additemlistener() method. When the action event occurs, that object's itemstatechanged method is invoked. Following is the declaration for java.awt.event. ItemListener interface, public interface ItemListener extends EventListener Methods inherited This interface inherits methods from the following interfaces, java.awt.eventlistener ItemListener Example import java.awt.*; import java.awt.event.*; public class AwtListenerDemo private Frame mainframe; private Label headerlabel; private Label statuslabel; private Panel controlpanel; public AwtListenerDemo() preparegui(); RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 9 of 26

72 Academic Year: Regulation CBCS public static void main(string[] args) AwtListenerDemo awtlistenerdemo = new AwtListenerDemo(); awtlistenerdemo.showitemlistenerdemo(); private void preparegui() mainframe = new Frame("Java AWT Examples"); mainframe.setsize(400,400); mainframe.setlayout(new GridLayout(3, 1)); mainframe.addwindowlistener(new WindowAdapter() public void windowclosing(windowevent windowevent) System.exit(0); ); headerlabel = new Label(); headerlabel.setalignment(label.center); statuslabel = new Label(); statuslabel.setalignment(label.center); statuslabel.setsize(350,100); controlpanel = new Panel(); controlpanel.setlayout(new FlowLayout()); mainframe.add(headerlabel); mainframe.add(controlpanel); mainframe.add(statuslabel); mainframe.setvisible(true); private void showitemlistenerdemo() headerlabel.settext("listener in action: ItemListener"); Checkbox chkapple = new Checkbox("Apple"); Checkbox chkmango = new Checkbox("Mango"); Checkbox chkpeer = new Checkbox("Peer"); chkapple.additemlistener(new CustomItemListener()); chkmango.additemlistener(new CustomItemListener()); chkpeer.additemlistener(new CustomItemListener()); controlpanel.add(chkapple); controlpanel.add(chkmango); controlpanel.add(chkpeer); mainframe.setvisible(true); class CustomItemListener implements ItemListener public void itemstatechanged(itemevent e) statuslabel.settext(e.getitem() +" Checkbox: " + RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 10 of 26

73 Academic Year: Regulation CBCS Output (e.getstatechange()==1?"checked":"unchecked")); 5. Describe any five GUI components with example. April 11 a) Label Class Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end user in any way. Following is the declaration for java.awt.label class: public class Label extends Component implements Accessible Field Following are the fields for java.awt.component class, static int CENTER -- Indicates that the label should be centered. static int LEFT -- Indicates that the label should be left justified. static int RIGHT -- Indicates that the label should be right justified. Constructors Label() Label(String text) Label(String text, int alignment) Methods void addnotify() int getalignment() String gettext() void settext() b) Button Class Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processevent on the button. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 11 of 26

74 Academic Year: Regulation CBCS The button's processevent method receives all events for the button; it passes an action event along by calling its own processactionevent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button. If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and register the new listener to receive events from this button, by calling the button's addactionlistener method. The application can make use of the button's action command as a messaging protocol. Following is the declaration for java.awt.button class: public class Button extends Component implements Accessible Constructors Button() Button(String text) Methods String getactioncommand() void setactioncommand(string command) String getlabel() void setlabel(string label) Example import java.applet.applet; import java.awt.button; /*<applet code="createawtbuttonexample" width=200 height=200> </applet>*/ public class CreateAWTButtonExample extends Applet public void init() Button button1 = new Button(); button1.setlabel("my Button 1"); Button button2 = new Button("My Button 2"); add(button1); add(button2); Output c) CheckBox Class RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 12 of 26

75 Academic Year: Regulation CBCS Checkbox control is used to turn an option on (true) or off (false). There is label for each checkbox representing what the checkbox does. The state of a checkbox can be changed by clicking on it. Following is the declaration for java.awt.checkbox class, public class Checkbox extends Component implements ItemSelectable, Accessible Constructors Checkbox() Checkbox(String label) Checkbox(String label, boolean state) Methods void additemlistener(itemlistener i) String getlabel() void setstate(boolean state ) void setcheckboxgroup(checkboxgroup c) CheckBox Example import java.applet.applet; import java.awt.checkbox; import java.awt.graphics; /*<applet code="getcheckboxstate" width=200 height=200> </applet>*/ public class GetCheckboxState extends Applet Checkbox checkbox1 = null; Checkbox checkbox2 = null; public void init() checkbox1 = new Checkbox("My Checkbox 1"); checkbox2 = new Checkbox("My Checkbox 2", true); add(checkbox1); add(checkbox2); public void paint(graphics g) g.drawstring("is checkbox 1 selected? " + checkbox1.getstate(), 10, 80); g.drawstring("is checkbox 2 selected? " + checkbox2.getstate(), 10, 100); Output d) CheckBoxGroup Class The CheckboxGroup class is used to group the set of checkbox. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 13 of 26

76 Academic Year: Regulation CBCS Following is the declaration for java.awt.checkboxgroup class: public class CheckboxGroup extends Object implements Serializable Constructors CheckBoxGroup() Methods Checkbox getcurrent() Checkbox getselectedcheckbox() void setselectedcheckbox(checkbox box) Example import java.applet.applet; import java.awt.checkbox; import java.awt.checkboxgroup; /*<applet code="createradiobuttonsexample" width=200 height=200> </applet>*/ public class CreateRadioButtonsExample extends Applet public void init() CheckboxGroup lnggrp = new CheckboxGroup(); Checkbox java = new Checkbox("Java", lnggrp, true); Checkbox cpp = new Checkbox("C++", lnggrp, true); Checkbox vb = new Checkbox("VB", lnggrp, true); add(java); add(cpp); add(vb); Output e) List Class The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items. Following is the declaration for java.awt.list class: public class List extends Component implements ItemSelectable, Accessible Constructors List() RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 14 of 26

77 Academic Year: Regulation CBCS List(int rows) Methods void add(string item) void addactionlistener(actionlistener l) void additem(string item) void clear() 6. Write the Java Code to implement the use of JCheckBox. April 13 The class JCheckBox is an implementation of a check box - an item that can be selected or deselected, and which displays its state to the user. Following is the declaration for javax.swing.jcheckbox class, public class JCheckBox extends JToggleButton implements Accessible Field Following are the fields for javax.swing.jcheckbox class: static String BORDER_PAINTED_FLAT_CHANGED_PROPERTY -- Identifies a change to the flat property. Constructors JCheckBox() JCheckBox(Action a) JCheckBox(Icon icon) JCheckBox(String text) Methods boolean isborderpaintedflat() String getuiclassid() void updateui() JCheckBox Example JCheckBox checkbox = new JCheckBox("Enable logging"); // add to a container frame.add(checkbox); // set state checkbox.setselected(true); // check state if (checkbox.isselected()) // do something... else // do something else... RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 15 of 26

78 Academic Year: Regulation CBCS How java makes different kinds of events? April 14 Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen. Types of Event The events can be broadly classified into two categories, Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc. Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events. Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events. Let's have a brief introduction to this model. The Delegation Event Model has the following key participants namely Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to its handler. Java provide as with classes for source object. Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received, the listener processes the event an then returns. The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model, Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners that want to receive them. 8. Describe the function of JLabel with an example. April 14 The class JLabel can display text, an image, or both. Label's contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default. Following is the declaration for javax.swing.jlabel class: public class JLabel extends JComponent implements SwingConstants, Accessible Field RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 16 of 26

79 Academic Year: Regulation CBCS Following are the fields for javax.swing.jlabel class: protected Component labelfor Constructors JLabel() JLabel(Icon image) JLabel(String text) Class methods Icon getdisabledicon() int gethorizontalalignment() int gethorizontaltextposition() Icon geticon() String gettext() Example Program import java.awt.gridlayout; import java.awt.event.windowadapter; import java.awt.event.windowevent; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jframe; import javax.swing.imageicon; public class JlabelDemo extends JPanel JLabel jlblabel1, jlblabel2, jlblabel3; public JlabelDemo() ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG", "My Website"); // Creating an Icon setlayout(new GridLayout(3, 1)); // 3 rows, 1 column Panel having Grid Layout jlblabel1 = new JLabel("Image with Text", icon, JLabel.CENTER); // We can position of the text, relative to the icon: jlblabel1.setverticaltextposition(jlabel.bottom); jlblabel1.sethorizontaltextposition(jlabel.center); jlblabel2 = new JLabel("Text Only Label"); jlblabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlblabel1); add(jlblabel2); add(jlblabel3); public static void main(string[] args) JFrame frame = new JFrame("jLabel Usage Demo"); frame.addwindowlistener(new WindowAdapter() // Shows code to Add Window Listener public void windowclosing(windowevent e) RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 17 of 26

80 Academic Year: Regulation CBCS Output System.exit(0); ); frame.setcontentpane(new JlabelDemo()); frame.pack(); frame.setvisible(true); RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 18 of 26

81 Academic Year: Regulation CBCS PART C 1. Discuss the various GUI components available in java. Nov 12 Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying Operating System also offers GUI via window, frame, Panel, Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as components. Using these components we can create an interactive user interface for an application. GUI provides result to end user in response to raised events.gui is entirely based events. For example clicking over a button, closing a window, opening a window, typing something in a textarea etc. These activities are known as events.gui makes it easier for the end user to use an application. It also makes them interesting. Examples of GUI based Applications Following are some of the examples for GUI based applications. o Automated Teller Machine (ATM) o Airline Ticketing System o Information Kiosks at railway stations o Mobile Applications o Navigation Systems Advantages of GUI over CUI GUI provides graphical icons to interact while the CUI (Character User Interface) offers the simple text-based interfaces. GUI makes the application more entertaining and interesting on the other hand CUI does not. GUI offers click and execute environment while in CUI every time we have to enter the command for a task. New user can easily interact with graphical user interface by the visual indicators but it is difficult in Character user interface. GUI offers a lot of controls of file system and the operating system while in CUI you have to use commands which are difficult to remember. Windows concept in GUI allow the user to view, manipulate and control the multiple applications at once while in CUI user can control one task at a time. GUI provides multitasking environment so as the CUI also does but CUI does not provide same ease as the GUI does. Using GUI it is easier to control and navigate the operating system which becomes very slow in command user interface. GUI can be easily customized. Basic Terminologies RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 19 of 26

82 Academic Year: Regulation CBCS Every AWT controls inherits properties from Component class. AWT UI Elements Following is the list of commonly used controls while designed GUI using AWT. RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 20 of 26

83 Academic Year: Regulation CBCS Discuss the different types of event handling in java. April 11, April 12 Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling. Event classes and Listener interfaces Event Classes Listener Interfaces ActionEvent ActionListener MouseEvent MouseListener and MouseMotionListener MouseWheelEvent MouseWheelListener KeyEvent KeyListener ItemEvent ItemListener TextEvent TextListener AdjustmentEvent AdjustmentListener WindowEvent WindowListener ComponentEvent ComponentListener ContainerEvent ContainerListener FocusEvent FocusListener Steps to perform EventHandling: Following steps are required to perform event handling: Implement the Listener interface and overrides its methods Register the component with the Listener For registering the component with the Listener, many classes provide the registration methods. For example: Button public void addactionlistener(actionlistener a) MenuItem public void addactionlistener(actionlistener a) TextField public void addactionlistener(actionlistener a) public void addtextlistener(textlistener a) TextArea public void addtextlistener(textlistener a) Checkbox public void additemlistener(itemlistener a) Choice public void additemlistener(itemlistener a) List public void addactionlistener(actionlistener a) public void additemlistener(itemlistener a) EventHandling Codes We can put the event handling code into one of the following places, Same class Other class Annonymous class RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 21 of 26

84 Academic Year: Regulation CBCS Example of event handling within class import java.awt.*; import java.awt.event.*; class AEvent extends Frame implements ActionListener TextField tf; AEvent() tf=new TextField(); tf.setbounds(60,50,170,20); Button b=new Button("click me"); b.setbounds(100,120,80,30); b.addactionlistener(this); add(b); add(tf); setsize(300,300); setlayout(null); setvisible(true); public void actionperformed(actionevent e) tf.settext("welcome"); public static void main(string args[]) new AEvent(); public void setbounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc. Output RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 22 of 26

85 Academic Year: Regulation CBCS Explain the various Event Listener Interfaces with example. April 13 The Event listener represents the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject. EventListner interface It is a marker interface which every listener interface has to extend. This class is defined in java.util package. Following is the declaration for java.util.eventlistener interface: public interface EventListener AWT Event Listener Interfaces Following is the list of commonly used event listeners. a) ActionListener Interface The class which processes the ActionEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addactionlistener() method. When the action event occurs, that object's action Performed method is invoked. Interface declaration Following is the declaration for java.awt.event.actionlistener interface: public interface ActionListener extends EventListener Interface methods RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 23 of 26

86 Academic Year: Regulation CBCS ActionListener Example import java.awt.*; import java.awt.event.*; class ButtonAction extends Frame Button b1,b2,b3; Frame thisframe; public ButtonAction() // Set the frame properties settitle("button with ActionListener Demo"); setsize(400,400); setlayout(new FlowLayout()); setlocationrelativeto(null); setvisible(true); // Assign current object thisframe=this; // Create buttons b1=new Button("Minimize"); b2=new Button("Maximize/Restore"); b3=new Button("Exit"); // Add buttons add(b1); add(b2); add(b3); // Add action listeners to buttons b1.addactionlistener(new ActionListener() public void actionperformed(actionevent ae) setstate(frame.iconified); ); b2.addactionlistener(new ActionListener() public void actionperformed(actionevent ae) if(thisframe.getextendedstate()==frame.normal) setextendedstate(frame.maximized_both); else if(thisframe.getextendedstate()==frame.maximized_both) setextendedstate(frame.normal); ); b3.addactionlistener(new ActionListener() public void actionperformed(actionevent ae) RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 24 of 26

87 Academic Year: Regulation CBCS System.exit(0); ); public static void main(string args[]) new ButtonAction(); Output 4. Develop an application on your own to exhibit the usage of JLabel, JTextfield, and JTextarea in java. April 14 import java.awt.*; import javax.swing.*; public class Label_TextField_TextArea public static void main(string[] args) JFrame f = new JFrame("My First GUI"); JLabel L; L = new JLabel("Hello World!"); // Make a JLabel component f.getcontentpane().add(l); // Stick f.setsize(400, 300); f.setvisible(true); JFrame h = new JFrame("My Second GUI"); JTextField x; x = new JTextField(); // Make a JTextField h.getcontentpane().add(x); // Stick x.seteditable(false); // Output only x.settext("hello World"); h.setsize(400, 300); RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 25 of 26

88 Academic Year: Regulation CBCS h.setvisible(true); JFrame g= new JFrame("My GUI"); JTextArea m; m = new JTextArea(); // Make a JTextArea g.getcontentpane().add(m); // Stick m.seteditable(true); // Output only m.settext("hello World"); m.append("\n"); m.append("hello Again"); g.setsize(400, 300); g.setvisible(true); RAAK / B. Sc. (CS) / M. Usha / II Year/ IV Sem/ SCS41/ Java Programming / Unit-III Q & A Unit III Question and Answer Page 26 of 26

89 Academic Year: Regulation CBCS What is flow layout? (April 12) UCS41 Java Programming Unit-IV Question & Answers PART A This is the default layout manager for an applet. The FlowLayout class places controls in a row that is centered in the available space. If the controls cannot fit in the current row, another row is started. 2. What is the syntax of drawline() method? (April 13, April 14,Nov/Dec 2016) The general form is: void drawline ( int x1, int y1, int x2, int y2 ) This method takes two pairs of coordinates. (x1, y1) and (x2, y2) as arguments and draws a line between them. 3. How to select a font? Give example. (April 13) The class Font is used to set the fonts used in the graphical object. The Font class defines the following constructor: Font ( String name, int style, int size ) Example: Font f = new Font ( Arial, Font.ITALIC, 40); 4. Describe the argument used in the method drawrect(). (Nov 12) void drawrect ( int x, int y, int w, int h ) Here, the first two arguments x and y represent the x and y coordinates of the top left corner of the rectangle. The last two arguments w and h represent the width and height of the rectangle. 5. How to define menus?(april 14) Menus allow the user to perform actions without unnecessarily cluttering a GUI. Example: JMenu file = JMenu( File ); File.add( New ); File.add( Open ); File.add( Save ); File.add( Save As ); 6. What are the different types of layout managers? The various layout managers are as follows: i. Flow Layout ii. Border layout iii. Grid Layout RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 1 of 22

90 Academic Year: Regulation CBCS List FlowLayout constructors. (Apr/May 2016) The Flow Layout class has three constructors. They are: a) FlowLayout ( ) b) FlowLayout ( int alignment ) c) FlowLayout ( int alignment, int h, int v ) 8. What is meant by Border Layout? The Border Layout class allows geographic terms: North, South, East, West and Center. The Border Layout class has two constructors. Namely, BorderLayout ( ) : It is used to create default border layout. BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal and vertical space between the components. 9. Define Layout manager.(noc/dec 2016) Layout Manager are special objects that determine how the components of a container are organized. A Layout Manager is an instance of any class that implements the Layout Manager interface. The Layout Managers is set by the setlayout() method. The general format is: void setlayout ( LayoutManager obj ) 10. List the different regions followed in Border Layout. The BorderLayout defines the following regions: BorderLayout. NORTH BorderLayout. SOUTH BorderLayout. EAST BorderLayout. WEST BorderLayout. CENTER 11. Define Grid layout. The Grid Layout class automatically arranges components in a grid. The Grid Layout Manager organizes the display into a rectangular grid. All components of the grid is created of the grid is created with equal size. 12. What is Graphics Class in Java? Class graphics is an abstract class. When Java is implemented on each platform, a subclass of Graphics is created that implements the drawing capabilities. This implementation is hidden from us by Class Graphics, which supplies the interface that enables us to use graphics in a platform-independent manner. RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 2 of 22

91 Academic Year: Regulation CBCS Define Color Control. The Class Color is used to control the color of the graphics object. This class contains methods and constants for manipulating colors in applet programs. The different colors are created from the base color red, green, and blue. 14. What are the most commonly used Color methods? The most commonly used color ( ) methods are as follows: Methods Description int getred ( ) Returns the current color red value ( 0 to 255 ) int getgreen ( ) Returns the current color green value ( 0 to 255 ) int getblue ( ) Returns the current color blue value ( 0 to 255 ) color getcolor ( ) Returns the color of the current graphics objects void setcolor ( Color c ) Sets the current drawing color 15. Define Font Control. The class Font is used to set the fonts used in the graphical object. The Font class define the following constructor: Font ( String name, int style, int size ) The Font class constructor has three arguments: Font name, Font Style, and Font Size. The size of a font is measured as points. A point is 1/72 of an inch. 16. How to draw ovals in Java? The drawoval ( ) method is used to draw an oval with the specified width and height from (x, y). The general form is: void drawoval ( int x, int y, int w, int h ) Here, the first two parameters x and y represent the bounding rectangle s top left corner is at the coordinates (x, y). The last two parameters width w and height h specifies the width and height of the oval. 17. Define JMenuBar. The JMenuBar class is used as a container for menus. The general form is, JMenuBar ( ) 18. What is JMenu? The JMenu class is used to control the menus. The general form is, RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 3 of 22

92 Academic Year: Regulation CBCS JMenu ( String str ) 19. What is the function of JMenuItem? The JMenuItem class is used to control the menu items. The general form is, JMenuItem ( String str ) 20. Define JCheckBoxMenuItem. The JCheckBoxMenuItem class is used to control menu items that we can be toggled on or off. Using this we can select more than one option. PART B 1. Explain in detail about the grid layout. (Nov 12) The Grid Layout class automatically arranges components in a grid. The Grid Layout Manager organizes the display into a rectangular grid. All components of the grid is created of the grid is created with equal size. The Grid Layout has three constructors they are, GridLayout ( ) GridLayout ( int numrows, numcols ) GridLayout ( int numrows, numcols, int h, int v ) Parameters numrows - Determine the number of rows numcols - Determine the number of columns h - Specifies the horizontal gap in pixels between components v - Specifies the vertical gap in pixels between components Example An applet program whose display is organized as two dimensional grid: import java.awt.*; import java.applet.*; /*<applet code="gridlayoutdemo" width = 900 height=900> </applet>*/ public class GridLayoutDemo extends Applet Button b1, b2, b3, b4; GridLayout g = new GridLayout(2,2); public void init() setlayout(g); b1=new Button("Xavier"); b2=new Button("Catherin"); b3=new Button("Benjamin"); b4=new Button("John"); add(b1); add(b2); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 4 of 22

93 Academic Year: Regulation CBCS add(b3); add(b4); 2. Write a Java program to draw a rectangle, circle and ellipse. (April 13) import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code="dra1" width = 300 height=300> </applet>*/ public class dra1 extends Applet implements ActionListener Button dl,dov,dr; String s; public void init() dl=new Button("Circle"); dov=new Button("Oval"); dr=new Button("Rectangle"); add(dl); add(dov); add(dr); dl.addactionlistener(this); dov.addactionlistener(this); dr.addactionlistener(this); public void actionperformed(actionevent ae) s=ae.getactioncommand(); repaint(); public void paint(graphics g) g.drawstring("usage Graphics Class",300,100); if(s.equals("circle")) g.drawoval(300,250,100,100); else if(s.equals("oval")) g.drawoval(300,250,150,75); else g.drawrect(300,200,200,100); g.drawstring("u Pressed " +s,300,400); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 5 of 22

94 Academic Year: Regulation CBCS Output: 3. List the necessary methods for drawing a Line and Rectangle. (April 14,Apr/May 2016) Drawing Lines The drawline ( ) method is used to draw a straight line between points (x1, y1) and (x2, y2). The general form is: void drawline(int x1, int y1, int x2, int y2) This method takes two pair of coordinates (x1, y1) and (x2, y2) as arguments and draws a line between them. Drawing Rectangles Using Graphics class methods we can draw three types of rectangles. i. Sharp Corner Rectangle ii. Round Corner Rectangle iii. 3D Rectangle The drawrect ( ) method is used to draws a rectangle with upper-left corner at coordinates x and y, width w, and height h. The general form is: void drawrect ( int x, int y, int w, int h ) Here, the first two arguments x and y represent the x and y coordinates of the top left corner of the rectangle. The last two arguments w and h represent the width and height of the rectangle. RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 6 of 22

95 Academic Year: Regulation CBCS Rounded Corner Rectangle The drawroundrect ( ) method is used to draws a round corner rectangle with the specified width w, and height h from (x,y). Arc width aw and Arc height ah determines the rounding of the corners. The general form is: void drawroundrect ( int x, int y, int w, int h, int aw, int ah) 3D Rectangle The draw3drect ( ) method is used to draw a three dimensional rectangle with the specified width w and height h from left corner at coordinates x and y. The general form is: void draw3drect ( int x, int y, int h, int w, Boolean b) The first two parameters x and y represent the top-left corner of the rectangle, the third and fourth arguments h and w represent the width and height of the rectangle and last parameter b indicates that whether the rectangle has to be raised or not. 4. Write a Java program to define a frame. (April 14) import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JFrameDemo public static void main(string s[]) JFrame frame = new JFrame("JFrame Source Demo"); // Add a window listner for close button frame.addwindowlistener(new WindowAdapter() public void windowclosing(windowevent e) System.exit(0); ); // This is an empty content area in the frame JLabel jlbempty = new JLabel(""); jlbempty.setpreferredsize(new Dimension(175, 100)); frame.getcontentpane().add(jlbempty, BorderLayout.CENTER); frame.pack(); frame.setvisible(true); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 7 of 22

96 Academic Year: Regulation CBCS Output 5. How to create a frame window in applet? (Nov 12, April 13) Creating a new frame window from within an applet is actually quite easy. The following steps may be used to do it, Create a subclass of Frame Override any of the standard window methods, such as init(),start(),stop(),and paint(). Implement the windowclosing() method of the windowlistener interface, calling setvisible(false) when the window is closed Once you have defined a Frame subclass, you can create an object of that class. But it will not be initially visible When created, the window is given a default height and width You can set the size of the window explicitly by calling the setsize() method The example program is shown below: // Create a child frame window from within an applet. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="appletframe" width=400 height=60> </applet> */ // Create a subclass of Frame. class SampleFrame extends Frame SampleFrame(String title) super(title); // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this); // register it to receive those events addwindowlistener(adapter); public void paint(graphics g) g.drawstring("this is in frame window", 10, 40); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 8 of 22

97 Academic Year: Regulation CBCS class MyWindowAdapter extends WindowAdapter SampleFrame sampleframe; public MyWindowAdapter(SampleFrame sampleframe) this.sampleframe = sampleframe; public void windowclosing(windowevent we) sampleframe.setvisible(false); // Create frame window. public class AppletFrame extends Applet Frame f; public void init() f = new SampleFrame("A Frame Window"); f.setsize(150, 150); f.setvisible(true); public void start() f.setvisible(true); public void stop() f.setvisible(false); public void paint(graphics g) g.drawstring("this is in applet window", 15, 30); Output: 6. State the functions/methods of Flow Layout. (April 14) This is the default layout manager for an applet. The FlowLayout class places controls in a row that is centered in the available space. If the controls cannot fit in the current row, another row is started. RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 9 of 22

98 Academic Year: Regulation CBCS The Flow Layout class has three constructors. They are: a) FlowLayout ( ) b) FlowLayout ( int alignment ) c) FlowLayout ( int alignment, int h, int v ) Parameters: Alignment specifies how each line is aligned. The valid values are alignment. They are: FlowLayout.LEFT FlowLayout RIGHT FlowLayout.CENTER H specifies the horizontal or gap between the controls. V specifies the vertical gap between controls. Example: import java.awt.*; import java.applet.*; /*<applet code="flowlayoutdemo" width = 200 height=200> </applet>*/ public class FlowLayoutDemo extends Applet public void init() setlayout(new FlowLayout(FlowLayout.RIGHT, 5,5)); for(int i=1;i<12;i++) add(new Button("Toys" +i)); Output: RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 10 of 22

99 Academic Year: Regulation CBCS Explain in detail about the border layout. April 12 The Border Layout class allows geographic terms: North, South, East, West and Center. The Border Layout class has two constructors. Namely, BorderLayout ( ) : It is used to create default border layout. BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal and vertical space between the components. The BorderLayout defines the following regions: BorderLayout. NORTH BorderLayout. SOUTH BorderLayout. EAST BorderLayout. WEST BorderLayout. CENTER Example An Applet whose display is organized as geographic terms (north, south, east, west and center) import java.awt.*; import java.applet.*; /*<applet code="borderlayoutdemo" width = 200 height=200> </applet>*/ public class BorderLayoutDemo extends Applet public void init() setlayout(new BorderLayout(5,5)); Button b1=new Button("North"); Button b2=new Button("South"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center"); add(b1,"north"); add(b2,"south"); add(b3,"east"); add(b4,"west"); add(b5,"center"); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 11 of 22

100 Academic Year: Regulation CBCS Write an applet program to display organized geographic terms(north, south, east and center) using BorderLayout. An Applet whose display is organized as geographic terms (north, south, east, west and center) import java.awt.*; import java.applet.*; /*<applet code="borderlayoutdemo" width = 200 height=200> </applet>*/ public class BorderLayoutDemo extends Applet public void init() setlayout(new BorderLayout(5,5)); Button b1=new Button("North"); Button b2=new Button("South"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center"); add(b1,"north"); add(b2,"south"); add(b3,"east"); add(b4,"west"); add(b5,"center"); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 12 of 22

101 Academic Year: Regulation CBCS PART C 1. Develop a scientific calculator in Java with menus and frames. (April 14) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalop = "="; private CalculatorOp op = new CalculatorOp(); public Calculator() textfield = new JTextField("", 12); textfield.sethorizontalalignment(jtextfield.right); textfield.setfont(bigger_font); ActionListener numberlistener = new NumberListener(); String buttonorder = " "; JPanel buttonpanel = new JPanel(); buttonpanel.setlayout(new GridLayout(4, 4, 4, 4)); for (int i = 0; i < buttonorder.length(); i++) String key = buttonorder.substring(i, i+1); if (key.equals(" ")) buttonpanel.add(new JLabel("")); else JButton button = new JButton(key); button.addactionlistener(numberlistener); button.setfont(bigger_font); buttonpanel.add(button); ActionListener operatorlistener = new OperatorListener(); JPanel panel = new JPanel(); panel.setlayout(new GridLayout(4, 4, 4, 4)); String[] oporder = "+", "-", "*", "/","=","C","sin","cos","log"; for (int i = 0; i < oporder.length; i++) JButton button = new JButton(opOrder[i]); button.addactionlistener(operatorlistener); button.setfont(bigger_font); panel.add(button); JPanel pan = new JPanel(); pan.setlayout(new BorderLayout(4, 4)); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 13 of 22

102 Academic Year: Regulation CBCS pan.add(textfield, BorderLayout.NORTH ); pan.add(buttonpanel, BorderLayout.CENTER); pan.add(panel, BorderLayout.EAST); this.setcontentpane(pan); this.pack(); this.settitle("calculator"); this.setresizable(false); private void action() number = true; textfield.settext(""); equalop = "="; op.settotal(""); class OperatorListener implements ActionListener public void actionperformed(actionevent e) String displaytext = textfield.gettext(); if (e.getactioncommand().equals("sin")) textfield.settext("" + Math.sin(Double.valueOf(displayText).doubleValue())); else if (e.getactioncommand().equals("cos")) textfield.settext("" + Math.cos(Double.valueOf(displayText).doubleValue())); else if (e.getactioncommand().equals("log")) textfield.settext("" + Math.log(Double.valueOf(displayText).doubleValue())); else if (e.getactioncommand().equals("c")) textfield.settext(""); else if (number) action(); textfield.settext(""); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 14 of 22

103 Academic Year: Regulation CBCS else number = true; if (equalop.equals("=")) op.settotal(displaytext); else if (equalop.equals("+")) op.add(displaytext); else if (equalop.equals("-")) op.subtract(displaytext); else if (equalop.equals("*")) op.multiply(displaytext); else if (equalop.equals("/")) op.divide(displaytext); textfield.settext("" + op.gettotalstring()); equalop = e.getactioncommand(); class NumberListener implements ActionListener public void actionperformed(actionevent event) String digit = event.getactioncommand(); if (number) textfield.settext(digit); number = false; else textfield.settext(textfield.gettext() + digit); public class CalculatorOp private int total; public CalculatorOp() total = 0; public String gettotalstring() RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 15 of 22

104 Academic Year: Regulation CBCS return ""+total; public void settotal(string n) total = converttonumber(n); public void add(string n) total += converttonumber(n); public void subtract(string n) total -= converttonumber(n); public void multiply(string n) total *= converttonumber(n); public void divide(string n) total /= converttonumber(n); private int converttonumber(string n) return Integer.parseInt(n); class SwingCalculator public static void main(string[] args) JFrame frame = new Calculator(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); Output RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 16 of 22

105 Academic Year: Regulation CBCS Write short notes on BorderLayout and GridLayout with an example. (April 14) Border Layout The Border Layout class allows geographic terms: North, South, East, West and Center. The Border Layout class has two constructors. Namely, BorderLayout ( ) : It is used to create default border layout. BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal and vertical space between the components. The BorderLayout defines the following regions: BorderLayout. NORTH BorderLayout. SOUTH BorderLayout. EAST BorderLayout. WEST BorderLayout. CENTER Example: An Applet whose display is organized as geographic terms (north, south, east, west and center) import java.awt.*; import java.applet.*; /*<applet code="borderlayoutdemo" width = 200 height=200> </applet>*/ public class BorderLayoutDemo extends Applet public void init() setlayout(new BorderLayout(5,5)); Button b1=new Button("North"); Button b2=new Button("South"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center"); add(b1,"north"); add(b2,"south"); add(b3,"east"); add(b4,"west"); add(b5,"center"); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 17 of 22

106 Academic Year: Regulation CBCS Grid Layout: The Grid Layout class automatically arranges components in a grid. The Grid Layout Manager organizes the display into a rectangular grid. All components of the grid is created of the grid is created with equal size. The Grid Layout has three constructors they are, GridLayout ( ) GridLayout ( int numrows, numcols ) GridLayout ( int numrows, numcols, int h, int v ) Parameters: numrows - Determine the number of rows numcols - Determine the number of columns h - Specifies the horizontal gap in pixels between components v - Specifies the vertical gap in pixels between components Example: An applet program whose display is organized as two dimensional grid: import java.awt.*; import java.applet.*; /*<applet code="gridlayoutdemo" width = 900 height=900> </applet>*/ public class GridLayoutDemo extends Applet Button b1, b2, b3, b4; GridLayout g = new GridLayout(2,2); public void init() setlayout(g); b1=new Button("Xavier"); b2=new Button("Catherin"); b3=new Button("Benjamin"); b4=new Button("John"); add(b1); add(b2); add(b3); add(b4); 3. Write a program to create a menu by using JFrame. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 18 of 22

107 Academic Year: Regulation CBCS public class Menu1 extends JFrame public static Menu1 fr; public Menu1() this(null); public Menu1(String title) super(title); protected void frameinit() super.frameinit(); JMenuBar mb=createmenu(); setjmenubar(mb); protected JMenuBar createmenu() JMenuBar mb= new JMenuBar(); JMenu file= new JMenu("file"); file.add("new"); file.add("open"); file.addseparator(); file.add("save"); file.add("saveas"); file.addseparator(); JMenuItem item = new JMenuItem("Exit"); item.addactionlistener(new ActionListener() public void actionperformed(actionevent e) System.exit(0); ); file.add(item); mb.add(file); return(mb); public static void main(string args[]) JFrame fr1=new Menu1("File Menu"); fr1.pack(); fr1.setvisible(true); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 19 of 22

108 Academic Year: Regulation CBCS Describe the different layout managers with example. (April 13) Layout Manager are special objects that determine how the components of a container are organized. A Layout Manager is an instance of any class that implements the Layout Manager interface. The Layout Managers is set by the setlayout() method. The general format is: void setlayout ( LayoutManager obj ) The various layout managers are as follows: i. Flow Layout ii. Border layout iii. Grid Layout Flow Layout: This is the default layout manager for an applet. The FlowLayout class places controls in a row that is centered in the available space. If the controls cannot fit in the current row, another row is started. The Flow Layout class has three constructors. They are: d) FlowLayout ( ) e) FlowLayout ( int alignment ) f) FlowLayout ( int alignment, int h, int v ) Parameters: Alignment specifies how each line is aligned. The valid values are alignment. They are: FlowLayout.LEFT FlowLayout RIGHT FlowLayout.CENTER H specifies the horizontal or gap between the controls. V specifies the vertical gap between controls. Example: import java.awt.*; import java.applet.*; /*<applet code="flowlayoutdemo" width = 200 height=200> </applet>*/ public class FlowLayoutDemo extends Applet public void init() setlayout(new FlowLayout(FlowLayout.RIGHT, 5,5)); for(int i=1;i<12;i++) add(new Button("Toys" +i)); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 20 of 22

109 Academic Year: Regulation CBCS Border Layout: The Border Layout class allows geographic terms: North, South, East, West and Center. The Border Layout class has two constructors. Namely, BorderLayout ( ) : It is used to create default border layout. BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal and vertical space between the components. The BorderLayout defines the following regions: BorderLayout. NORTH BorderLayout. SOUTH BorderLayout. EAST BorderLayout. WEST BorderLayout. CENTER Example: An Applet whose display is organized as geographic terms (north, south, east, west and center) import java.awt.*; import java.applet.*; /*<applet code="borderlayoutdemo" width = 200 height=200> </applet>*/ public class BorderLayoutDemo extends Applet public void init() setlayout(new BorderLayout(5,5)); Button b1=new Button("North"); Button b2=new Button("South"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center"); add(b1,"north"); add(b2,"south"); add(b3,"east"); add(b4,"west"); add(b5,"center"); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 21 of 22

110 Academic Year: Regulation CBCS Grid Layout: The Grid Layout class automatically arranges components in a grid. The Grid Layout Manager organizes the display into a rectangular grid. All components of the grid is created of the grid is created with equal size. The Grid Layout has three constructors they are, GridLayout ( ) GridLayout ( int numrows, numcols ) GridLayout ( int numrows, numcols, int h, int v ) Parameters: numrows - Determine the number of rows numcols - Determine the number of columns h - Specifies the horizontal gap in pixels between components v - Specifies the vertical gap in pixels between components Example: An applet program whose display is organized as two dimensional grid: import java.awt.*; import java.applet.*; /*<applet code="gridlayoutdemo" width = 900 height=900> </applet>*/ public class GridLayoutDemo extends Applet Button b1, b2, b3, b4; GridLayout g = new GridLayout(2,2); public void init() setlayout(g); b1=new Button("Xavier"); b2=new Button("Catherin"); b3=new Button("Benjamin"); b4=new Button("John"); add(b1); add(b2); add(b3); add(b4); RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/SCS41 /Java Programming /Unit-IV Q&A Unit IV Question and Answer Bank Page 22 of 22

111 ACADEMIC YEAR: REGULATION CBCS (SCS41) (Java Programming) Unit-5 Exception and File Handling Type:100% Theory Question & Answers PART A QUESTIONS 1. Define Exception.(April 2012) Ans:An exception is an object that is generated at runtime to describe a problem encountered during the execution of a program. 2. What is Tomcat? (April 2012) Ans:Apache Tomcat is an open-source web server and servlet container developed by the Apache Software Foundation (A SF). Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket. 3. Define Applet. (Nov 2012) Ans:Applets are small java programs developed for internet applications. This can be run using the web browser or applet viewer. 4. Define Multithreading.(April 2013) Ans:Multithreading is the mechanism in which more than onethreadrunindependentofeach otherwithintheprocess 5. What is meant by Packages in Java?(Nov/Dec 2016) Ans:Packages are group of classes and interfaces. Two types of Packages are 1) System package 2) User defined package 6. Define Interface.(Nov/Dec 2016) Ans:An interface is a group of constants and methods declarations that define the form of a class. RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 1 of 23

112 ACADEMIC YEAR: REGULATION CBCS What is the use of finally block? Ans:Finally block creates a statement that will be executed after a try or catch block has been computed. The finally block will execute whether or not an exception is thrown. 8. What is thread?(nov/dec 2016) Ans:Thread is a single sequential flow of control. A thread is a sequence of execution within a program. 9. What are the ways available in java to creating thread? Ans:There are two ways of creating a thread in java. Extending the class thread Implementing Runnable Interface 10. What is Stream? Ans:A stream is a path of communication between the source and destination of data. 11. List out any three Java API packages. Java.util package Java.lang package Java.io package 12. Whatis thedifferencebetweenthrowandthrows clause? Ans:Throw is used to throw an exception manually, whereas throws is used in the case of checked exceptions, to tell the compiler that we haven't handled the exception, so that the exception will be handled by the calling function. 13. What are purpose waitand sleepmethods? Ans:Sleep() method maintains control of thread execution but delays the next action until the sleep time expires. Wait() method gives up control over thread execution in definitely so that other threads can run. 14. Whatis synchronization? Ans:Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization,it is possible for one thread to modify a shared object. RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 2 of 23

113 ACADEMIC YEAR: REGULATION CBCS PART B QUESTIONS 1. Explain the importance of synchronization in multithreading.( April 2012 Ans:Synchronization in java is the capability of control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why use Synchronization? The synchronization is mainly used to To prevent thread interference. To prevent consistency problem. Types of Synchronization: There are two types of synchronization Process Synchronization Thread Synchronization Thread Synchronization: There are two types of thread synchronization mutual exclusive and inter-thread communication. Mutual Exclusive o Synchronized method. o Synchronized block. o Static synchronization. Cooperation (Inter-thread communication in java) Java synchronized method: If you declare any method as synchronized; it is known as synchronized method.synchronized method is used to lock an object for any shared resource. RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 3 of 23

114 ACADEMIC YEAR: REGULATION CBCS When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. Example: public class BankAccount intaccountnumber; doubleaccountbalance; public synchronized boolean transfer (double amount) doublenewaccountbalance; if( amount >accountbalance) return false; else newaccountbalance = accountbalance - amount; accountbalance = newaccountbalance; return true; public synchronized boolean deposit(double amount) doublenewaccountbalance; if( amount < 0.0) return false; // can not deposit a negative amount else newaccountbalance = accountbalance + amount; accountbalance = newaccountbalance; return true; RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 4 of 23

115 ACADEMIC YEAR: REGULATION CBCS How do applets differ from applications?(april 2012) Small Program Applet Used to run on client browser Applet is portable and can be executed by any JAVA supported browser. Applet applications are executed in a Restricted Environment Applets are created by extending the java.applet.applet Applet application has 5 methods which will be automatically invoked on occurrence of specific event importjava.awt.*; importjava.applet.*; public class Myclass extends Applet public void init() public void start() public void stop() public void destroy() public void paint(graphics g) Application Large Program Can be executed on standalone computer system Need JDK, JRE, JVM installed on client machine. Application can access all the resources of the computer Applications are created by writing public static void main (String[] s) method. Application has a single start point which is main method public class MyClass public static void main(string args[]) 3. With example explain Frame window creation in applet.(nov 2012) Ans:Creating a new frame window from within an applet is actually quite easy. The following steps may be used to do it, Create a subclass of Frame Override any of the standard window methods, such as init(),start(),stop(),and paint(). Implement the windowclosing() method of the window listener interface, calling AppletVisible(false)when the window is closed. Once you have defined a Frame subclass,you can create an object of that class.but it will not be initially visible. When created, the window is given a default height and width. You can set the size of the window explicitly by calling the setsize() method Example: RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 5 of 23

116 ACADEMIC YEAR: REGULATION CBCS importjava.awt.*; importjava.applet.*; /* <applet code="appletframe" width=400 height=60> </applet> */ public class AppletFrame extends Applet Frame f; public void init() f = new SampleFrame("A Frame Window"); f.setsize(150, 150); f.setvisible(true); public void start() f.setvisible(true); public void stop() f.setvisible(false); public void paint(graphics g) g.drawstring("this is in applet window", 15, 30); 4. Explain the output stream of java in detail.(april 2013) Ans: Java I/O (Input and Output) is used to process the input and produce the output based on the input. Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. Stream: A stream is a sequence of data.in Java a stream is composed of bytes. It's called a stream because it's like a stream of water that continues to flow. In java, output streams are created as System.out: standard output stream RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 6 of 23

117 ACADEMIC YEAR: REGULATION CBCS OutputStream: Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket. OutputStream class: OutputStream class is an abstract class.it is the superclass of all classess representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Commonly used methods of OutputStream class Method 1) public void write(int) )throws IOException: 2) public void write(byte[])throws IOException: 3) public void flush()throws IOException: 4) public void close()throws IOException: Description is used to write a byte to the current output stream. is used to write an array of byte to the current output stream. flushes the current output stream. is used to close the current output stream. 5. Explain how to handle arithmetic exception by giving a suitable example.(april 2013) Class: Java.lang.ArithmeticException This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by zero. Eg: class ExceptionDemo1 public static void main(string args[]) RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 7 of 23

118 ACADEMIC YEAR: REGULATION CBCS try int num1=30, num2=0; int output=num1/num2; System.out.println ("Result = " +output); catch(arithmeticexception e) System.out.println ("Arithmetic Exception: You can't divide an integer by 0"); Output of above program: Arithmetic Exception: You can't divide an integer by 0 6. Describe the Applet life cycle.(nov 2013) Ans:Java applet inherits features from the class Applet. Thus, whenever an applet is created, it undergoes a series of changes from initialization to destruction. Various stages of an applet life cycle are depicted in the figure below: Initial State: When a new applet is born or created, it is activated by calling init() method. At this stage, new objects to the applet are created, initial values are set, images are loaded and the colors of the images are set. An applet is initialized only once in its lifetime. Its general form is: public void init( ) //Action to be performed RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 8 of 23

119 ACADEMIC YEAR: REGULATION CBCS Running State: An applet achieves the running state when the system calls the start() method. This occurs as soon as the applet is initialized. An applet may also start when it is in idle state. At that time, the start() method is overridden. Its general form is: Idle State: public void start( ) //Action to be performed An applet comes in idle state when its execution has been stopped either implicitly or explicitly. An applet is implicitly stopped when we leave the page containing the currently running applet. An applet is explicitly stopped when we call stop() method to stop its execution. Its general form is: Dead State public void stop //Action to be performed An applet is in dead state when it has been removed from the memory. This can be done by using destroy() method. Its general form is: public void destroy( ) //Action to be performed 7. What is Package? How packages are created in java.(nov 2013) Ans:Packages are container for classes. It is like a header file in C++ and it is stored in a hierarchical manner. Uses: Package reduce the complexity of the software Because a large number of classes can be grouped into limited number of package. We can create classes with same name in different package. RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 9 of 23

120 ACADEMIC YEAR: REGULATION CBCS Using package we can hide class Crating a package: Java has a facility to create our own package. Create a sub directory with the same name of the package. This gives one package. We can also create another package within this director. Example: c:\package1>package2>md package 3; Defining a package: Each package contains number of related classes. We access these class in our application. There are two methods to access a package a) By specifying the fully qualified class name b) By using import statement By specifying the fully qualified class name: We can access a package by specifying the class path at time of declaration of our object. Syntax: pack1.pack2.packn.classname obj; Example: bb.aa.sample.obj; Let a class sample belong to a package aa, this package is inside another package b. If we want to use the class sample in our application. We have to do the declaration. By using import statement: By using statement we can either use all classes of a package in our application or a specific class. Example: import aa.sample; This statement allows us to use the sample class of package as in our application. 8. Explain the importance of try-catch block with example. (April 2014) Java try block: RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 10 of 23

121 ACADEMIC YEAR: REGULATION CBCS Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block. Syntax of java try-catch: Try //code thatt may throw exception catch(exception_class_name ref) Syntax of try-finally block: Try //code thatt may throw exception finally Java catch block: Java catch block is used to handle the Exception. It must be used after the try block only. We can use multiple catch block with a single try. Internal working of javaa try-catch block: Example: public class Testtrycatch2 RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 11 of 23

122 ACADEMIC YEAR: REGULATION CBCS public static void main(string args[]) Try int data=50/0; catch(arithmeticexception e)system.out.println(e); System.out.println("rest of the code..."); Example: 9. Write short notes on File streams used for I/O. (April 2014) Ans:In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java. Java FileOutputStream class Java FileOutputStream is an output stream for writing data to a file. If we have to write primitive values then use FileOutputStream.Instead, for character- oriented data, prefer FileWriter. import java.io.*; class Test public static void main(string args[]) Try FileOutputstream fout=new FileOutputStream("abc.txt"); String s="sachin Tendulkar is my favourite player"; byte b[]=s.getbytes();//converting string into byte array fout.write(b); fout.close(); RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 12 of 23

123 ACADEMIC YEAR: REGULATION CBCS System.out.println("success..."); catch(exception e)system.out.println(e); Java FileInputStream class: Java FileInputStreamclass obtains input bytes from a file.it is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. It should be used to read byte-oriented data for example to read image, audio, video etc. Example : import java.io.*; class SimpleRead public static void main(string args[]) Try FileInputStream fin=new FileInputStream("abc.txt"); int i=0; while((i=fin.read())!=-1) System.out.println((char)i); fin.close(); catch(exception e)system.out.println(e); RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 13 of 23

124 ACADEMIC YEAR: REGULATION CBCS Describe the concept of Multithreading using an example.(april 2014) Ans:Multithreading is a program control. A multithreaded program contains two or more parts that can run concurrently. Each parts of such a program are called a Thread. The OS is responsible for scheduling and allocating resource for thread. Thread class:- Thread is a class and it contains constructors and methods needed for creating threads. This class is present in java.lang.package. Important thread Constructors:- a) Public thread(string threadname) b) Public thread() Advantages of thread:- It increase the speed of the execution It allow the run more task simultaneously It reduce the complexity of large programs It maximize cpu utilization Thread Methods:- The important thread class methods are Run() contains the statement for the particular thread Start() to start the execution of thread Stop() to block the currently executing thread Interrupt() to interrupt the currently running thread IsAlive() - to check whether the thread is running or not Yield() - to bring the stopped thread to run mode Wait() to stop the currently running thread RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 14 of 23

125 ACADEMIC YEAR: REGULATION CBCS PART C QUESTIONS 1. Discuss the inter-thread communication with example.(april 2012, Nov 2012 & April 2013) Ans:Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class: wait() notify() notifyall() wait() method: Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyall() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. Method public final void wait()throws InterruptedException public final void wait(long timeout)throws InterruptedException Description waits until object is notified. waits for the specified amount of time. notify() method: Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:public final void notify() notifyall() method: RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 15 of 23

126 ACADEMIC YEAR: REGULATION CBCS Wakes up all threads that are waiting on this object's monitor. Syntax:public final void notifyall() Understanding the process of inter-thread communication The point to point explanation of the above diagram is as follows: Threads enter to acquire lock. Lock is acquired by on thread. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. If you call notify() or notifyall() method, thread moves to the notified state (runnable state). Now thread is available to acquire lock. After completion of the task, thread releases the lock and exits the monitor state of the object. 2. Explain the two ways of creating threads in java. (Nov 2013) Thread Creation: There are two ways to create thread in java; Implement the Runnable interface (java.lang.runnable) By Extending the Thread class (java.lang.thread) Implementing the Runnable Interface: The Runnable Interface Signature public interface Runnable void run(); The procedure for creating threads based on the Runnable interface is as follows: RAAK/CS/ M.USHA/II YEAR/IV Sem/SCS41 /JAVA PROGRAMMING /UNIT-5 ANS/VER 2.0 Unit 5 Question and Answer Bank Page 16 of 23

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths. Loop Control There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first,

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

Lecture 1: Overview of Java

Lecture 1: Overview of Java Lecture 1: Overview of Java What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

Software Practice 1 Basic Grammar

Software Practice 1 Basic Grammar Software Practice 1 Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee (43) 1 2 Java Program //package details

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java What is Java? Chapter 1 Introduction to Java Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows,

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions Index Course Outline Grading Policy Lab Time Distribution Important Instructions 2 Course Outline Week Topics 1 - History and Evolution of Java - Overview of Java 2 - Datatypes - Variables 3 - Arrays 4

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 Java Program //package details public class ClassName {

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

Building Java Programs. Introduction to Programming and Simple Java Programs

Building Java Programs. Introduction to Programming and Simple Java Programs Building Java Programs Introduction to Programming and Simple Java Programs 1 A simple Java program public class Hello { public static void main(string[] args) { System.out.println("Hello, world!"); code

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. Object and Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Communication Objects are the basic runtime entities in

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Core JAVA Training Syllabus FEE: RS. 8000/-

Core JAVA Training Syllabus FEE: RS. 8000/- About JAVA Java is a high-level programming language, developed by James Gosling at Sun Microsystems as a core component of the Java platform. Java follows the "write once, run anywhere" concept, as it

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

Programming. Syntax and Semantics

Programming. Syntax and Semantics Programming For the next ten weeks you will learn basic programming principles There is much more to programming than knowing a programming language When programming you need to use a tool, in this case

More information

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Expressions, Statements and Arrays. Java technology is: A programming

More information

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials Introduction to Android Saturday Yanqiao ZHU Google Camp School of Software Engineering, Tongji University In courtesy of The Java Tutorials Getting Started Introduction to Java The Java Programming Language

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Special Topics: Programming Languages

Special Topics: Programming Languages Lecture #23 0 V22.0490.001 Special Topics: Programming Languages B. Mishra New York University. Lecture # 23 Lecture #23 1 Slide 1 Java: History Spring 1990 April 1991: Naughton, Gosling and Sheridan (

More information

Learning the Java Language. 2.1 Object-Oriented Programming

Learning the Java Language. 2.1 Object-Oriented Programming Learning the Java Language 2.1 Object-Oriented Programming What is an Object? Real world is composed by different kind of objects: buildings, men, women, dogs, cars, etc. Each object has its own states

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University Lecture 2 COMP1406/1006 (the Java course) Fall 2013 M. Jason Hinek Carleton University today s agenda a quick look back (last Thursday) assignment 0 is posted and is due this Friday at 2pm Java compiling

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms COMP9024: Data Structures and Algorithms Week One: Java Programming Language (I) Hui Wu Session 2, 2016 http://www.cse.unsw.edu.au/~cs9024 Outline Classes and objects Methods Primitive data types and operators

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

B.V. Patel Institute of BMC & IT, UTU 2014

B.V. Patel Institute of BMC & IT, UTU 2014 BCA 3 rd Semester 030010301 - Java Programming Unit-1(Java Platform and Programming Elements) Q-1 Answer the following question in short. [1 Mark each] 1. Who is known as creator of JAVA? 2. Why do we

More information

Programming for the Web with PHP

Programming for the Web with PHP Aptech Ltd Version 1.0 Page 1 of 11 Table of Contents Aptech Ltd Version 1.0 Page 2 of 11 Abstraction Anonymous Class Apache Arithmetic Operators Array Array Identifier arsort Function Assignment Operators

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 2012 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Learning objectives. The Java Environment. Java timeline (cont d) Java timeline. Understand the basic features of Java

Learning objectives. The Java Environment. Java timeline (cont d) Java timeline. Understand the basic features of Java Learning objectives The Java Environment Understand the basic features of Java What are portability and robustness? Understand the concepts of bytecode and interpreter What is the JVM? Learn few coding

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Java Professional Certificate Day 1- Bridge Session

Java Professional Certificate Day 1- Bridge Session Java Professional Certificate Day 1- Bridge Session 1 Java - An Introduction Basic Features and Concepts Java - The new programming language from Sun Microsystems Java -Allows anyone to publish a web page

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information