Jntuh Java Notes

  • Uploaded by: Akhil
  • 0
  • 0
  • March 2021
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jntuh Java Notes as PDF for free.

More details

  • Words: 45,203
  • Pages: 237
Loading documents preview...
Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / II

Academic year: 2015-16

Subject: Object oriented programming through java Tutorial sheet: UNIT II-I INHERITANCE SHORT ANSWER QUESTIONS

1. What is meant by inheritance? 2. What are the types of inheritance? 3. How Inheritance can be implemented in java? 4. Does Java support Multiple Inheritance ? 5. What is the name of the root class for all objects in java? 6. Define the term sub class? What You Can Do in a Subclass? 7. If a class is declared without any access modifiers, where may the class be accessed? 8. Can you declare a class as private? 9. What is the super key word used for? 10. What happens if both super class and sub class have a field with same name? 11. Can a private method of a super class be declared within a subclass? 12. What restrictions are placed on method overriding? 13. What is the difference between final, finally and finalize() in Java? 14. What is an abstract class? 15. When an Abstract Class Implements an Interface

LONG ANSWER QUESTIONS 1. What is inheritance? What are the advantages and disadvantages of inheritance? 2. What are the types of inheritance? 3. Explain briefly member access rules? Where are they used? 4. What is meant by polymorphism? Explain types of polymorphism 5. What does it mean to override a method?

Tutor

Faculty

HOD

SHORT ANSWER QUESTIONS Q1).What is meant by inheritance? Ans Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.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.When we talk about inheritance, the most commonly used keyword would be extends and implements. By using these keywords we can make one object acquire the properties of another object. Inheritance represents the IS-A relationship, also known as parentchild relationship. use inheritance in java 

For Method Overriding (so runtime polymorphism can be achieved).



For Code Reusability.

Syntax of Java Inheritance 1. class Subclass-name extends Superclass-name 2. { 3.

//methods and fields

4. } 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

Q2).What are the types of inheritance? Ans: There are 5 types of inheritance. 1. Single Inheritance : One class is extended by only one class. 2. Multilevel Inheritance : One class is extended by a class and that class in turn is extended by another class thus forming a chain of inheritance. 3. Hierarchical Inheritance : One class is extended by many classes. 4. Multiple Inheritance : One class extends more than one classes. (Java does not support multiple inheritance.) 5. Hybrid Inheritance : It is a combination of above types of inheritance.

Q3).How Inheritance can be implemented in java? Ans :Inheritance can be implemented in JAVA using below two keywords: 1.extends 2.implements  extends is used for developing inheritance between two classes and two interfaces.



implements keyword is used to developed inheritance between interface and class.



As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

Q4). Does Java support Multiple Inheritance ? Ans:. 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. 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. 1. class A{ 2. void msg() 3. { 4. System.out.println("Hello"); 5. } 6. } 7. class B 8. { 9. void msg() 10. { 11. System.out.println("Welcome"); 12. } 13. } 14. class C extends A,B 15. {//suppose if it were

16.

Public Static void main(String args[])

17. { 18.

C obj=new C();

19.

obj.msg();//Now which msg() method would be invoked?

20. } 21. } Test it Now: Compile Time Error Q5). What is the name of the root class for all objects in java? Ans : All the classes written in JAVA make use of inheritance. If a root class is not specified for a class then it means it is derived from a root class name "Object". Object is the base class for all the classes, by default. That means if parent class is not provided then the object class will be its parent class. Q6). Define the term sub class? What You Can Do in a Subclass? Ans :A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: 1. The inherited fields can be used directly, just like any other fields. 2. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). 3. You can declare new fields in the subclass that are not in the superclass. 4. The inherited methods can be used directly as they are. 5. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. 6. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. 7. You can declare new methods in the subclass that are not in the superclass. 8. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. Q7) .If a class is decared without any access modifiers, where may the class be accessed? Ans : A class that is declared without any access modifies is said to have a package or

friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. Q8) .Can you declare a class as private? Ans : yes,we can declare a private class as an inner class. For example: class MyPrivate { Private static class MyKey { string key="12345"; } public static void main(string[ ] args) { System.out.println(new Mykey().key);//prints 12345 } } Q9). What is the super key word used for? Ans :The super keyword is similar to this keyword following are the scenarios where the super keyword is used. 

It is used to differentiate the members of superclass from the members of subclass, if they have same names.



It is used to invoke the super class constructor from subclass.

Q10). What happens if both super class and sub class have a field with same name? Ans :Super class field will be hidden in the sub class. You can access hidden super class field in sub class using super key word If a class is inheriting the properties of another class. And if the members of the super class have the names same as the sub class, to differentiate these variables we use super keyword as shown below.

super.variable super.method(); Q11). Can a private method of a superclass be declared within a subclass? Ans : Yes. A private field or method or inner class belongs to its declared class and hides from its subclasses. there is no way for private stuff to have a runtime overloading or overriding (polymorphism) features. Q12). What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Q13) .What is the difference between final, finally and finalize() in Java? Ans: final – handles constant declaration. Finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc. finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Q14). What is an abstract class? Ans :A class which contains the abstract keyword in its declaration is known as abstract class.  Abstract classes may or may not contain abstract methods ie., methods with out body ( public void get(); )

 But, if a class have at least one abstract method, then the class must be declared abstract.  If a class is declared abstract it cannot be instantiated.  To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.  If you inherit an abstract class you have to provide implementations to all the abstract methods in it. Abstract Methods: If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.  abstract keyword is used to declare the method as abstract.  You have to place the abstract keyword before the method name in the method declaration.  An abstract method contains a method signature, but no method body. Q15 ).When an Abstract Class Implements an Interface Ans :In the Interfaces, the class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface's methods, provided that the class is declared to be abstract. For example, abstract class X implements Y { // implements all but one method of Y }

class XX extends X { // implements the remaining method in Y } In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

LONG ANSWER QUESTIONS

Q1).What is inheritance? What are the advantages and disadvantages of inheritance? Ans :Inheritance is one of the feature of Object-Oriented Programming. Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviours from the base class. The derived class is also called subclass and the base class is also known as super-class. The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class. Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But a subclass can have only one super class. This is because Java does not support multiple inheritance. Advantages: increased reliability, software reusability, code sharing, software components, consistency of interface, polymorphism and frame works Disadvantages: Since inheritance inherits everything from the super class and interface it may make the subclass to clustering and sometimes error prone when dynamic overriding or dynamic overloading in some situation. In addition the inheritance may make peers hardly understand your code if they don't know how your super class acts and add learning curve to the process of development. Usually when you want to use a functionality of a class you may use subclass to inherits such function or use an instance of this class in your class. Which is better depends on your specification. Q2). What are the types of inheritance? Ans :Below are Various types of inheritance in Java. We will see each one of them one by one with the help of examples and flow diagrams. 1) Single Inheritance Single inheritance is damn easy to understand. When a class extends another one class only then we call it a single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A. Single Inheritance example program in Java: Class A

{ public void methodA() { System.out.println("Base class method"); } }

Class B extends A { public void methodB() { System.out.println("Child class method"); } public static void main(String args[]) { B obj = new B(); obj.methodA(); //calling super class method obj.methodB(); //calling local method } } 2) Multiple Inheritance “Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes. Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to problems in the hierarchy. This results in unwanted complexity when further extending the class. Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

3) Multilevel Inheritance Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see in below flow diagram C is subclass or child class of B and B is a child class of A. Multilevel Inheritance example program in Java Class X{ public void methodX() { System.out.println("Class X method"); } } Class Y extends X { public void methodY() { System.out.println("class Y method"); } } Class Z extends Y { public void methodZ() { System.out.println("class Z method"); } public static void main(String args[]) { Z obj = new Z(); obj.methodX(); //calling grand parent class method obj.methodY(); //calling parent class method obj.methodZ(); //calling local method } }

4) Hierarchical Inheritance In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D. 5) Hybrid Inheritance In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance. A typical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java. Q3). Explain briefly member access rules? Where are they used? Ans :The basic Accessibility Modifiers are of 4 types in Java. They are 1. 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 public keyword If class member is “public” then it can be accessed from anywhere. The member variable or method is accessed globally. This is simplest way to provide access to class members. Usually class variables are kept as private and getter-setter methods are provided to work with them. private keyword If class member is “private” then it will be accessible only inside the same class. This is the

most restricted access and the class member will not be visible to the outer world. Usually we keep class variables as private and methods that are intended to be used only inside the class as private. protected keyword If class member is “protected” then it will be accessible only to the classes in the same package and to the subclasses. This modifier is less restricted from private but more restricted from public access. Usually we use this keyword to make sure the class variables are accessible only to the subclasses. | Class | Package | Subclass | World ————————————+———— public

| y |

y | y

| y

————————————+— protected | y |

y |

y

| n

————————————+—— no modifier | y |

y |

n

| n

———————————— private

| y | n

| n

| n

y: accessible n: not accessible Access Modifiers are used at 2 access levels in Java. They are 1. Top-level for Classes & Interfaces 2. Member-level for Classes & Interfaces 1) Access Modifiers for Top-level Classes & Interfaces Only 2 basic access modifiers are applicable for Top-level Classes & Interfaces. They are Public and Package/Default modifiers.  Public: If top level class or interface within a package is declared as Public, then it is accessible both inside and outside of the package.  Default: If no access modifier is specified in the declaration of the top level class or interface, then it is accessible only within package level. It is not accessible in other

packages or sub packages. Access Modifiers is the way of specifying the accessibility of a class and its members with respective to other classes and members. Access Modifiers for Top-level Classes & Interfaces: public, default, abstract, final Access Modifiers for Members: public Members, protected Members, default Members, private Members, static Members, final Members, abstract Methods, synchronized Methods, native

Methods,

transientFields,volatileFields.

Access Modifiers for Nested Classes & Interfaces: Nested Interfaces, Nested Classes, Static member classes, Non-Static member classes, Local classes, Anonymous classes. Q4).What is meant by polymorphism? Explain types of polymorphism Ans :Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in detail.  It is a feature that allows one interface to be used for a general class of actions.  An operation may exhibit different behaviour in different instances.  The behaviour depends on the types of data used in the operation.  It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.  Polymorphism means to process objects differently based on their data type.  In other words it means, one method with multiple implementation, for a certain class of action. And which implementation to be used is decided at runtime depending upon the situation (i.e., data type of the object) This can be implemented by designing a generic interface, which provides generic methods for a certain class of action and there can be multiple classes, which provides the implementation of these generic methods Polymorphism could be static and dynamic both. Overloading is static polymorphism while, overriding is dynamic polymorphism.  Overloading in simple words means two methods having same method name but takes different input parameters. This called static because, which method to be invoked

will be decided at the time of compilation  Overriding means a derived class is implementing a method of its super class. There are two types of polymorphism in java- Runtime polymorphism( Dynamic polymorphism) and Compile time polymorphism (static polymorphism). Runtime Polymorphism( or Dynamic polymorphism) Method overriding is a perfect example of runtime polymorphism. In this kind of polymorphism, reference of class X can hold object of class X or an object of any sub classes of class X. For e.g. if class Y extends class X then both of the following statements are valid: Y obj = new Y(); //Parent class reference can be assigned to child object X obj = new Y(); Compile time Polymorphism( or Static polymorphism) Compile time polymorphism is nothing but the method overloading in java. In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both Q5).What does it mean to override a method? Ans :Method Overriding In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within its subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hiddenExample: public class BaseClass { public void methodToOverride() //Base class method { System.out.println ("I'm the method of BaseClass"); } } public class DerivedClass extends BaseClass {

public void methodToOverride() //Derived Class method { System.out.println ("I'm the method of DerivedClass"); } }

public class TestMethod { public static void main (String args []) { // BaseClass reference and object BaseClass obj1 = new BaseClass(); // BaseClass reference but DerivedClass object BaseClass obj2 = new DerivedClass(); // Calls the method from BaseClass class obj1.methodToOverride(); //Calls the method from DerivedClass class obj2.methodToOverride(); } } Output: I'm the method of BaseClass I'm the method of DerivedClass Rules for Method Overriding: 1. applies only to inherited methods 2. object type (NOT reference variable type) determines which overridden method will be used at runtime 3. Overriding method can have different return type (refer this) 4. Overriding method must not have more restrictive access modifier 5. Abstract methods must be overridden 6. Static and final methods cannot be overridden 7. Constructors cannot be overridden

8. It is also known as Runtime polymorphism.

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOPS THROUGH JAVA Tutorial Sheet: UNIT III-2 MULTITHREDDING Short answer questions 1. Explain the differences between process and thread? 2. What is multithreading? 3. What the differences between multicasting and multithreading? 4. List the imported methods defined by a thread class? 5. Explain thread life cycle? 6. Write a short notes on creation of thread 7. What is synchronization? Why it is important in multithreaded programming 8. What is deadlock? How is it resolved 9. What is the use of isAlive() and joint() methods? 10. What is a daemon thread? 11. Explain ThreadGroup class. List some methods defined by it? 12. Write a java program to create a simple thread by extending thread class? 13. Write a java program to create thread by runnable interface? 14. Explain inter-thread communication? 15. Describe about thread priorities? Descriptive questions/Programs/Experiment 1. Define multithreading? Explain in detail with an example? 2. What is a thread? Explain its life cycle? 3. Explain in detail about creating threads and synchronizing threads? 4. Explain in detail about Daemon threads? 5. Explain thread group class, methods defined by it? Explain any three of them? Tutor

Faculty

HOD

1

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16 Tutorial Sheet: III-2 Question & Answers SHORT ANSWER QUESTIONS

1. Describe the differences between process and thread Ans:

Process

Thread

A process has separate virtual Threads are entities within a process. All threads address

space.

Two

processes of a process share its virtual address space and

running on the same system at the system resources but they have their own stack same time do not overlap each created. other. Processes

use

communication

inter

process Threads

techniques

do

not

need

inter

process

to communication techniques because they are not

interact with other processes.

altogether separate address spaces. They share the same address space; therefore, they can directly communicate with other threads of the process.

Process has no synchronization Threads of a process share the same address overhead in the same way a thread space; therefore synchronizing the access to the has.

shared data within the process's address space becomes very important.

Child process creation within from Threads can be created quite easily and no a

parent

process

requires duplication of resources is required.

duplication of the resources of parent process 2. What is multithreading? Ans: Multithreading is a concept in which a program is divided into two or more subprograms, which can be executed at the same time. The part of a program or subprogram is called a thread 2

and each thread executes separately. Multithreading is a powerful programming tool that enables towrite efficient programs by making maximum use of the CPU because the CPU idle time can be reduced. Multithreading in java is a process of executing multiple threads simultaneously. The aim of multithreading is to achieve the concurrent execution. 3. What the differences between multicasting and multithreading? Ans: Multitasking The ability to run several programs simultaneously, potentially by utilizing several processors,

but

predominantly,

by

time-sharing

their

resource

requirements.

An example is right on your desktop, where you may have a web browser, e-mail client, audio player, word processor, spreadsheet and who knows what else on the air at the same time. They can dance in and out of having the processor to themselves many times per second, because neither of them needs all of it for very long at a time. Multithreading The ability to run several functions of a single program simultaneously, predominantly by utilizing several processors, but potentially, by time-sharing their resource requirements. An example would be a web server, where the responses to all the incoming requests need much of the same program logic and state, but different handles on a few things (network socket, id of caller, whatever else). Sharing the greater bunch of the data pertaining to the program, but having dedicated copies of a small amount of private things, lets threads be spawned and destroyed very quickly, and permits an increase in available processing power to increase the number of requests answered without requiring an additional copies of the server program to be running.

4.

List some imported methods defined by a thread class?

Ans: Methods of Thread class are: getPriority(), setPriority(), getName(), setName(), isDeamon(), run(), start() , sleep(), suspend(), resume(), stop(), isAlive(), currentThread(), join(), getState(), yield()

5. Explain thread life cycle? Ans: Life cycle of thread: State of a thread are classified into five types they are: 1. New State 2. Ready State 3. Running State 4. Waiting State 5. Halted or dead State 3

In new state thread is created and about to enter into main memory. No memory is available if the thread is in new state. In ready state thread will be entered into main memory, memory space is allocated for the thread and 1st time waiting for the CPU. Whenever the thread is under execution it is known as running state. If the thread execution is stopped permanently than it comes under dead state, no memory is available for the thread if it comes to dead state. 6. Write a short note on creation of thread Ans: There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface.  By extending Thread class: In java language multithreading program can be created by following below rules. 1. Create any user defined class and make that one as a derived class of thread class. class Class_Name extends Thread { ........ } 2. Override run() method of Thread class (It contains the logic of perform any operation) 3. Create an object for user-defined thread class and attached that object to predefined thread class object. Class_Name obj=new Class_Name Thread t=new Thread(obj); 4. Call start() method of thread class to execute run() method. 5. Save the program with filename.java

4

 By implementing Runnable interface:

Runnable is one of the predefined interface in java.lang package, which is containing only one method and whose prototype is " Public abstract void run ". The run() method of thread class defined with null body and run() method of Runnable interface belongs to abstract. Industry is highly recommended to override abstract run() method of Runnable interface but not recommended to override null body run() method of thread class. In some of the circumstance if one derived class is extending some type of predefined class along with thread class which is not possible because java programming never supports multiple inheritance. To avoid this multiple inheritance problem, rather than extending thread class we implement Runnable interface. Rules to create the thread using Runnable interface 

Create any user defined class and implements runnable interface within that



Override run() method within the user defined class.



call start() method to execute run() method of thread class



Save the program with classname.java class Class_Name implement Runnable { public void run() { 5

........ } } Class_Name obj=new Class_name(); Thread t=new Thread(); t.start();

Note: While implementing runnable interface it is very mandatory to attach user defined thread class object reference to predefined thread class object reference. It is optional while creating thread by extending Thread class. 7. What is synchronization? Why it is important in multithreaded programming Ans: Synchronization is a process in which an acess to a shared resource is allowed to only one thread at a time. Synchronization is required in multithreaded programming when two or more threads try to access the shared resources at the same time. If two threads are allowed to access the shared resource at the same time then the data will be changed, hence producing the wrong output. Thread Synchronization: Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used. Definition: Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe. In java language thread synchronization can be achieve in two different ways. 1. Synchronized block 2. Synchronized method Note: synchronization is a keyword (access modifier in java) Synchronized block Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block. class Class_Name implement Runnable or extends Thread { public void run() 6

{ synchronized(this) { ....... ....... } } } Synchronized method Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method. class Class_Name implement Runnable or extends Thread { public void run() { synchronized void fun() { ....... ....... } public void run() { fun(); .... } }

8. What is deadlock? How is it resolved? Ans: Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

7

Assume that a thread holds a lock on the synchronized object 1 and it is waiting to get a lock on object 2. Also assume that another thread holds a lock on object 2 and it is waiting to get a lock on object 1. From this situation it is clear that both threads are waiting for each other to release a lock. But first thread can’t release the lock until it gets a lock on object 2. And second thread cant release lock until it gets a lock on object1. Hence both of them cant proceed to success. This situation is called as deadlock. The

deadlock

can

be

resolved

by synchronizing

the

threads

using

semaphores.

Semaphores are used for signaling between two threads. They coordinate two threads and resolve the deadlock condition. 9. What is the use of isAlive() and join() methods? Ans: isAlive(): Which is return true if the thread is in ready or running or waiting state and return false if the thread is in new or dead state. Thread t=new Thread(); t.isAlive();

join(): Which can be used to combined more than one thread into a single group signature is public final void join()throws InterruptedException try { t.join(); t2.join(); ..... ..... }

10. What is a daemon thread? Ans: Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM 8

terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc. Points to remember for Daemon Thread   

It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. Its life depends on user threads. It is a low priority thread.

11. Explain ThreadGroup class. List some methods defined by it? Ans: The java.lang.ThreadGroup class represents a set of threads. It can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent. This class inherits methods from the java.lang.Object classes. Class constructors: S.N.

Constructor & Description

1

ThreadGroup(String name) This constructs a new thread group.

2

ThreadGroup(ThreadGroup parent, String name) This creates a new thread group.

Class methods: S.N.

Method & Description

1

int activeCount() This method returns an estimate of the number of active threads in this thread group.

2

int activeGroupCount() This method returns an estimate of the number of active groups in this thread group.

3

void checkAccess() This method determines if the currently running thread has permission to modify this thread group. 9

12. Write a java program to create a simple thread by extending thread class?

class Th1 extends Thread { public void run() { try { for(int i=1;i< =10;i++) { System.out.println("value of i="+i); Thread.sleep(1000); } } catch(InterruptedException ie) { System.err.println("Problem in thread execution"); } } } class Threaddemo2 { public static void main(String args[]) { Th1 t1=new Th1(); System.out.println("Execution status of t1 before start="+t1.isAlive()); t1.start(); System.out.println("Execution status of t1 before start="+t1.isAlive()); try { Thread.sleep(5000); } catch(InterruptedException ie) { System.out.println("Problem in thread execution"); } System.out.println("Execution status of t1 during execution="+t1.isAlive()); try {

10

Thread.sleep(5001); } catch(InterruptedException ie) { System.out.println("problem in thread execution"); } System.out.println("Execution status of t1 after completation="+t1.isAlive()); } }

OUTPUT: Execution status of t1 before start=false

//new state

Execution status of t1 after start=true //ready state 1 2 3 4 5 6 Execution status of t1 during execution=true

//running state

7 8 9 10 Execution status of t1 after completation=false //halted state

13. Write a java program to create thread by runnable interface? Ans: package com.myjava.threads; class MyRunnableThread implements Runnable{ public static int myCount = 0; public MyRunnableThread(){ } public void run() { while(MyRunnableThread.myCount <= 10){ try{ System.out.println("Expl Thread: "+(++MyRunnableThread.myCount)); 11

Thread.sleep(100); } catch (InterruptedException iex) { System.out.println("Exception in thread: "+iex.getMessage()); } } }} public class RunMyThread { public static void main(String a[]){ System.out.println("Starting Main Thread..."); MyRunnableThread mrt = new MyRunnableThread(); Thread t = new Thread(mrt); t.start(); while(MyRunnableThread.myCount <= 10){ try{ System.out.println("Main Thread: "+(++MyRunnableThread.myCount)); Thread.sleep(100); } catch (InterruptedException iex){ System.out.println("Exception in main thread: "+iex.getMessage()); }

}

System.out.println("End of Main Thread..."); } } Example Output Starting Main Thread... Main Thread: 1 Expl Thread: 2 Main Thread: 3 Expl Thread: 4 Main Thread: 5 Expl Thread: 6 Main Thread: 7 Expl Thread: 8 Main Thread: 9 Expl Thread: 10 Main Thread: 11 End of Main Thread...

12

14. Explain inter-thread communication? Ans: If you are aware of inter-process communication then it will be easy for you to understand inter thread communication. Inter thread communication is important when you develop an application where two or more threads exchange some information. There are simply three methods and a little trick which makes thread communication possible. First let's see all the three methods listed below: SN

Methods with Description

1

public void wait() Causes the current thread to wait until another thread invokes the notify().

2

public void notify() Wakes up a single thread that is waiting on this object's monitor.

3

public void notifyAll() Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context. 15. Describe about thread priorities? Ans: MAX-PRIORITY, MIN-PRIORITY, NORM-PRIORITY MAX-PRIORITY Which represent the minimum priority that a thread can have whose values is 10. Syntax: public static final int MAX-PRIORITY=10 MIN-PRIORITY Which represents the minimum priority that a thread can have. Syntax: public static final int MIN-PRIORITY=0 NORM-PRIORITY Which represent the default priority that is assigned to a thread. Syntax: public static final int NORM-PRIORITY=5 13

DESCRIPTIVE QUESTIONS/PROGRAMS/EXPERIMENTS 1. Define multithreading? Explain in detail with an example? Ans: Multithreading is a concept in which a program is divided into two or more subprograms, which can be executed at the same time. The part of a program or subprogram is called a thread and each thread executes separately. Multithreading is a powerful programming tool that enables to write efficient programs by making maximum use of the CPU because the CPU idle time can be reduced to minimum. Multithreading is useful in a number of ways. It enables the programmers to do multiple things at a time. They can divide a large program into threads (subprograms) and execute them in parallel. Multithreading is very much important in a networked environment in which Java operates. Multithreading means running more than one thread at the same time concurrently. The processor switches between the threads and execute them parallel. The processor execute each thread so fast that it appears as if they are being done simultaneously. Multithreading is asynchronous i.e. , any thread can access any resources at any time. If two threads try to access a shard resource at the same time then there will be no problem. To prevent this, there is a synchronization concept in java. This synchronization is achieved by using ‘synchronized’ keyword. While a thread is inside a synchronized method, all the other threads are made to wait until the thread exit the monitor and release the resource to the next waiting thread. For example: 2.What is a thread? Explain its life cycle? Ans: Thread: Thread is a lightweight components and it is a flow of control. In other words a flow of control is known as thread. State or Life cycle of thread :State of a thread are classified into five types they are 1. New State 2. Ready State 3. Running State 4. Waiting State 5. Halted or dead State 14

New State If any new thread class is created that represent new state of a thread, In new state thread is created and about to enter into main memory. No memory is available if the thread is in new state. Ready State In ready state thread will be entered into main memory, memory space is allocated for the thread and 1st time waiting for the CPU. Running State Whenever the thread is under execution known as running state. Halted or dead State If the thread execution is stopped permanently than it comes under dead state, no memory is available for the thread if it comes to dead state. Note: If the thread is in new or dead state no memory is available but sufficient memory is available if that is in ready or running or waiting state. 3. Explain in detail about creating threads and synchronizing threads? Ans: When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

15

Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement: synchronized(objectidentifier) { // Access shared variables and other shared resources } Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads. Multithreading example without Synchronization: Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces different result based on CPU availability to a thread. class PrintDemo { public void printCount(){ try { for(int i = 5; i > 0; i--) System.out.println("Counter --- " + i ); } catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; ThreadDemo( String name, PrintDemo pd){ threadName = name; 16

PD = pd; } public void run() { PD.printCount(); System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null){ t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) {

PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch( Exception e) { System.out.println("Interrupted"); } }

} This produces different result every time you run this program: Starting Thread - 1 17

Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 5 Counter --- 2 Counter --- 1 Counter --- 4 Thread Thread - 1 exiting. Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting. Multithreading example with Synchronization: Here is the same example which prints counter value in sequence and every time we run it, it produces same result. class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i--) System.out.println("Counter --- " + i ); }

catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; 18

ThreadDemo( String name, PrintDemo pd) {

threadName = name; PD = pd; } public void run()

{

synchronized(PD) { PD.printCount(); } System.out.println("Thread " + threadName + " exiting."); } public void start () {System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } }

} public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch( Exception e) { System.out.println("Interrupted"); } 19

} } This produces same result every time you run this program: Starting Thread - 1 Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 1 exiting. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting.

4. Explain about Daemon threads with an example? Ans: Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits. When a new thread is created it inherits the daemon status of its parent. Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound – JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O. 20

Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such as garbage collection (gc) etc., they do not prevent the JVM from exiting (even if the daemon thread itself is running) when all the user threads (non-daemon threads) finish their execution. JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not care whether Daemon thread is running or not, if JVM finds running daemon thread (upon completion of user threads), it terminates the thread and after that shutdown itself. Properties of Daemon threads: 1. A newly created thread inherits the daemon status of its parent. That’s the reason all threads created inside main method (child threads of main thread) are non-daemon by default, because main thread is non-daemon. However you can make a user thread to Daemon

by

using setDaemon()

methodof

thread

class.

Just a quick note on main thread: When the JVM starts, it creates a thread called “Main”. Your program will run on this thread, unless you create additional threads yourself. The first thing the “Main” thread does is to look for your static void main (String args[]) method and invoke it. That is the entry-point to your program. If you create additional threads in the main method those threads would be the child threads of main thread. 2. Methods

of

Thread

class

that

are

related

to

Daemon

threads:

public void setDaemon(boolean status): This method is used for making a user thread to Daemon thread or vice versa. For example if I have a user thread t then t.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread td then by calling td.setDaemon(false) would make it normal thread(user thread/non-daemon

thread).

public boolean isDaemon(): This method is used for checking the status of a thread. It returns true if the thread is Daemon else it returns false. 3. setDaemon() method can only be called before starting the thread. This method would throw IllegalThreadStateException if you call this method after Thread.start() method. (refer the example) Daemon thread example: Ex:DaemonThreadExample1.java This example is to demonstrate the usage of setDaemon() and isDaemon() method. public class DaemonThreadExample1 extends Thread{ public void run(){ // Checking whether the thread is Daemon or not 21

if(Thread.currentThread().isDaemon()){ System.out.println("Daemon thread executing"); } else{ System.out.println("user(normal) thread executing"); } } public static void main(String[] args){ /* Creating two threads: by default they are * user threads (non-daemon threads) */ DaemonThreadExample1 t1=new DaemonThreadExample1(); DaemonThreadExample1 t2=new DaemonThreadExample1(); //Making user thread t1 to Daemon t1.setDaemon(true); //starting both the threads t1.start(); t2.start(); } } Output: Daemon thread executing User (normal) thread executing 5. Explain thread group class, methods defined by it? Explain any three of them? Ans: The java.lang.ThreadGroup class represents a set of threads. It can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent. Class declaration Following is the declaration for java.lang.ThreadGroup class: public class ThreadGroup extends Object implements Thread.UncaughtExceptionHandler Class constructors S.N.

Constructor & Description 22

1

ThreadGroup(String name) This constructs a new thread group.

2

ThreadGroup(ThreadGroup parent, String name) This creates a new thread group.

Class methods S.N.

Method & Description

1

int activeCount() This method returns an estimate of the number of active threads in this thread group.

2

int activeGroupCount() This method returns an estimate of the number of active groups in this thread group.

3

void checkAccess() This method determines if the currently running thread has permission to modify this thread group.

4

void destroy() This method Destroys this thread group and all of its subgroups.

5

int enumerate(Thread[] list) This method Copies into the specified array every active thread in this thread group and its subgroups.

6

int enumerate(Thread[] list, boolean recurse) This method copies into the specified array every active thread in this thread group.

7

int enumerate(ThreadGroup[] list) This method copies into the specified array references to every active subgroup in this thread group.

8

int enumerate(ThreadGroup[] list, boolean recurse) This method copies into the specified array references to every active subgroup in this thread group.

9

int getMaxPriority() This method returns the maximum priority of this thread group.

10

String getName() 23

This method returns the name of this thread group. 11

ThreadGroup getParent() This method returns the parent of this thread group.

12

void interrupt() This method interrupts all threads in this thread group.

13

boolean isDaemon() This method Tests if this thread group is a daemon thread group.

14

boolean isDestroyed() This method tests if this thread group has been destroyed.

15

void list() This method prints information about this thread group to the standard output.

16

boolean parentOf(ThreadGroup g) This method tests if this thread group is either the thread group argument or one of its ancestor thread groups.

17

void setDaemon(boolean daemon) This method changes the daemon status of this thread group.

18

void setMaxPriority(int pri) This method sets the maximum priority of the group.

19

String toString() This method returns a string representation of this Thread group.

20

void uncaughtException(Thread t, Throwable e) This method called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed.

Methods inherited This class inherits methods from the following classes: 

java.lang.Object

24

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOP THROUGH JAVA Tutorial Sheet: UNIT 1I-II PACKAGES & INTERFACES SHORT ANSWER QUESTIONS: 1) What is a java package? 2) What are the advantages of java packages? 3) Explain the processes of defining a package with example? 4) Explain how to create and access a java package with example? 5) Which package is always imported by default? 6) Can I import same package/class twice? Will the JVM load the package twice at runtime? 7) Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code? 8) Which package has light weight components? 9) How do we add a class or interface to package with example? 10) What do you know about the Java garbage collector? When does the garbage collection occur? 11) Does garbage collection guarantee that a program will not run out of memory? What is the purpose of garbage collection? 12) How does a class implement an interface? 13) How is an abstract class different from interface?14) Show to achieve multiple inheritance in Java using interfaces? 15) Why are the interfaces more flexible than abstract classes?

Long answer questions:

1) What are packages? types of packages? what are they used for? 2) How do we import a package? 3) Write short notes on java.io.package? 4) Explain the processes of defining an interface? 5) What is a class path?

TUTOR

FACULTY

HOD

SHORT ANSWER QUESTIONS

Q1).What is a java package? Ans To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specifiedpackage. The package statement defines a name space in which classes are stored. If youomit the package statement, the class names are put into the default package, which has no name. (This is why you haven’t had to worry about packages before now.) While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, you will define a package for your code. This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage: package MyPackage;. Q2).What are the advantages of java packages? Ans: Advantages of using a package  Reusability: Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.  Easy to locate the files.  In real life situation there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.  : It helps resolve naming conflicts when different packages have classes with the same names. This also helps you organize files within your project. For example: java.io package do something related to I/O and java.net package do something to do with network and so on. If we tend to put all .java files into a single package, as the project gets bigger, then it would become a nightmare to manage all your files.

 We can create a package as follows with package keyword, which is the first keyword in any Java program followed by import statements. The java.lang package is imported implicitly by default and all the other packages must be explicitly imported.  package com.xyz.client ;  import java.io.File;  import java.net.URL;

Q3).Explain the processes of defining a package with example? Ans: Defining a Package: This statement should be used in the beginning of the program to include that program in that particular package. package <package name>; Example: package tools; public class Hammer { public void id () { System.out.println ("Hammer"); } } Points to remember: 1. At most one package declaration can appear in a source file. 2. The package declaration must be the first statement in the unit. Naming conventions: A global naming scheme has been proposed to use the internet domain names to uniquely identify packages. Companies use their reversed Internet domain name in their package names, like this: com.company.packageName

Q4).Explain how to create and access a java package with example? Ans: The package keyword is used to create a package in java. 1.

//save as Simple.java

2.

package mypack;

3.

public class Simple{

4.

public static void main(String args[]){

5.

System.out.println("Welcome to package");

6.

}

7.

}

Compile java package If you are not using any IDE, you need to follow the syntax given below: 1.

javac -d directory javafilename

For example 1.

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot). Run java package program You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java To Run: java mypack.Simple Output:Welcome to package The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder. Q5).Which package is always imported by default? Ans: The java.lang package is always imported by default. It is by default loaded internally by the JVM. The java.lang.Class class instance represent classes and interfaces in a running Java application.It has no public constructor.

The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. The java.lang.Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. The java.lang.Compiler class is provided to support Java-to-native-code compilers and related services. By design, it serves as a placeholder for a JIT compiler implementation. The java.lang.Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Q6).Can I import same package/class twice? Will the JVM load the package twice at runtime? Ans: One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class. Q7).Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*? Ans: No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in the package bob only. It will not import any class in any of its sub package’s. Q8).Which package has light weight components? Ans: javax,swing.package.All components in swing, except JApplet, JDialog, JFrame and JWindow are light weight components. Component

Description

Comments and information sources

JAppletapi

JDialogapi

Implements a Java

The root class for

applet.

applets.

Adds enhancements

Contains a root pane as its only child; must

to java.awt.Dialog.

be managed using content panes. See JDialogapi.

JFrameapi

Adds enhancements

To be covered in an upcoming issue;

to java.awt.Frame.

meanwhile,

Adds enhancements JWindowapi

to java.awt.Window.

Q9).How do we add a calss or interface to package with example? Ans: packages s1; public class A { } The package s1 contains one public class by name A.if suppose we want to add another calss B to this package we must follow the below steps. 1) Define the class and make it public. Now place the package statement before the class definition as shown below

package s1; public class B {

} 1. Store this B.Java file under the directory s1. 2. Compile B.java file.This creation a B.class file and place it in the directory S1. Using the same procedure we can also add a non public class to a package.Now the package S1 contains both the classes A and B.The below statement is used for importing both the classes import s1.*;

Q10). What do you know about the Java garbage collector? When does the garbage collection occur? Ans: Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the

memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (background) thread. We can nicely ask the garbage collector to collect garbage by calling System.gc() but we can’t force it.

Q11).Does garbage collection guarantee that a program will not run out of memory? What is the purpose of garbage collection? Ans: No, it doesn't .it is possible for programs to use up memory resources faster than they are garbage collected. it is also possible for programs to create objects that are not subject to garbage collection. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

Q12).How does a class implement an interface? Ans: I must provide all of the methods in the interface and identify the interface in its implements clause. This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface. Note: Class implements interface but an interface extends another interface. interface My Interface { public void method1(); public void method2(); } class XYZ implements MyInterface { public void method1() { System.out.println("implementation of method1"); } public void method2() { System.out.println("implementation of method2"); } public static void main(String arg[]) {

MyInterface obj = new XYZ(); obj. method1(); } } Output: implementation of method1 Q13). How is an abstract class different from interface? Ans:

1

2

3

4

5

6

7

Abstract Classes

Interfaces

Abstract class can extend only one class or one

Interface can extend any number of

abstract class at a time

interfaces at a time

Abstract class can extend from a class or from

Interface can extend only from an

an abstract class

interface

Abstract class can have both abstract and

Interface can have only abstract

concrete methods

methods

A class can extend only one abstract class In abstract class keyword ‘abstract’ is mandatory to declare a method as an abstract

A class can implement any number of interfaces In an interface keyword ‘abstract’ is optional to declare a method as an abstract

Abstract class can have protected , public and

Interface can have only public abstract

public abstract methods

methods i.e. by default

Abstract class can have static, final or static

Interface can have only static final

final variable with any access specifier

(constant) variable i.e. by default

Q14).Show to achieve multiple inheritance in Java using interfaces? Ans : interface X { public void myMethod(); }

interface Y { public void myMethod(); } class Demo implements X, Y { public void myMethod() { System.out.println(" Multiple inheritance example using interfaces"); } } Q15).Why are the interfaces more flexible than abstract classes? Ans: 

An interface defined type can be implemented by any class in a class hierarchy and can be extended by another interface. In contrast, any abstract class defined type can be implemented only by classes that subclass the abstract class.



An interface defined type can be used well in polymorphism. The so-called interface type vs implementation types.



Abstract classes evolve more easily than interfaces. If you add a new concrete method to an abstract class, The hierarchy system is still working. If you add a method to an interface the classes that really on the interface will break when recompiled .



Generally, user interfaces for flexibility, use abstract classes for ease of evolution(like expanding class functionality).

LONG ANSWER QUESTIONS

Q1).What are packages?Types of packages?What are they used for? Ans :Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages.Many implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize class files into packages. All we need to do is put related class files in the same directory, give the directory a name that relates to the purpose of the classes, and add line to the top of each class file that declares the package name, which is the same as the director name where they reside.In java there are already many predefined packages that we use while programming. example:java.lang, java.io, java.util. However one of the most useful feature of java is that we can define our own packages Types of package 1) User defined package: The package we create is called user-defined package. 2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages. How to Use a Package: 1. We can call it by its full name. For instance, com.myPackage1.myPackage2 myNewClass = new com.myPackage1.myPackage2(); However this method is very time consuming. So normally we use the second method. 2.

We

use

the

“import”

keyword

to

access

packages.

If

you

say

import

com.myPackage1.myPackage2, then every time we type “myPackage2″, the compiler will understand that we mean com.myPackage1.myPackage2. So we can do:

import com.myPackage1.myPackage2; class myClass { myPackage2 myNewClass= new myPackage2 (); … … … }

Q2).How do we import a package? Ans: There are two ways of importing package: Importing only a single member of the package //here ‘subclass’ is a java file in myPackage2 import com.myPackage1.myPackage2.subClass; class myClass { subClass myNewClass= new subClass(); … … … } Importing all members of a package. import com.myPackage1.*; import java.sql.* ; Also, when we use *, only the classes in the package referred are imported, and not the classes in the sub package. The

Java

runtime

automatically

imports

two

entire

packages

by

default:

The java.lang package and the current package by default (the classes in the current folder/directory).

Points to remember: 1. Sometimes class name conflict may occur. For example: There are two packages myPackage1 and myPackage2.Both of these packages contains a class with the same name, let it be myClass.java. Now both this packages are imported by some other class. import myPackage1.*; import myPackage2.*; This will cause compiler error. To avoid these naming conflicts in such a situation, we have

to be more specific and use the member’s qualified name to indicate exactly which myClass.java class we want: myPackage1.myClass myNewClass1 = new myPackage1.myClass (); myPackage2.myClass myNewClass2 = new myPackage1.myClass (); 2. While creating a package, which needs some other packages to be imported, the package statement should be the first statement of the program, followed by the import statement. Q3).Write short notes on java.io.package? Ans: Java.io package provides classes for system input and output through data streams, serialization and the file system. This reference will take you through simple and practical methods available in java.io package Java.io.BufferedInputStream :The Java.io.BufferedInputStream class adds functionality to another input stream, the ability to buffer the input and to support the mark and reset methods. Following are the important points about BufferedInputStream: 

When the BufferedInputStream is created, an internal buffer array is created.



As bytes from the stream are read or skipped, the internal buffer is refilled as

necessary from the contained input stream, many bytes at a time. Class declaration Following is the declaration for Java.io.BufferedInputStream class: public class BufferedInputStream extends FilterInputStream Java.io.BufferedOutputStream :The Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. Class declaration Following is the declaration for Java.io.BufferedOutputStream class: public class BufferedOutputStream extends FilterOutputStream

Java.io.BufferedReader :The Java.io.BufferedReader class reads text from a characterinput stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.Following are the important points about BufferedReader: 

The buffer size may be specified, or the default size may be used.



Each read request made of a Reader causes a corresponding read request to be

made of the underlying character or byte stream. Class declaration Following is the declaration for Java.io.BufferedReader class: public class BufferedReader extends Reader Introduction Java.io.BufferedWriter :The Java.io.BufferedWriter class writes text to a characteroutput stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.Following are the important points about BufferedWriter: 

The buffer size may be specified, or the default size may be used.



A Writer sends its output immediately to the underlying character or byte

stream. Class declaration Following is the declaration for Java.io.BufferedWriter class: public class BufferedWriter extends Writer

Java.io.File :The Java.io.File class is an abstract representation of file and directory pathnames. Following are the important points about File: 

Instances may or may not denote an actual file-system object such as a file or

a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. 

A file system may implement restrictions to certain operations on the actual

file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.



Instances of the File class are immutable; that is, once created, the abstract

pathname represented by a File object will never change. Class declaration Following is the declaration for Java.io.File class: public class File extends Object implements Serializable, Comparable

Java.io.InputStream :The Java.io.InputStream class is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input. Class declaration Following is the declaration for Java.io.InputStream class: public abstract class InputStream extends Object implements Closeable Java.io.InputStreamReader :The Java.io.InputStreamReader class is a bridge from byte streams to character streams.It reads bytes and decodes them into characters using a specified charset. Class declaration Following is the declaration for Java.io.InputStreamReader class: public class InputStreamReader extends Reader Java.io.OutputStream :The Java.io.OutputStream class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Class declaration Following is the declaration for Java.io.OutputStream class:

public abstract class OutputStream extends Object implements Closeable, Flushable Java.io.OutputStreamWriter :The Java.io.OutputStreamWriter class is a bridge from character streams to byte streams. Characters written to it are encoded into bytes using a specified charset. Class declaration Following is the declaration for Java.io.OutputStreamWriter class: public class OutputStreamWriter extends Writer

Q4). Explain the processes of defining and implementing an interface ? Ans :Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface: Example: Let us look at an example that depicts encapsulation: /* File name : NameOfInterface.java */ import java.lang.*; //Any number of import statements public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations\ }

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class

Declaration following the extends portion of the declaration.

/* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return0; }

Interfaces have the following properties: • An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. • Methods in an interface are implicitly public. Example: /* File name : Animal.java */ interface Animal {

public void eat(); public void travel(); } Example: public static void main(String args[]) { MammalInt m =new MammalInt(); m.eat(); m.travel(); } } This would produce the following result: Mammal eats Mammal travels When overriding methods defined in interfaces there are several rules to be followed: • Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. • The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. • An implementation class itself can be abstract and if so interface methods need not be implemented. When implementation interfaces there are several rules: • A class can implement more than one interface at a time. • A class can extend only one class, but implement many interfaces. • An interface can extend another interface, similarly to the way that a class can extend another class

Q5).What is a class path? Ans:It is a environmental variable, which contains the path for the default-working directory (.). The specific location that java compiler will consider, as the root of any package hierarchy is, controlled by Classpath Set CLASSPATH SystemVariable:

To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell): • In Windows -> C:\> set CLASSPATHAt the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is.class For example: // File Name: Dell.java package com.apple.computers; public class Dell { } classUps { } Now, compile this file as follows using -d option: $javac -d .Dell.java This would put compiled files as follows: .\com\apple\computers\Dell.class .\com\apple\computers\Ups.class You can import all the classes or interfaces defined in \com\apple\computers\ as follows: import com.apple.computers.*; Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:

<path-one>\sources\com\apple\computers\Dell.java <path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters. A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (UNIX). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path. In UNIX -> % echo $CLASSPATH To delete the current contents of the CLASSPATH variable, use: • In Windows -> C:\> set CLASSPATH= • In UNIX -> % unset CLASSPATH; export CLASSPATH To set the CLASSPATH variable: • In Windows -> set CLASSPATH=C:\users\jack\java\classes • In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOPS THROUGH JAVA Tutorial Sheet: UNIT III-1 EXCEPTION HANDLING Short answer questions 1. What is an Exception 2. What is Exception Handling 3. What are the different types of exceptions 4. What is checked exception list any 3 checked exceptions 5. What is Unchecked exception list any 3 Unchecked exceptions 6. Draw and Explain Exception Hierarchy 7. List the clauses used in java to handle exceptions along with syntax of each clause 8. Explain syntax and differences between throw and throws clauses with examples 9. What is a built-in exception 10. Explain the syntax of multiple catch block with necessary example 11. Write a short note on the following a) FileNotFoundException b) IOException 12. Explain about compile time errors and runtime errors and list out various compile time and runtime errors 13. How do you create your own exception classes 14. Explain about re-throwing an exception 15. Discuss about the nested try statement with syntax Descriptive questions/Programs/Experiment 1. Define and explain exception handling? 2. Explain java’s built-in exception? 3. What is exception? What are the different types of exceptions? 4. Explain in detail about checked and unchecked exception with examples? 5. Explain in detail about the usage of try, catch, throw, throws and finally with examples? Tutor

Faculty

HOD 1

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16 Tutorial Sheet: III-1 Question & Answers SHORT ANSWER QUESTIONS

1. What is an Exception Ans: An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions. 

Unexpected events (End of File)



Erroneous events (Subscript out of bounds)

When an exception occurs, the method currently executing creates an exception object and passes it to the runtime system, which looks for a special block of code, called an exception handler, that deals with the exception 2. What is Exception Handling Ans: The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful features of Java to handle run time error and maintain normal flow of java application. Handling the exception is nothing but converting system error generated message into user friendly error message. Whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user friendly error message. You can convert system error message into user friendly error message by using exception handling feature of java. For Example: when you divide any number by zero then system generate / by zero so this is not understandable by user so you can convert this message into user friendly error message like Don't enter zero for denominator. 3. What are the different types of Exceptions Ans: Type of Exception 1. Checked Exception 2. Un-Checked Exception

2

Checked Exception are the exception which checked at compile-time. These exception are directly sub-class of java.lang.Exception class. Un-Checked Exception are the exception both identifies or raised at run time. These exceptions are directly sub-classed of java.lang.RuntimeException class. 4. What is checked exception list any 3 checked exceptions Ans: Checked Exception: Checked Exception are the exception which checked at compile-time. These exception are directly sub-class of java.lang.Exception class. Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.

5. What is checked exception list any 3 checked exceptions Ans: Un-Checked Exception: Un-Checked Exception are the exception both identifies or raised at run time. These exceptions are directly sub-classed of java.lang.RuntimeException class. Note: In real time application mostly we can handle un-checked exception. Only for remember: Un-checked means not checked by compiler so un-checked exceptions are checked at run-time not compile time.

3

6. Draw the hierarchy of Exception classes Ans:

7. List the clauses used in java to handle exceptions along with syntax for each clause Ans: Use Five keywords/clauses for Handling the Exception 

try



catch



finally



throws



throw

4

Syntax for handling the exception Syntax for try, catch and finally try { // statements causes problem at run time } catch(type of exception-1 object-1) { // statements provides user friendly error message } catch(type of exception-2 object-2) { // statements provides user friendly error message } finally { // statements which will execute compulsory }

Syntax of throw class className { returntype method(...) throws Exception_class { throw(Exception obj) } }

Syntax of throws returnType methodName(parameter)throws Exception_class.... { ..... }

5

8. Explain syntax and differences between throw and throws clauses with examples Ans: throw and throws Throw: throw is a keyword in java language which is used to throw any user defined exception to the same signature of method in which the exception is raised. Note: throw keyword always should exist within method body. whenever method body contain throw keyword than the call method should be followed by throws keyword. Syntax class className { returntype method(...) throws Exception_class { throw(Exception obj) } }

Throws: throws is a keyword in java language which is used to throw the exception which is raised in the called method to it's calling method throws keyword always followed by method signature. Syntax returnType methodName(parameter)throws Exception_class.... { ..... }

Difference between throw and throws Throw throw is a keyword used for hitting and 1 generating the exception which are occurring as a part of method body

2

The place of using throw keyword is always as a part of method body.

throws throws is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages The place of using throws is a keyword is always as a part of method heading 6

When we use throw keyword as a part of method body, it is mandatory to the java 3 programmer to write throws keyword as a part of method heading

When we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body.

Example of throw and throws Example // save by DivZero.java package pack; public class DivZero { public void division(int a, int b)throws ArithmeticException { if(b==0) { ArithmeticException ae=new ArithmeticException("Does not enter zero for Denominator"); throw ae; } else { int c=a/b; System.out.println("Result: "+c); } } }

9. What is a built-in exception Ans: Java defines several exception classes inside the standard package java.lang. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. Java defines several other types of exceptions that relate to its various class libraries.

7

10. Explain the syntax of multiple catch block with necessary example Ans: Multiple catch block You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example. Example import java.util.*; class ExceptionDemo { public static void main(String[] args) { int a, b, ans=0; Scanner s=new Scanner(System.in); System.out.println("Enter any two numbers: "); try { a=s.nextInt(); b=s.nextInt(); ans=a/b; System.out.println("Result: "+ans); } catch(ArithmeticException ae) { System.out.println("Denominator not be zero"); } catch(Exception e) { System.out.println("Enter valid number"); } } }

Output Enter any two number: 5 0 Denominator not be zero

8

11. Write a short note on the following

a) FileNotFoundException b) IOException

Ans: a) FileNotFoundException: If the given filename is not available in a specific location ( in file handling concept) then FileNotFoundException will be raised. This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors.

This exception is thrown during a failed attempt to open the file denoted by a specified pathname. Also, this exception can be thrown when an application tries to open a file for writing, but the file is read only, or the permissions of the file do not allow the file to be read by any application. This exception extends the IOException class, which is the general class of exceptions produced by failed or interrupted I/O operations. Also, it implements the Serializableinterface and finally, the FileNotFoundException exists since the first version of Java (1.0). b) IOException: This is exception is raised whenever problem occurred while writing and reading the data in the file. This exception is occurred due to following reason; 

When try to transfer more data but less data are present.



When try to read data which is corrupted.



When try to write on file but file is read only.

An IOException can occur in a variety of ways when you try to access the local filesystem. In the following Java code segment an IOException can be thrown by the br.readLine() method, so a try/catch wrapper is used around that portion of code to trap (and arguably deal with) the potential problem: BufferedReader br = new BufferedReader(new FileReader(f)); String s = null; try { while ((s = br.readLine()) != null) { System.out.println(s); } }

9

catch (IOException e) { // deal with the error here ... e.printStackTrace(); }

12. Explain about compile time errors and runtime errors and list out various compile time and runtime errors Ans: At compile time, when the code does not comply with the Java syntactic and semantics rules as described in Java Language Specification (JLS), compile-time errors will occurs. The goal of the compiler is to ensure the code is compliant with these rules. Any rule-violations detected at this stage are reported as compilation errors. The best way to get to know those rules is to go through all the sections in the JLS containing the key words "compile-time error". In general, these rules include syntax checking: declarations, expressions, lexical parsing, file-naming conventions etc; exception handling: for checked exceptions; accessibility, type-compatibility, name resolution: checking to see all named entities - variables, classes, method calls etc. are reachable through at least one of the declared path; etc. The following are some common compile time errors:         

a class tries to extend more than one class overloading or overriding is not implemented correctly attempt to refer to a variable that is not in the scope of the current block an inner class has the same name as one of one of its enclosing classes a class contains one or more abstract methods and the class itself is not declared "abstract" a class tries to reference a private member of another class trying to create an instance of an abstract class trying to change the value of an already initialized constant (final member) declare two (class or instance) members with the same name When the code compiles without any error, there is still chance that the code will fail at run time. The errors only occurs at run time are call run time errors. Run time errors are those that passed compiler's checking, but fails when the code gets executed. There are a lot of causes may result in runtime errors, such as incompatible type-casting, referencing an invalid index in an array, using an null-object, resource problems like unavailable file-handles, out of memory situations, thread dead-locks, infinite loops(not detected!), etc.

10

The following are some common runtime errors:      

trying to invoke a method on an uninitialized variable (NullPointerException) ran out memory (memory leaks...) (OutOfMemoryError) trying to open a file that doesn't exist (FileNotFoundException) trying to pass arguments to a method which are not within the accepted bounds (IllegalArgumentException) trying to invoke the start() method on a dead thread (IllegalThreadStateException) trying to invoke wait() or notify() on an object without owning the object's monitor (IllegalMonitorStateException) 13. How do you create your own exception classes Ans: Custom Exception: If any exception is design by the user known as user defined or Custom Exception. Custom Exception is created by user.

Rules to design user defined Exception: 1. Create a package with valid user defined name. 2. Create any user defined class. 3. Make that user defined class as derived class of Exception or RuntimeException class. 4. Declare parameterized constructor with string variable. 5. call super class constructor by passing string variable within the derived class constructor. 6. Save the program with public class name.java

11

14. Explain about re-throwing an exception Ans: When you catch an exception, it's possible to rethrow it. This is just the same as if you hadn't caught it in the first place - the exception will continue to bubble up through the layers until it reaches some other code that catches it (or it reaches the top of the stack and the program exits).

So why would you do this? Well, it means you have temporary access to the exception at the point where you caught it. One situation I've used this in is where I want to log the fact that an error has occurred, but the real error handling is happening at a higher level. You'd only do this, though, if this local logging could add something useful that the higher level error handling doesn't know about. 1

...

2

try {

3

riskyOperationThatCanThrowAnException(target);

4

}

5

catch (IOException ex) { Logger.log("Exception while carrying out risky operation on " + target);

6

throw ex;

7 }

8

15. Discuss about the nested try statement with syntax Ans: Inside try block we write the block of statements which causes executions at run time in other words try block always contains problematic statements. Important points about try block: 

If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.



After executing appropriate catch block, even through we use run time statement, CPU control never goes to try block to execute the rest of the statements.



Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

Syntax try { .....

12

} /* Here no other statements are allowed between try and catch block */ catch() { .... }



Each and every try block must contains at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages.



One try block can contains another try block that is nested or inner try block can be possible.

Syntax try { ....... try { ....... } }

DESCRIPTIVE QUESTIONS/PROGRAMS/EXPERIMENTS 1. Define and explain exception handling? Ans: Exception Handling The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful features of Java to handle run time error and maintain normal flow of java application.

Why we use Exception Handling Handling the exception is nothing but converting system error generated message into user friendly error message. Whenever an exception occurs in the java application, JVM will create 13

an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user friendly error message. You can convert system error message into user friendly error message by using exception handling feature of java. For Example: when you divide any number by zero then system generate / by zero so this is not understandable by user so you can convert this message into user friendly error message like Don't enter zero for denominator. Hierarchy of Exception classes:

Type of Exception 

Checked Exception



Un-Checked Exception

Checked Exception are the exception which checked at compile-time. These exception are directly sub-class of java.lang.Exception class. Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.

14

Un-Checked Exception are the exception both identifies or raised at run time. These exceptions are directly sub-classed of java.lang.RuntimeException class. Note: In real time application mostly we can handle un-checked exception. Only for remember: Un-checked means not checked by compiler so un-checked exceptions are checked at run-time not compile time.

Handling the Exception Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java. Five keywords for Handling the Exception try, catch, finally, throws, throw Syntax for handling the exception 15

Syntax try { // statements causes problem at run time } catch(type of exception-1 object-1) { // statements provides user friendly error message } catch(type of exception-2 object-2) { // statements provides user friendly error message } finally { // statements which will execute compulsory } 2. Explain java’s built-in exception? Ans: Java defines several exception classes inside the standard package java.lang. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. Java defines several other types of exceptions that relate to its various class libraries. Following is the list of Java Unchecked RuntimeException. Exception

Description

ArithmeticException

Arithmetic error, such as divide-byzero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException

Assignment to an array element of an incompatible type.

ClassCastException

Invalid cast.

IllegalArgumentException

Illegal argument used to invoke a 16

method. IllegalMonitorStateException

Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException

Environment or application is in incorrect state.

IllegalThreadStateException

Requested operation not compatible with current thread state.

IndexOutOfBoundsException

Some type of index is out-of-bounds.

NegativeArraySizeException

Array created with a negative size.

NullPointerException

Invalid use of a null reference.

NumberFormatException

Invalid conversion of a string to a numeric format.

SecurityException

Attempt to violate security.

StringIndexOutOfBounds

Attempt to index outside the bounds of a string.

UnsupportedOperationException

An unsupported encountered.

operation

was

Following is the list of Java Checked Exceptions Defined in java.lang. Exception

Description

ClassNotFoundException

Class not found.

CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. IllegalAccessException

Access to a class is denied.

InstantiationException

Attempt to create an object of an abstract class or interface.

InterruptedException

One thread has been interrupted by another thread.

NoSuchFieldException

A requested field does not exist.

NoSuchMethodException

A requested method does not exist.

17

3. What is exception? What are the different types of exceptions? Ans: An Exception is a runtime error that indicates that a problem occurred during programs execution. A Java exception is an instance of a class derived from throwable. This throwable class is stored in the java.lang package and subclasses of throwable are contained in different packages.

4. Explain in detail about checked and unchecked exception with examples? Ans: Checked exceptions: A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care of (handle) these exceptions. For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]){ File file=new File("E://file.txt");

18

FileReader fr = new FileReader(file); }

}

If you try to compile the above program you will get exceptions as shown below. C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error

Note: Since the methods read() and close() of FileReader class throws IOException, you can observe that compiler notifies to handle IOException, along with FileNotFoundException.  Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime Exceptions, these include programming bugs, such as logic errors or improper use of an API. runtime exceptions are ignored at the time of compilation. For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexceptionoccurs. public class Unchecked_Demo {

public static void main(String args[]){ int num[]={1,2,3,4}; System.out.println(num[5]); }

}

If you compile and execute the above program you will get exception as shown below.  

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

5. Explain in detail about the usage of try, catch, throw, throws and finally with examples? Ans: try block: 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. 19

Syntax of java try-catch try{ //code that may throw exception }catch(Exception_class_Name ref){} Catch block: Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try. public class Testtrycatch2{ 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..."); } } Output: Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code. Now, as displayed in the above example, rest of the code is executed i.e. rest of the code statement is printed. throw Keyword throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax : throw ThrowableInstance Creating Instance of Throwable class There are two possible ways to get an instance of class Throwable, 1.

Using a parameter in catch block.

2. 3.

Creating instance with new operator. new NullPointerException("test"); This constructs an instance of NullPointerException with name test.

Example demonstrating throw Keyword class Test { static void avg() 20

{ try { throw new ArithmeticException("demo"); } catch(ArithmeticException e) { System.out.println("Exception caught"); } } public static void main(String args[]) { avg(); } } In the above example the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement. throws Keyword Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword. Syntax : type method_name(parameter_list) throws exception_list { //definition of method } NOTE : It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their subclass. Example demonstrating throws Keyword class Test { 21

static void check() throws ArithmeticException { System.out.println("Inside check function"); throw new ArithmeticException("demo"); } public static void main(String args[]) { try { check(); } catch(ArithmeticException e) { System.out.println("caught" + e); } } } finally clause A finally keyword is used to create a block of code that follows a try block. A finally block of code always executes whether or not exception has occurred. Using a finally block, lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block. Example demonstrating finally Clause Class ExceptionTest { public static void main(String[] args) { int a[]= new int[2]; System.out.println("out of try"); try 22

{ System.out.println("Access invalid element"+ a[3]); /* the above statement will throw ArrayIndexOutOfBoundException */ } finally { System.out.println("finally is always executed."); } } } Output: Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception. You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.

23

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / II

Academic year: 2015-16

SUB:OOPS THROUGH JAVA Tutorial Sheet: UNIT V-1 SWING Short answer questions 1. Explain the steps ivolved In Jtextfield 2. Write a java program to illustrate Jtextfield 3. Explain about JLabel and constructor of JLable 4. Explain about Jbutton and constructor of jbutton 5. Write a java program using four push buttons and a label. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the label. 6. Explain about JCheckBox and constructors in it? 7. Write a java program to illustrate JCheckBox 8. Explain about JToggleButton and constructors in it 9. Write a java program to illustrate JtoggleButton 10. Explain about radio buttons and constructors in it 11. Write a java program to illustrate Radio Buttons

Descriptive questions/programs/experiments 1.Explain about JComboBox 2.Write in detail about Trees 3.Write in detail about Tables. 4. Explain about Jscrollpane 5.Explain about Jtabbedpane Tutor

Faculty

HOD 17

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / I

Academic year: 2015-16

Tutorial Sheet:V-1 Question & Answers SHORT ANSWER QUESTIONS 1.Explain the steps ivolved In Jtextfield Ans:JTextField is the simplest Swing text component. It is also probably its most widely used text component. JTextField allows you to edit one line of text. It is derived from jextComponent, which provides the basic functionality common to Swing text components. JTextField uses the Document interface for its model. Three of JTextField’s constructors are shown here: JTextField(int cols) JTextField(String str, int cols) JTextField(String str) Here, str is the string to be initially presented, and cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string. JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the user presses enter. A CaretEvent is fired each time the caret (i.e., the cursor) changes position. (CaretEvent is packaged in javax.swing.event.) Other events are also possible. In many cases, your program will not need to handle these events. Instead,you will simply obtain the string currently in the text field when it is needed. To obtain the text currently in the text field, call getText( ). 2. Write a java program to illustrate Jtextfield Ans:// Demonstrate JTextField. import java.awt.*; import java.awt.event.*; 18

import javax.swing.*; /* */ public class JTextFieldDemo extends JApplet { JTextField jtf; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add text field to content pane. jtf = new JTextField(15); add(jtf); jtf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Show text when user presses ENTER. showStatus(jtf.getText());}});}}

19

3.Explin about JLabel and constructor of JLable Ans:JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to display text and/or an icon. It is a passive component in that it does not respond to user input. JLabel defines several constructors. Here are three of them: JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the SwingConstants interface, along with several others used by the Swing classes. 4.Explain about Jbutton and constructor of jbutton The JButton class provides the functionality of a push button. You have already seen a simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be associated with the push button. Three of its constructors are shown here: JButton(Icon icon) JButton(String str) JButton(String str, Icon icon) Here, str and icon are the string and icon used for the button.When the button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( ) method of the registered ActionListener, you can obtain the action command string associated with the button. By default, this is the string displayed.inside the button. However, you can set the action command by calling setActionCommand( ) on the button. You can obtain the action command by calling getActionCommand( ) on the event object. It is declared like this: String getActionCommand( ) The action command identifies the button. Thus, when using two or more buttons within the same application, the action command gives you an easy way to determine which button was pressed. 20

5.Write a java program using four push buttons and a label. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the label. Ans: // Demonstrate an icon-based JButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JButtonDemo extends JApplet implements ActionListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add buttons to content pane. ImageIcon france = new ImageIcon("france.gif"); JButton jb = new JButton(france); jb.setActionCommand("France"); jb.addActionListener(this); 21

add(jb); ImageIcon germany = new ImageIcon("germany.gif"); jb = new JButton(germany); jb.setActionCommand("Germany"); jb.addActionListener(this); add(jb); ImageIcon italy = new ImageIcon("italy.gif"); jb = new JButton(italy); jb.setActionCommand("Italy"); jb.addActionListener(this); add(jb);Part III ImageIcon japan = new ImageIcon("japan.gif"); jb = new JButton(japan); jb.setActionCommand("Japan"); jb.addActionListener(this); add(jb); // Create and add the label to content pane. jlab = new JLabel("Choose a Flag"); add(jlab);} // Handle button events. public void actionPerformed(ActionEvent ae) { jlab.setText("You selected " + ae.getActionCommand());}} Output from the button example is shown here:.

22

6.Explain about JCheckBox and constructors in it? Ans: The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines several constructors. The one used here is JCheckBox(String str) It creates a check box that has the text specified by str as a label. Other constructors let you specify the initial selection state of the button and specify an icon.When the user selects or deselects a check box, an ItemEvent is generated. You can obtain a reference to the JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged(

23

) method defined by ItemListener. The easiest way to determine the selected state of a check box is to call isSelected( ) on the JCheckBox instance. 7.Write a java program to illustrate JCheckBox // Demonstrate JCheckbox. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JCheckBoxDemo extends JApplet implements ItemListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add check boxes to the content pane. JCheckBox cb = new JCheckBox("C"); cb.addItemListener(this); add(cb); cb = new JCheckBox("C++"); 24

cb.addItemListener(this); add(cb); cb = new JCheckBox("Java"); cb.addItemListener(this); add(cb); cb = new JCheckBox("Perl"); cb.addItemListener(this); add(cb); // Create the label and add it to the content pane. add(jlab);} // Handle item events for the check boxes. public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); if(cb.isSelected()) jlab.setText(cb.getText() + " is selected"); else jlab.setText(cb.getText() + " is cleared");}} Output from this example is shown here:

8.Explain about JToggleButton and constructors in it Ans:A useful variation on the push button is called a toggle button. A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its two states. Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also 25

represent two-state controls. Thus, JToggleButton defines the basic functionality of all two-state components. JToggleButton defines several constructors. The one used by the example in this section is shown here: JToggleButton(String str) This creates a toggle button that contains the text passed in str. By default, the button is in the off position. Other constructors enable you to create toggle buttons that contain images, or images and text. JToggleButton

uses

a

model

defined

by

a

nested

class

called

JToggleButton.ToggleButtonModel. Normally, you won’t need to interact directly with the model to use a standard toggle button. Like JButton, JToggleButton generates an action event each time it is pressed. Unlike JButton, however, JToggleButton also generates an item event. This event is used by those components that support the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is deselected. To handle item events, you must implement the ItemListener interface. each time an item event is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a reference to the JToggleButton instance that generated the event. It is shown here: Object getItem( ) A reference to the button is returned. You will need to cast this reference to JToggleButton. The easiest way to determine a toggle button’s state is by calling the isSelected( ) method (inherited from AbstractButton) on the button that generated the event. It is shown here: boolean isSelected( ) It returns true if the button is selected and false otherwise. 9.Write a java program to illustrate JtoggleButton // Demonstrate JToggleButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* 26

*/ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jtbn; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Create a label. jlab = new JLabel("Button is off."); // Make a toggle button. jtbn = new JToggleButton("On/Off"); // Add an item listener for the toggle button. jtbn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if(jtbn.isSelected()) jlab.setText("Button is on."); else jlab.setText("Button is off.");} }); // Add the toggle button and label to the content pane. 27

add(jtbn); add(jlab);}} The output from the toggle button example is shown here

. 10.Explain about radio buttons and constructors in it Ans: Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. They are supported by the JRadioButton class, which extends JToggleButton. JRadioButton provides several constructors. The one used in the example is shown here: JRadioButton(String str) Here, str is the label for the button. Other constructors let you specify the initial selection state of the button and specify an icon.In order for their mutually exclusive nature to be activated, radio buttons must be configured into a group. Only one of the buttons in the group can be selected at any time.For example, if a user presses a radio button that is in a group, any previously selected button in that group is automatically deselected. A button group is created by the ButtonGroup class. Its default constructor is invoked for this purpose. Elements are then added to the button group via the following method: void add(AbstractButton ab) Here, ab is a reference to the button to be added to the group.A JRadioButton generates action events, item events, and change events each time the button selection changes. Most often, it is the action event that is handled, which means that you will normally implement the ActionListener interface. Recall that the only method defined by ActionListener is actionPerformed( ). Inside this method, you can use a number of different ways to determine which button was selected. First, you can check its action command by calling 28

getActionCommand( ). By default, the action command is the same as the button label, but you can set the action command to something else by calling setActionCommand( ) on the radio button. Second, you can call getSource( ) on the ActionEvent object and check that reference against the buttons. Finally, you can simply check each radio button to find out which one is currently selected by calling isSelected( ) on each button. Remember, each time an action event occurs, it means that the button being selected has changed and that one and only one button will be selected. 11.Write a java program to illustrate Radio Buttons Ans: // Demonstrate JRadioButton import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JRadioButtonDemo extends JApplet implements ActionListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); 29

// Create radio buttons and add them to content pane. JRadioButton b1 = new JRadioButton("A"); b1.addActionListener(this); add(b1); JRadioButton b2 = new JRadioButton("B"); b2.addActionListener(this); add(b2); JRadioButton b3 = new JRadioButton("C"); b3.addActionListener(this); add(b3); // Define a button group. ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); bg.add(b3); // Create a label and add it to the content pane. jlab = new JLabel("Select One"); add(jlab);} // Handle button selection. public void actionPerformed(ActionEvent ae) { jlab.setText("You selected " + ae.getActionCommand());}} Output from the radio button example is shown here:

30

LONG ANSWER QUESTIONS 1.Explain about JTbbedPane? Ans:JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with tabs. Selecting a tab causes the component associated with that tab to come to the forefront. Tabbed panes are very common in the modern GUI, and you have no doubt used them many times. Given the complex nature of a tabbed pane, they are surprisingly easy to create and use. JTabbedPane defines three constructors. We will use its default constructor, which creates an empty control with the tabs positioned across the top of the pane. The other two constructors let you specify the location of the tabs, which can be along any of the four sides. JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling addTab( ). Here is one of its forms: void addTab(String name, Component comp) Here, name is the name for the tab, and comp is the component that should be added to the tab. Often, the component added to a tab is a JPanel that contains a group of related components.This technique allows a tab to hold a set of components. The general procedure to use a tabbed pane is outlined here: 1. Create an instance of JTabbedPane. 2. Add each tab by calling addTab( ). 3. Add the tabbed pane to the content pane. The following example illustrates a tabbed pane. The first tab is titled "Cities" and contains four buttons. Each button displays the name of a city. The second tab is titled "Colors" and contains three check boxes. Each check box displays the name of a color. The third tab is titled "Flavors" and contains one combo box. This enables the user to select one of three flavors. // Demonstrate JTabbedPane. import javax.swing.*; /* */ public class JTabbedPaneDemo extends JApplet { 31

public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); add(jtp);}} // Make the panels that will be added to the tabbed pane. class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4);}}t III class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); 32

add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3);}} class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox<String> jcb = new JComboBox<String>(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb);}} Output from the tabbed pane example is shown in the following three illustrations:

33

2.Explain about JScrollPane? Ans:JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can be either an individual component, such as a table, or a group of components contained within another lightweight container, such as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars. The viewable area of a scroll pane is called the viewport. It is a window in which the component being scrolled is displayed. Thus, the viewport displays the visible portion of the component being scrolled. The scroll bars scroll the component through the viewport.In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as needed.For example, if the component is taller than the viewport, a vertical scroll bar is added. If the component will completely fit within the viewport, the scroll bars are removed.JScrollPane defines several constructors. The one used in this chapter is shown here: JScrollPane(Component comp) The component to be scrolled is specified by comp. Scroll bars are automatically displayed when the content of the pane exceeds the dimensions of the viewport.Here are the steps to follow to use a scroll pane: 1. Create the component to be scrolled. 2. Create an instance of JScrollPane, passing to it the object to scroll. 3. Add the scroll pane to the content pane. The following example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons are added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the 34

scroll pane is added to the content pane. Because the panel is larger than the viewport, vertical and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the buttons into view. // Demonstrate JScrollPane. import java.awt.*; import javax.swing.*; /* */ public class JScrollPaneDemo extends JApplet { public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() {art III // Add 400 buttons to a panel. JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b;}} // Create the scroll pane. JScrollPane jsp = new JScrollPane(jp); 35

// Add the scroll pane to the content pane. // Because the default border layout is used, // the scroll pane will be added to the center. add(jsp, BorderLayout.CENTER);}} Output from the scroll pane example is shown here:

3. Write in detail about Trees Ans: A tree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the tree class. A sampling of its constructors is shown here: JTree(Object obj [ ]) JTree(Vector v) JTree(TreeNode tn)Part III In the first form, the tree is constructed from the elements in the array obj. The second form constructs the tree from the elements of vector v. In the third form, the tree whose root node is specified by tn specifies the tree. Although JTree is packaged in javax.swing, its support classes and interfaces are packaged in javax.swing.tree. This is because the number of classes and interfaces needed to support JTree is quite large. 36

JTree relies on two models: TreeModel and TreeSelectionModel. A JTree generates a variety of events, but three relate specifically to trees: TreeExpansionEvent, TreeSelectionEvent,and TreeModelEvent. TreeExpansionEvent events occur when a node is expanded or collapsed. A TreeSelectionEvent is generated when the user selects or deselects a node within the tree. A TreeModelEvent is fired when the data or structure of the tree changes. The listeners for these events are TreeExpansionListener, TreeSelectionListener, and TreeModelListener, respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.The event handled by the sample program shown in this section is TreeSelectionEvent. To listen for this event, implement TreeSelectionListener. It defines only one method, called valueChanged( ), which receives the TreeSelectionEvent object. You can obtain the path to the selected object by calling getPath( ), shown here, on the event object: TreePath getPath( ) It returns a TreePath object that describes the path to the changed node. The Tree Path class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node.The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here: DefaultMutableTreeNode(Object obj) Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children.To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here: void add(MutableTreeNode child) Here, child is a mutable tree node that is to be added as a child to the current node.JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport. Here are the steps to follow to use a tree: 37

1. Create an instance of JTree. 2. Create a JScrollPane and specify the tree as the object to be scrolled. 3. Add the tree to the scroll pane. 4. Add the scroll pane to the content pane. The following example illustrates how to create a tree and handle selections. The program creates a DefaultMutableTreeNode instance labeled "Options". This is the top node of the tree hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll pane is then added to the content pane. Next, a label is created and added to the content pane. The tree selection is displayed

in this label. To receive selection events from the tree, a

TreeSelectionListener is registered for the tree. Inside the valueChanged( ) method, the path to the current selection is obtained and displayed. // Demonstrate JTree. import java.awt.*; import javax.swing.event.*; import javax.swing.*; import javax.swing.tree.*; /* */ public class JTreeDemo extends JApplet { JTree tree; JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { 38

makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Create top node of tree. DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "A". DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1);rt III DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); // Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3); // Create the tree. tree = new JTree(top); // Add the tree to a scroll pane. JScrollPane jsp = new JScrollPane(tree); // Add the scroll pane to the content pane. add(jsp); // Add the label to the content pane. jlab = new JLabel(); 39

add(jlab, BorderLayout.SOUTH); // Handle tree selection events. tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { jlab.setText("Selection is " + tse.getPath());}});}} Output from the tree example is shown here:

4.Write in detail about Tables. Ans:JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position.Depending on its configuration, it is also possible to select a row, column, or cell within the table, and to change the data within a cell. JTable is a sophisticated component that offers many more options and features than can be discussed here. (It is perhaps Swing’s most complicated component.) However, in its default configuration, JTable still offers substantial functionality that is easy to use—especially if you simply want to use the table to present data in a tabular format. The brief overview presented here will give you a general understanding of this powerful component. Like JTree, JTable has many classes and interfaces associated with it. These are packaged in javax.swing.table. At its core, JTable is conceptually simple. It is a component that consists of one or more columns of information. At the top of each column is a heading. In addition to describing the data in a 40

column, the heading also provides the mechanism by which the user can change the size of a column or change the location of a column within the table. JTable does not provide any scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a JScrollPane. JTable supplies several constructors. The one used here is JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.JTable relies on three models. The first is the table model, which is defined by the TableModel interface. This model defines those things related to displaying data in a two-dimensional format. The second is the table column model, which is represented by TableColumnModel. JTable is defined in terms of columns, and it is TableColumnModel that specifies the characteristics of a column. These two models are packaged in javax.swing.table. The third model determines how items are selected, and it is specified by the ListSelectionModel, which was described when JList was discussed. A JTable can generate several different events. The two most fundamental to a table’s operation are ListSelectionEvent and TableModelEvent. A ListSelectionEvent is generated when the user selects something in the table. By default, JTable allows you to select one or more complete rows, but you can change this behavior to allow one or more columns, or one or more individual cells to be selected. A TableModelEvent is fired when that table’s data changes in some way. Handling these events requires a bit more work than it does to handle the events generated by the previously described components and is beyond the scope of this book. However, if you simply want to use JTable to display data (as the following example does), then you don’t need to handle any events.Here are the steps required to set up a simple JTable that can be used to display data: 1. Create an instance of JTable. 2. Create a JScrollPane object, specifying the table as the object to scroll. 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane.Part III The following example illustrates how to create and use a simple table. A one-dimensional array of strings called colHeads is created for the column headings. A two-dimensional array of strings called data is created for the table cells. You can see that each element in the array is an array of three strings. These arrays are passed to the JTable constructor. The table is added to a scroll 41

pane, and then the scroll pane is added to the content pane. The table displays the data in the data array. The default table configuration also allows the contents of a cell to be edited. Changes affect the underlying array, which is data in this case. // Demonstrate JTable. import java.awt.*; import javax.swing.*; /* */ public class JTableDemo extends JApplet { public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Initialize column headings. String[] colHeads = { "Name", "Extension", "ID#" }; // Initialize data. Object[][] data = { { "Gail", "4567", "865" }, { "Ken", "7566", "555" }, { "Viviane", "5634", "587" }, { "Melanie", "7345", "922" }, { "Anne", "1237", "333" }, { "John", "5656", "314" }, 42

{ "Matt", "5672", "217" }, { "Claire", "6741", "444" }, { "Erwin", "9023", "519" }, { "Ellen", "1134", "532" }, { "Jennifer", "5689", "112" }, { "Ed", "9030", "133" }, { "Helen", "6751", "145" } }; // Create the table. JTable table = new JTable(data, colHeads); // Add the table to a scroll pane. JScrollPane jsp = new JScrollPane(table); // Add the scroll pane to the content pane. add(jsp);}} Output from this example is shown here:

5. Explain about JComboBox Ans: A useful variation on the push button is called a toggle button. A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its two states.Toggle buttons are objects

43

of the JToggleButton class.JToggleButton implements AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also represent two-state controls.Thus, JToggleButton defines the basic functionality of all two-state components. JToggleButton defines several constructors. The one used by the example in this section is shown here: JToggleButton(String str) To handle item events, you must implement the ItemListener interface. Each time an item event is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a reference to the JToggleButton instance that generated the event. It is shown here: Object getItem( ) A reference to the button is returned. You will need to cast this reference to JToggleButton. The easiest way to determine a toggle button’s state is by calling the isSelected( ) method (inherited from AbstractButton) on the button that generated the event. It is shown here: boolean isSelected( ) It returns true if the button is selected and false otherwise. Here is an example that uses a toggle button. Notice how the item listener works. It simply calls isSelected( ) to determine the button’s state. // Demonstrate JToggleButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jtbn; public void init() { try { 44

SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout());Part III // Create a label. jlab = new JLabel("Button is off."); // Make a toggle button. jtbn = new JToggleButton("On/Off"); // Add an item listener for the toggle button. jtbn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if(jtbn.isSelected()) jlab.setText("Button is on."); else jlab.setText("Button is off.");}); // Add the toggle button and label to the content pane. add(jtbn); add(jlab);}} The output from the toggle button example is shown here

45

46

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / II

Academic year: 2015-16

SUB:OOPS THROUGH JAVA Tutorial Sheet: UNIT V-2 SWING Short answer questions 1. Explain the steps ivolved In Jtextfield 2. Write a java program to illustrate Jtextfield 3. Explain about JLabel and constructor of JLable 4. Explain about Jbutton and constructor of jbutton 5. Write a java program using four push buttons and a label. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the label. 6. Explain about JCheckBox and constructors in it? 7. Write a java program to illustrate JCheckBox 8. Explain about JToggleButton and constructors in it 9. Write a java program to illustrate JtoggleButton 10. Explain about radio buttons and constructors in it 11. Write a java program to illustrate Radio Buttons

Descriptive questions/programs/experiments 1.Explain about JComboBox 2.Write in detail about Trees 3.Write in detail about Tables. 4. Explain about Jscrollpane 5.Explain about Jtabbedpane Tutor

Faculty

HOD 17

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / I

Academic year: 2015-16

Tutorial Sheet:V-2 Question & Answers SHORT ANSWER QUESTIONS 1.Explain the steps ivolved In Jtextfield Ans:JTextField is the simplest Swing text component. It is also probably its most widely used text component. JTextField allows you to edit one line of text. It is derived from jextComponent, which provides the basic functionality common to Swing text components. JTextField uses the Document interface for its model. Three of JTextField’s constructors are shown here: JTextField(int cols) JTextField(String str, int cols) JTextField(String str) Here, str is the string to be initially presented, and cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string. JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the user presses enter. A CaretEvent is fired each time the caret (i.e., the cursor) changes position. (CaretEvent is packaged in javax.swing.event.) Other events are also possible. In many cases, your program will not need to handle these events. Instead,you will simply obtain the string currently in the text field when it is needed. To obtain the text currently in the text field, call getText( ). 2. Write a java program to illustrate Jtextfield Ans:// Demonstrate JTextField. import java.awt.*; import java.awt.event.*; 18

import javax.swing.*; /* */ public class JTextFieldDemo extends JApplet { JTextField jtf; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add text field to content pane. jtf = new JTextField(15); add(jtf); jtf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Show text when user presses ENTER. showStatus(jtf.getText());}});}}

19

3.Explin about JLabel and constructor of JLable Ans:JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to display text and/or an icon. It is a passive component in that it does not respond to user input. JLabel defines several constructors. Here are three of them: JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the SwingConstants interface, along with several others used by the Swing classes. 4.Explain about Jbutton and constructor of jbutton The JButton class provides the functionality of a push button. You have already seen a simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be associated with the push button. Three of its constructors are shown here: JButton(Icon icon) JButton(String str) JButton(String str, Icon icon) Here, str and icon are the string and icon used for the button.When the button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( ) method of the registered ActionListener, you can obtain the action command string associated with the button. By default, this is the string displayed.inside the button. However, you can set the action command by calling setActionCommand( ) on the button. You can obtain the action command by calling getActionCommand( ) on the event object. It is declared like this: String getActionCommand( ) The action command identifies the button. Thus, when using two or more buttons within the same application, the action command gives you an easy way to determine which button was pressed. 20

5.Write a java program using four push buttons and a label. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the label. Ans: // Demonstrate an icon-based JButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JButtonDemo extends JApplet implements ActionListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add buttons to content pane. ImageIcon france = new ImageIcon("france.gif"); JButton jb = new JButton(france); jb.setActionCommand("France"); jb.addActionListener(this); 21

add(jb); ImageIcon germany = new ImageIcon("germany.gif"); jb = new JButton(germany); jb.setActionCommand("Germany"); jb.addActionListener(this); add(jb); ImageIcon italy = new ImageIcon("italy.gif"); jb = new JButton(italy); jb.setActionCommand("Italy"); jb.addActionListener(this); add(jb);Part III ImageIcon japan = new ImageIcon("japan.gif"); jb = new JButton(japan); jb.setActionCommand("Japan"); jb.addActionListener(this); add(jb); // Create and add the label to content pane. jlab = new JLabel("Choose a Flag"); add(jlab);} // Handle button events. public void actionPerformed(ActionEvent ae) { jlab.setText("You selected " + ae.getActionCommand());}} Output from the button example is shown here:.

22

6.Explain about JCheckBox and constructors in it? Ans: The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines several constructors. The one used here is JCheckBox(String str) It creates a check box that has the text specified by str as a label. Other constructors let you specify the initial selection state of the button and specify an icon.When the user selects or deselects a check box, an ItemEvent is generated. You can obtain a reference to the JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged(

23

) method defined by ItemListener. The easiest way to determine the selected state of a check box is to call isSelected( ) on the JCheckBox instance. 7.Write a java program to illustrate JCheckBox // Demonstrate JCheckbox. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JCheckBoxDemo extends JApplet implements ItemListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Add check boxes to the content pane. JCheckBox cb = new JCheckBox("C"); cb.addItemListener(this); add(cb); cb = new JCheckBox("C++"); 24

cb.addItemListener(this); add(cb); cb = new JCheckBox("Java"); cb.addItemListener(this); add(cb); cb = new JCheckBox("Perl"); cb.addItemListener(this); add(cb); // Create the label and add it to the content pane. add(jlab);} // Handle item events for the check boxes. public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); if(cb.isSelected()) jlab.setText(cb.getText() + " is selected"); else jlab.setText(cb.getText() + " is cleared");}} Output from this example is shown here:

8.Explain about JToggleButton and constructors in it Ans:A useful variation on the push button is called a toggle button. A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its two states. Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also 25

represent two-state controls. Thus, JToggleButton defines the basic functionality of all two-state components. JToggleButton defines several constructors. The one used by the example in this section is shown here: JToggleButton(String str) This creates a toggle button that contains the text passed in str. By default, the button is in the off position. Other constructors enable you to create toggle buttons that contain images, or images and text. JToggleButton

uses

a

model

defined

by

a

nested

class

called

JToggleButton.ToggleButtonModel. Normally, you won’t need to interact directly with the model to use a standard toggle button. Like JButton, JToggleButton generates an action event each time it is pressed. Unlike JButton, however, JToggleButton also generates an item event. This event is used by those components that support the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is deselected. To handle item events, you must implement the ItemListener interface. each time an item event is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a reference to the JToggleButton instance that generated the event. It is shown here: Object getItem( ) A reference to the button is returned. You will need to cast this reference to JToggleButton. The easiest way to determine a toggle button’s state is by calling the isSelected( ) method (inherited from AbstractButton) on the button that generated the event. It is shown here: boolean isSelected( ) It returns true if the button is selected and false otherwise. 9.Write a java program to illustrate JtoggleButton // Demonstrate JToggleButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* 26

*/ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jtbn; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); // Create a label. jlab = new JLabel("Button is off."); // Make a toggle button. jtbn = new JToggleButton("On/Off"); // Add an item listener for the toggle button. jtbn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if(jtbn.isSelected()) jlab.setText("Button is on."); else jlab.setText("Button is off.");} }); // Add the toggle button and label to the content pane. 27

add(jtbn); add(jlab);}} The output from the toggle button example is shown here

. 10.Explain about radio buttons and constructors in it Ans: Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. They are supported by the JRadioButton class, which extends JToggleButton. JRadioButton provides several constructors. The one used in the example is shown here: JRadioButton(String str) Here, str is the label for the button. Other constructors let you specify the initial selection state of the button and specify an icon.In order for their mutually exclusive nature to be activated, radio buttons must be configured into a group. Only one of the buttons in the group can be selected at any time.For example, if a user presses a radio button that is in a group, any previously selected button in that group is automatically deselected. A button group is created by the ButtonGroup class. Its default constructor is invoked for this purpose. Elements are then added to the button group via the following method: void add(AbstractButton ab) Here, ab is a reference to the button to be added to the group.A JRadioButton generates action events, item events, and change events each time the button selection changes. Most often, it is the action event that is handled, which means that you will normally implement the ActionListener interface. Recall that the only method defined by ActionListener is actionPerformed( ). Inside this method, you can use a number of different ways to determine which button was selected. First, you can check its action command by calling 28

getActionCommand( ). By default, the action command is the same as the button label, but you can set the action command to something else by calling setActionCommand( ) on the radio button. Second, you can call getSource( ) on the ActionEvent object and check that reference against the buttons. Finally, you can simply check each radio button to find out which one is currently selected by calling isSelected( ) on each button. Remember, each time an action event occurs, it means that the button being selected has changed and that one and only one button will be selected. 11.Write a java program to illustrate Radio Buttons Ans: // Demonstrate JRadioButton import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JRadioButtonDemo extends JApplet implements ActionListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout()); 29

// Create radio buttons and add them to content pane. JRadioButton b1 = new JRadioButton("A"); b1.addActionListener(this); add(b1); JRadioButton b2 = new JRadioButton("B"); b2.addActionListener(this); add(b2); JRadioButton b3 = new JRadioButton("C"); b3.addActionListener(this); add(b3); // Define a button group. ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); bg.add(b3); // Create a label and add it to the content pane. jlab = new JLabel("Select One"); add(jlab);} // Handle button selection. public void actionPerformed(ActionEvent ae) { jlab.setText("You selected " + ae.getActionCommand());}} Output from the radio button example is shown here:

30

LONG ANSWER QUESTIONS 1.Explain about JTbbedPane? Ans:JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with tabs. Selecting a tab causes the component associated with that tab to come to the forefront. Tabbed panes are very common in the modern GUI, and you have no doubt used them many times. Given the complex nature of a tabbed pane, they are surprisingly easy to create and use. JTabbedPane defines three constructors. We will use its default constructor, which creates an empty control with the tabs positioned across the top of the pane. The other two constructors let you specify the location of the tabs, which can be along any of the four sides. JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling addTab( ). Here is one of its forms: void addTab(String name, Component comp) Here, name is the name for the tab, and comp is the component that should be added to the tab. Often, the component added to a tab is a JPanel that contains a group of related components.This technique allows a tab to hold a set of components. The general procedure to use a tabbed pane is outlined here: 1. Create an instance of JTabbedPane. 2. Add each tab by calling addTab( ). 3. Add the tabbed pane to the content pane. The following example illustrates a tabbed pane. The first tab is titled "Cities" and contains four buttons. Each button displays the name of a city. The second tab is titled "Colors" and contains three check boxes. Each check box displays the name of a color. The third tab is titled "Flavors" and contains one combo box. This enables the user to select one of three flavors. // Demonstrate JTabbedPane. import javax.swing.*; /* */ public class JTabbedPaneDemo extends JApplet { 31

public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); add(jtp);}} // Make the panels that will be added to the tabbed pane. class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4);}}t III class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); 32

add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3);}} class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox<String> jcb = new JComboBox<String>(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb);}} Output from the tabbed pane example is shown in the following three illustrations:

33

2.Explain about JScrollPane? Ans:JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can be either an individual component, such as a table, or a group of components contained within another lightweight container, such as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars. The viewable area of a scroll pane is called the viewport. It is a window in which the component being scrolled is displayed. Thus, the viewport displays the visible portion of the component being scrolled. The scroll bars scroll the component through the viewport.In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as needed.For example, if the component is taller than the viewport, a vertical scroll bar is added. If the component will completely fit within the viewport, the scroll bars are removed.JScrollPane defines several constructors. The one used in this chapter is shown here: JScrollPane(Component comp) The component to be scrolled is specified by comp. Scroll bars are automatically displayed when the content of the pane exceeds the dimensions of the viewport.Here are the steps to follow to use a scroll pane: 1. Create the component to be scrolled. 2. Create an instance of JScrollPane, passing to it the object to scroll. 3. Add the scroll pane to the content pane. The following example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons are added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the 34

scroll pane is added to the content pane. Because the panel is larger than the viewport, vertical and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the buttons into view. // Demonstrate JScrollPane. import java.awt.*; import javax.swing.*; /* */ public class JScrollPaneDemo extends JApplet { public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() {art III // Add 400 buttons to a panel. JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b;}} // Create the scroll pane. JScrollPane jsp = new JScrollPane(jp); 35

// Add the scroll pane to the content pane. // Because the default border layout is used, // the scroll pane will be added to the center. add(jsp, BorderLayout.CENTER);}} Output from the scroll pane example is shown here:

3. Write in detail about Trees Ans: A tree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the tree class. A sampling of its constructors is shown here: JTree(Object obj [ ]) JTree(Vector v) JTree(TreeNode tn)Part III In the first form, the tree is constructed from the elements in the array obj. The second form constructs the tree from the elements of vector v. In the third form, the tree whose root node is specified by tn specifies the tree. Although JTree is packaged in javax.swing, its support classes and interfaces are packaged in javax.swing.tree. This is because the number of classes and interfaces needed to support JTree is quite large. 36

JTree relies on two models: TreeModel and TreeSelectionModel. A JTree generates a variety of events, but three relate specifically to trees: TreeExpansionEvent, TreeSelectionEvent,and TreeModelEvent. TreeExpansionEvent events occur when a node is expanded or collapsed. A TreeSelectionEvent is generated when the user selects or deselects a node within the tree. A TreeModelEvent is fired when the data or structure of the tree changes. The listeners for these events are TreeExpansionListener, TreeSelectionListener, and TreeModelListener, respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.The event handled by the sample program shown in this section is TreeSelectionEvent. To listen for this event, implement TreeSelectionListener. It defines only one method, called valueChanged( ), which receives the TreeSelectionEvent object. You can obtain the path to the selected object by calling getPath( ), shown here, on the event object: TreePath getPath( ) It returns a TreePath object that describes the path to the changed node. The Tree Path class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node.The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here: DefaultMutableTreeNode(Object obj) Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children.To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here: void add(MutableTreeNode child) Here, child is a mutable tree node that is to be added as a child to the current node.JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport. Here are the steps to follow to use a tree: 37

1. Create an instance of JTree. 2. Create a JScrollPane and specify the tree as the object to be scrolled. 3. Add the tree to the scroll pane. 4. Add the scroll pane to the content pane. The following example illustrates how to create a tree and handle selections. The program creates a DefaultMutableTreeNode instance labeled "Options". This is the top node of the tree hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll pane is then added to the content pane. Next, a label is created and added to the content pane. The tree selection is displayed

in this label. To receive selection events from the tree, a

TreeSelectionListener is registered for the tree. Inside the valueChanged( ) method, the path to the current selection is obtained and displayed. // Demonstrate JTree. import java.awt.*; import javax.swing.event.*; import javax.swing.*; import javax.swing.tree.*; /* */ public class JTreeDemo extends JApplet { JTree tree; JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { 38

makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Create top node of tree. DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "A". DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1);rt III DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); // Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3); // Create the tree. tree = new JTree(top); // Add the tree to a scroll pane. JScrollPane jsp = new JScrollPane(tree); // Add the scroll pane to the content pane. add(jsp); // Add the label to the content pane. jlab = new JLabel(); 39

add(jlab, BorderLayout.SOUTH); // Handle tree selection events. tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { jlab.setText("Selection is " + tse.getPath());}});}} Output from the tree example is shown here:

4.Write in detail about Tables. Ans:JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position.Depending on its configuration, it is also possible to select a row, column, or cell within the table, and to change the data within a cell. JTable is a sophisticated component that offers many more options and features than can be discussed here. (It is perhaps Swing’s most complicated component.) However, in its default configuration, JTable still offers substantial functionality that is easy to use—especially if you simply want to use the table to present data in a tabular format. The brief overview presented here will give you a general understanding of this powerful component. Like JTree, JTable has many classes and interfaces associated with it. These are packaged in javax.swing.table. At its core, JTable is conceptually simple. It is a component that consists of one or more columns of information. At the top of each column is a heading. In addition to describing the data in a 40

column, the heading also provides the mechanism by which the user can change the size of a column or change the location of a column within the table. JTable does not provide any scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a JScrollPane. JTable supplies several constructors. The one used here is JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.JTable relies on three models. The first is the table model, which is defined by the TableModel interface. This model defines those things related to displaying data in a two-dimensional format. The second is the table column model, which is represented by TableColumnModel. JTable is defined in terms of columns, and it is TableColumnModel that specifies the characteristics of a column. These two models are packaged in javax.swing.table. The third model determines how items are selected, and it is specified by the ListSelectionModel, which was described when JList was discussed. A JTable can generate several different events. The two most fundamental to a table’s operation are ListSelectionEvent and TableModelEvent. A ListSelectionEvent is generated when the user selects something in the table. By default, JTable allows you to select one or more complete rows, but you can change this behavior to allow one or more columns, or one or more individual cells to be selected. A TableModelEvent is fired when that table’s data changes in some way. Handling these events requires a bit more work than it does to handle the events generated by the previously described components and is beyond the scope of this book. However, if you simply want to use JTable to display data (as the following example does), then you don’t need to handle any events.Here are the steps required to set up a simple JTable that can be used to display data: 1. Create an instance of JTable. 2. Create a JScrollPane object, specifying the table as the object to scroll. 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane.Part III The following example illustrates how to create and use a simple table. A one-dimensional array of strings called colHeads is created for the column headings. A two-dimensional array of strings called data is created for the table cells. You can see that each element in the array is an array of three strings. These arrays are passed to the JTable constructor. The table is added to a scroll 41

pane, and then the scroll pane is added to the content pane. The table displays the data in the data array. The default table configuration also allows the contents of a cell to be edited. Changes affect the underlying array, which is data in this case. // Demonstrate JTable. import java.awt.*; import javax.swing.*; /* */ public class JTableDemo extends JApplet { public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Initialize column headings. String[] colHeads = { "Name", "Extension", "ID#" }; // Initialize data. Object[][] data = { { "Gail", "4567", "865" }, { "Ken", "7566", "555" }, { "Viviane", "5634", "587" }, { "Melanie", "7345", "922" }, { "Anne", "1237", "333" }, { "John", "5656", "314" }, 42

{ "Matt", "5672", "217" }, { "Claire", "6741", "444" }, { "Erwin", "9023", "519" }, { "Ellen", "1134", "532" }, { "Jennifer", "5689", "112" }, { "Ed", "9030", "133" }, { "Helen", "6751", "145" } }; // Create the table. JTable table = new JTable(data, colHeads); // Add the table to a scroll pane. JScrollPane jsp = new JScrollPane(table); // Add the scroll pane to the content pane. add(jsp);}} Output from this example is shown here:

5. Explain about JComboBox Ans: A useful variation on the push button is called a toggle button. A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its two states.Toggle buttons are objects

43

of the JToggleButton class.JToggleButton implements AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also represent two-state controls.Thus, JToggleButton defines the basic functionality of all two-state components. JToggleButton defines several constructors. The one used by the example in this section is shown here: JToggleButton(String str) To handle item events, you must implement the ItemListener interface. Each time an item event is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a reference to the JToggleButton instance that generated the event. It is shown here: Object getItem( ) A reference to the button is returned. You will need to cast this reference to JToggleButton. The easiest way to determine a toggle button’s state is by calling the isSelected( ) method (inherited from AbstractButton) on the button that generated the event. It is shown here: boolean isSelected( ) It returns true if the button is selected and false otherwise. Here is an example that uses a toggle button. Notice how the item listener works. It simply calls isSelected( ) to determine the button’s state. // Demonstrate JToggleButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jtbn; public void init() { try { 44

SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI();}}); } catch (Exception exc) { System.out.println("Can't create because of " + exc);}} private void makeGUI() { // Change to flow layout. setLayout(new FlowLayout());Part III // Create a label. jlab = new JLabel("Button is off."); // Make a toggle button. jtbn = new JToggleButton("On/Off"); // Add an item listener for the toggle button. jtbn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if(jtbn.isSelected()) jlab.setText("Button is on."); else jlab.setText("Button is off.");}); // Add the toggle button and label to the content pane. add(jtbn); add(jlab);}} The output from the toggle button example is shown here

45

46

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / I I

Academic year: 2015-16

SUB: OOP THROUGH JAVA Tutorial Sheet: UNIT I-I INTRODUCTION Short answer questions 1. Explain about history of java? 2. What is JVM?What it does? 3. Describe types of Java Applications? 4. List out java buzzwords? 5. Define variables in java? 6. Types of variables in java? 7. Define Array in java with Syntax? 8. What are the operators in java? 9. Define Expressions? 10. What are the control statements in java? 11. Illustrate Type casting with example? 12. Illustrate Type conversion with example? 13. Explain Scope and lifetime of variables briefly? 14. What is native code and byte code? 15. What are the differences between c++,java? Descriptive questions/programs/experiments 1. Explain in detail about basic Oops concepts? 2. Define Array? And Explain bout types of Arrays with example? 3. Explain about Control statements in java with example? 4. Explain about operators in java? 5. Explain about Data types and variables? Tutor

Faculty

HOD

SHORT ANSWER QUESTIONS 1. Explain about history of java? ANS:Java history is interesting to know. The history of java starts from Green Team. Java team members (also known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc. For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape. Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major point that describes the history of java. 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team. 2) Originally designed for small, embedded systems in electronic appliances like set-top boxes. 3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt. 4) After that, it was called Oak and was developed as a part of the Green project. 2. What is JVM? What it does? ANS:JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed. JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent). 1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies. 2. An implementation Its implementation is known as JRE (Java Runtime Environment). 3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created. The JVM performs following operation:  Loads code

 Verifies code  Executes code  Provides runtime environment JVM provides definitions for the:  Memory area  Class file format  Register set  Garbage-collected heap  Fatal error reporting etc. 3. Describe types of Java Applications ANS:There are mainly 4 types of applications that can be created using java programming: 1) Standalone Application It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications. 2) Web Application An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java. 3) Enterprise Application An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications. 4) Mobile Application An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications. 4. List out java buzzwords? ANS:Following are the features or buzzwords of Java language which made it popular: 1.Simple 2.Secure 3.Portable

4.Object-Oriented 5.Robust 6.Multithreaded 7.Architecture 8.Interpreted 9.HighPerformance 10.Distributed 11.Dynamic 5. Define variables in java? ANS:Data type variable [ = value][, variable [= value] ...] ; Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list. Following are valid examples of variable declaration and initialization in Java: 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 = 3.14159;

// declares and assigns a value of PI.

char a = 'a';

// the char variable a iis initialized with value 'a'

6. Types of variables in java? ANS:Three types of variables injava 1. Local Variables 2. Instance Variables (Non-static variables) 3. Class Variables (Static Variables) Declaration of variable:

int data=50;//Here data is variable

Local variables: Variables defined inside methods, constructors or blocks are called local variables. Thevariable will be declared and initialized within the method and the variable will be destroyed when the methodhas completed. Instance variables: Instance variables are variables within a class but outside any method. These

variablesare instantiated when the class is loaded. Instance variables can be accessed from inside any method,constructor or blocks of that particular class. Class variables: Class variables are variables declared within a class, outside any method, with the static keyword. 7. Define Array in java with Syntax?

ANS: Array Normally, array is a collection of similar type of elements that have contiguous memory location. Java array is an object that contains the 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 indexes. 1. dataType[]arr;(or) 2. dataType[]arr;(or) 3. dataType arr[]; Example: int a[]=new int[5];//declarationandinstantiation  a[0]=10;//initialization  a[1]=20;  a[2]=70;  a[3]=40;  a[4]=50; Advantage 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. 8. What are the operators in java? ANS:Operator in java is a symbol that is used to perform operations. There are many types of operators in java such as unary operator, arithmetic operator, relational operator, shift operator,

bitwise operator, ternary operator and assignment operator. 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 • Logical Operators • Assignment Operators • Misc Operators 9. Describe operator precedence? ANS:Operators

Precedence

Postfix

expr++ expr--

Unary

++expr --expr +expr -expr ~ !

Multiplicative

*/%

Additive

+-

Shift

<< >> >>>

Relational

< > <= >= instanceof

Equality

== !=

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

logical AND

&&

logical OR

||

Ternary

?:

Assignment

= += -= *= /= %= &= ^= |= <<= >>= >>>=

10. Define Expressions?

ANS:Expressions: An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below: int cadence = 0; anArray[0] = 100; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if (value1 == value2) System.out.println("value1 == value2"); 11. What are the Control statements in java? ANS:A program executes from top to bottom except when we use control statements, we can control the order of execution of the program, based on logic and values. In Java, control statements can be divided into the following three categories:  Selection Statements  Iteration Statements  Jump Statements 12. Illustrate Type casting with example? ANS:Type Casting Assigning a value of one type to a variable of another type is known as Type Casting. Example : int x = 10; byte y = (byte)x; In Java, type casting is classified into two types,  Widening Casting(Implicit)

 Narrowing Casting(Explicitly done) Automatic Type casting take place when,  the two types are compatible  the target type is larger than the source type Widening Casting(Implicit) Example : public class Test { public static void main(String[] args) { int i = 100; long l = i; float f = l; System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); } } Output: Int value 100 Long value 100 Float value 100.0 Narrowing or Explicit type casting When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. Example: Public class Test { public static void main(String[] args) {

double d = 100.04; long l = (long)d; //explicit type casting required int i = (int)l; //explicit type casting required System.out.println("Double value "+d); System.out.println("Long value "+l); System.out.println("Int value "+i); }} Output: Double value 100.04 Long value 100 Int value 100 13. Illustrate Type conversion with example? ANS: Java is much stronger than C++ in the type conversions that are allowed. There are two kinds ofconversion:implicitandexplicit. Implicitconversions: An implicit conversion means that a value of one type is changed to a value of another type without any special directive from the programmer. A char can be implicitly converted to an int, a long, a float, or a double. For example, the following will compile without error: char c = 'a'; int k = c; long x = c; float y = c; double d = c; For the other (numeric) primitive types, the basic rule is that implicit conversions can be done from one type to another if the range of values of the first type is a subset of the range of values of the second type. For example, a byte can be converted to a short, int, long or float; a short can be converted to an int, long, float, or double, etc. Explicit conversions: Explicit conversions are done via casting. The name of the type to which you want a value converted is given, in parentheses, in front of the value. For example, the following code casts a value of type double to a value of type int, and a value of type double to a value of type short: double d = 5.6;

int k = (int)d; short s = (short)(d * 2.0); Casting can be used to convert among any of the primitive types except boolean. Please note that casting can lose information; for example, floating-point values are truncated when they are cast to integers 14. Explain Scope and lifetime of variables briefly? ANS:The scope of a variable defines the section of the code in which the variable is visible. As a

general rule, variables that are defined within a block are not accessible outside that block. The lifetime of a variable refers to how long the variable exists before it is destroyed. Destroying variables refers to reallocating the memory that was allotted to the variables when declaring it. We have written a few classes till now. You might have observed that not all variables are the same. The ones declared in the body of a method were different from those that were declared in the class itself. Example: public class Main { public static void main(String args[]) { int x; // known within main x = 10; if (x == 10) { // start new scope int y = 20; // y is known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y + 2; } System.out.println("x is " + x); } } The output: x and y: 10 20 x is 22

15. What is native code and byte code? ANS: The native code is code that after you compile it, the compiled code runs on a

specific hardware platform. Byte code is the compiled format for Java programs. Once a Java program has been converted to byte code, it can be transferred across a network and executed by Java Virtual Machine (JVM). Byte code files generally have a .class extension. 16. What are the differences between c++,java? ANS:Java

C++

Java does not support pointers, templates, unions, operator C++ supports structures, unions, templates, operator overloading, overloading, structures etc. pointers and pointer arithmetic.

Java support automatic garbage collection. It does not support destructors as C++ does.

Java does not support conditional compilation and inclusion.

Java has built in support for threads. In Java, there is a Thread class that you inherit to create a new thread and override the run() method.

C++ support destructors, which is automatically invoked when the object is destroyed. Conditional

inclusion

(#ifdef

#ifndef type) is one of the main features of C++. C++ has no built in support for threads. C++ relies on non-standard third-party

libraries

for

thread

support. C++ supports default arguments.

Java does not support default arguments. There is no scope resolution operator (::) in Java. The method definitions must always occur within a class, so there is no need for scope resolution there either.

C++ has scope resolution operator (::) which is used to to define a method outside a class and to access a global variable within from the scope where a local variable also exists with the same name.

There is no goto statement in Java. The keywords const and goto are reserved, even though they are not used.

C++ has goto statement. However, it is not considered good practice to use of goto statement. C++

does

support

multiple

Java doesn't provide multiple inheritance, at least not in the inheritance. The keyword virtual is same sense that C++ does.

used to resolve ambiguities during multiple inheritance if there is any.

DESCRIPTIVE QUESTIONS 1. Define Array? And Explain bout types of Arrays with example? ANS:Normally, array is a collection of similar type of elements that have contiguous memory location. Java array is an object the 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.

Advantage 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.

Types of Array in java There are two types of array. 4. Single Dimensional Array 5. Multidimensional Array Single Dimensional Array in java Syntax to Declare an Array in java  DataType[] arr; (or)  dataType[]arr;(or)  dataTypearr[]; 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{  publicstatic 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
70 40 50 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
}}

Output: 3 4

5

Passing Array to method in java We can pass the java array to method so that we can reuse the same logic on any array. Let's see the simple example to get minimum number of an array using method.  class Testarray2{  static void min(int arr[]){  int min=arr[0];  for(int i=1;i<arr.length;i++)  if(min rel="nofollow">arr[i]) 

min=arr[i];

 System.out.println(min);  }  public static void main(String args[]){  int a[]={33,3,4,5};  min(a);//passing array to method  }}

Output:3 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; 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. 1. class Testarray3{ 2. public static void main(String args[]){ 3. //declaring and initializing 2D array 4. int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 5. //printing 2D array 6. for(int i=0;i<3;i++){

7. for(int j=0;j<3;j++){ 8.

System.out.print(arr[i][j]+" ");

9. } 10.

System.out.println();

11.

}

12.

}}

Output:1 2 3 245 445 Copying a java array We can copy an array to another by the arraycopy method of System class. Syntax of arraycopy method 1. public static void arraycopy( 2. sObject src, int srcPos,Object dest, int destPos, int length ) Example of arraycopy method 1. class TestArrayCopyDemo { 2.

public static void main(String[] args) {

3.

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',

4.

'i', 'n', 'a', 't', 'e', 'd' };

5.

char[] copyTo = new char[7];

6.

System.arraycopy(copyFrom, 2, copyTo, 0, 7);

7.

System.out.println(new String(copyTo));

8.

}

9. } Output:caffein 2. Explain in detail about basic Oops concepts Ans: Object Oriented programming is a programming style that is associated with the concept of objects, having data fields and related member functions. Objects are instances of classes and are used to interact amongst each other to create applications. Instance means, the object of class on which we are currently working. C++ can be

said to be as C language with classes. In C++ everything revolves around object of class, which have their methods & data members. C++ can be said to be as C language with classes. In C++ everything revolves around object of class, which has their methods & data members. For Example: We consider human body as a class, we do have multiple objects of this class, with variable as color, hair etc. and methods as walking, speaking etc. Now, let us discuss some of the main features of object oriented programming which you will be using in C++.



Objects



Classes



Abstraction



Encapsulation



Inheritance



Overloading



Exception Handling

Objects: Objects are the basic unit of OOP. They are instances of class, which have data members and use various member functions to perform tasks. Class: It is similar to structures in C language. Class can also be defined as user defined data type but it also contains functions in it. So, class is basically a blueprint for object. It declare & defines what data variables the object will have and what operations can be performed on the class's object. Abstraction: Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes provide methods to the outside world to access & use the data variables, but the variables are hidden from direct access Encapsulation: It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class. Inheritance: Inheritance is a way to reuse once written code again and again. The class which is inherited is called base calls & the class which inherits is called derived class. So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable.

Polymorphism: Polymorphion makes the code more readable. It is a features, which lets is create functions with same name but different arguments, which will perform differently. That is function with same name, functioning in different Overloading: Overloading is a part of polymorphion. Where a function or operator is made & defined many times, to perform different functions they are said to be overloaded. Exception Handling: Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime. 3. Explain about Control statements in java? ANS:A program executes from top to bottom except when we use control statements, we can

control the order of execution of the program, based on logic and values. In Java, control statements can be divided into the following three categories: 

Selection Statements



Iteration Statements



Jump Statements

Selection Statements Selection statements allow you to control the flow of program execution on the basis of the outcome of an expression or state of a variable known during runtime. Selection statements can be divided into the following categories: 

The if and if-else statements



The if-else statements



The if-else-if statements



The switch statements

The if statements The first contained statement (that can be a block) of an if statement only executes when the specified condition is true. If the condition is false and there is not else keyword then the first contained statement will be skipped and execution continues with the rest of the program. The condition is an expression that returns a boolean value.

Example 1. package com.deepak.main; 2. import java.util.Scanner; 3. public class IfDemo 4. { 5.

public static void main(String[] args) {

6.

int age;

7.

Scanner inputDevice = new Scanner(System.in);

8.

System.out.print("Please enter Age: ");

9.

age = inputDevice.nextInt();

10.

if(age > 18)

11. 12.

System.out.println("above 18 "); }

13. } Output: Please enter age:19 Above 18 The if-else statements In if-else statements, if the specified condition in the if statement is false, then the statemet after the else keyword (that can be a block) will execute. Example 1. package com.deepak.main; 2. import java.util.Scanner; 3. public class IfElseDemo 4. { 5.

public static void main( String[] args )

6.

{

7.

int age;

8.

Scanner inputDevice = new Scanner( System.in );

9.

System.out.print( "Please enter Age: " );

10.

age = inputDevice.nextInt();

11.

if ( age >= 18 )

12.

System.out.println( "above 18 " );

13.

else

14. 15.

System.out.println( "below 18" ); }

16. } Output Enter age:11 Below 18 The if-else-if statements This statement following the else keyword can be another if or if-else statement. That would looks like this: if(condition) statements; else if (condition) statements; else if(condition) statement; else statements; Whenever the condition is true, the associated statement will be executed and the remaining conditions will be bypassed. If none of the conditions are true then the else block will execute. Example 1. package com.deepak.main; 2. import java.util.Scanner;

3. public class IfElseIfDemo 4. { 5.

public static void main( String[] args )

6.

{

7.

int age;

8.

Scanner inputDevice = new Scanner( System.in );

9.

System.out.print( "Please enter Age: " );

10.

age = inputDevice.nextInt();

11.

if ( age >= 18 && age <=35 )

12.

System.out.println( "between 18-35 " );

13.

else if(age >35 && age <=60)

14.

System.out.println("between 36-60");

15.

else

16. 17.

System.out.println( "not matched" ); }

18. } Output Enter age:55 Between 36-60 The Switch Statements The switch statement is a multi-way branch statement. The switch statement of Java is another selection statement that defines multiple paths of execution of a program. It provides a better alternative than a large series of if-else-if statements. Example 1. package com.deepak.main; 2. import java.util.Scanner; 3. public class SwitchDemo

4. { 5.

public static void main( String[] args )

6.

{

7.

int age;

8.

Scanner inputDevice = new Scanner( System.in );

9.

System.out.print( "Please enter Age: " );

10.

age = inputDevice.nextInt();

11.

switch ( age )

12.

{

13.

case 18:

14.

System.out.println( "age 18" );

15.

break;

16.

case 19:

17.

System.out.println( "age 19" );

18.

break;

19.

default:

20.

System.out.println( "not matched" );

21.

break;

22. 23.

} }

24. } Output Please enter age:19 Age:19 An expression must be of a type of byte, short, int or char. Each of the values specified in the case statement must be of a type compatible with the expression. Duplicate case values are not allowed. The break statement is used inside the switch to terminate a statement sequence. The

break statement is optional in the switch statement. Iteration Statements Repeating the same code fragment several times until a specified condition is satisfied is called iteration. Iteration statements execute the same set of instructions until a termination condition is met. Java provides the following loop for iteration statements: 

The while loop



The for loop



The do-while loop



The for each loop

The while loop It continually executes a statement (that is usually be a block) while a condition is true. The condition must return a boolean value. Example 1. package com.deepak.main; 2. public class WhileDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

int i = 0;

7.

while ( i < 5 )

8.

{

9.

System.out.println( "Value :: " + i );

10.

i++;

11. 12. 13. }

} }

Output value : : 0 value : : 1 value : : 2 value : : 3 value : : 4 The do-while loop The only difference between a while and a do-while loop is that do-while evaluates its expression at the bottom of the loop instead of the top. The do-while loop executes at least one time then it will check the expression prior to the next iteration. Example 1. package com.deepak.main; 2. public class DoWhileDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

int i = 0;

7.

do

8.

{

9.

System.out.println( "value :: " + i );

10.

i++;

11.

}

12.

while ( i < 5);

13. 14. } Output value : : 0 value : : 1

}

value : : 2 value : : 3 value : : 4 The for loop A for loop executes a statement (that is usually a block) as long as the boolean condition evaluates to true. A for loop is a combination of the three elements initialization statement, boolean expression and increment or decrement statement. Syntax: for(;;){ } The initialization block executes first before the loop starts. It is used to initialize the loop variable. The condition statement evaluates every time prior to when the statement (that is usually be a block) executes, if the condition is true then only the statement (that is usually a block) will execute. The increment or decrement statement executes every time after the statement (that is usually a block). Example 1. package com.deepak.main; 2. public class WhileDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

int i = 0;

7.

while ( i < 5 )

8.

{

9.

System.out.println( "Value :: " + i );

10.

i++;

11. 12.

} }

13. } Output value : : 0 value : : 1 value : : 2 value : : 3 value : : 4 The For each loop This was introduced in Java 5. This loop is basically used to traverse the array or collection elements. Example 1. package com.deepak.main; 2. public class ForEachDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

int[] i =

7.

{ 1, 2, 3, 4, 5 };

8.

for ( int j : i )

9.

{

10.

System.out.println( "value :: " + j );

11. 12. 13. }

} }

Jump Statements Jump statements are used to unconditionally transfer the program control to another part of the program. Java provides the following jump statements: 

break statement



continue statement



return statement

Break Statement The break statement immediately quits the current iteration and goes to the first statement following the loop. Another form of break is used in the switch statement. The break statement has the following two forms: 

Labeled Break Statement



Unlabeled Break Statement

Unlabeled Break Statement: This is used to jump program control out of the specific loop on the specific condition. Example 1. package com.deepak.main; 2. public class UnLabeledBreakDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

for ( int var = 0; var < 5; var++ )

7.

{

8.

System.out.println( "Var is : " + var );

9.

if ( var == 3 )

10. 11.

break; }

12.

}

13. } Output var is : : 0 var is : : 1 var is : : 2 var is : : 3 Labeled Break Statement: This is used for when we want to jump the program control out of nested loops or multiple loops. Example 1. package com.deepak.main; 2. public class LabeledBreakDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

Outer: for ( int var1 = 0; var1 < 5; var1++ )

7.

{

8.

for ( int var2 = 1; var2 < 5; var2++ )

9.

{

10.

System.out.println( "var1:" + var1 + ", var2:" + var2 );

11.

if ( var1 == 3 )

12.

break Outer;

13.

}

14. 15. 16. }

} }

Continue Statement The continue statement is used when you want to continue running the loop with the next iteration and want to skip the rest of the statements of the body for the current iteration. The continue statement has the following two forms: 

Labeled Continue Statement



Unlabeled Continue Statement

Unlabeled Continue Statement: This statement skips the current iteration of the innermost for, while and do-while loop. Example 1. package com.deepak.main; 2. public class UnlabeledContinueDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

for ( int var1 = 0; var1 < 4; var1++ )

7.

{

8.

for ( int var2 = 0; var2 < 4; var2++ )

9.

{

10.

if ( var2 == 2 )

11.

continue;

12.

System.out.println( "var1:" + var1 + ", var2:" + var2 );

13.

}

14. 15. 16. }

} }

Labeled Continue Statement: This statement skips the current iteration of the loop with the specified label. Example 1. package com.deepak.main; 2. public class LabeledContinueDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

Outer: for ( int var1 = 0; var1 < 5; var1++ )

7.

{

8.

for ( int var2 = 0; var2 < 5; var2++ )

9.

{

10.

if ( var2 == 2 )

11.

continue Outer;

12.

System.out.println( "var1:" + var1 + ", var2:" + var2 );

13.

}

14. 15.

} }

16. } Return Statement The return statement is used to immediately quit the current method and return to the calling method. It is mandatory to use a return statement for non-void methods to return a value. Example 1. package com.deepak.main; 2. public class ReturnDemo 3. { 4.

public static void main( String[] args )

5.

{

6.

ReturnDemo returnDemo = new ReturnDemo();

7.

System.out.println( "No : " + returnDemo.returnCall() );

8.

}

9.

int returnCall()

10.

{

11.

return 5;

12.

}

13. } Output No:5 4. Explain about operators in java? ANS: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  Logical Operators  Assignment Operators  Misc Operators The Arithmetic Operators: 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: Show Examples SR.NO Operator and Example

+ ( Addition ) 1

Adds values on either side of the operator Example: A + B will give 30 - ( Subtraction )

2

Subtracts right hand operand from left hand operand Example: A - B will give -10 * ( Multiplication )

3

Multiplies values on either side of the operator Example: A * B will give 200 / (Division)

4

Divides left hand operand by right hand operand Example: B / A will give 2 % (Modulus)

5

Divides left hand operand by right hand operand and returns remainder Example: B % A will give 0 ++ (Increment)

6

Increases the value of operand by 1 Example: B++ gives 21 -- ( Decrement ) Decreases the value of operand by 1 Example: B-- gives 1

Relational operators: There are following relational operators supported by Java language Assume variable A holds 10 and variable B holds 20, then: Show Examples SR.NO Operator and Description 1

== (equal to)

Checks if the values of two operands are equal or not, if yes then condition becomes true. Example: (A == B) is not true. != (not equal to)

2

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. Example: (A != B) is true. > (greater than)

3

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Example: (A > B) is not true. < (less than)

4

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Example: (A < B) is true. >= (greater than or equal to)

5

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Example (A >= B) is not true. <= (less than or equal to)

6

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. example(A <= B) is true.

The Bitwise Operators: Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds 13 then: Show Examples SR.NO Operator and Description & (bitwise and) 1

Binary AND Operator copies a bit to the result if it exists in both operands. Example: (A & B) will give 12 which is 0000 1100 | (bitwise or)

2

Binary OR Operator copies a bit if it exists in either operand. Example: (A | B) will give 61 which is 0011 1101 ^ (bitwise XOR)

3

Binary XOR Operator copies the bit if it is set in one operand but not both. Example: (A ^ B) will give 49 which is 0011 0001 ~ (bitwise compliment)

4

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

Example: (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << (left shift) Binary Left Shift Operator. The left operands value is moved left by the number of bits

5

specified by the right operand Example: A << 2 will give 240 which is 1111 0000 >> (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of

6

bits specified by the right operand. Example: A >> 2 will give 15 which is 1111 >>> (zero fill right shift) Shift right zero fill operator. The left operands value is moved right by the number of

7

bits specified by the right operand and shifted values are filled up with zeros. Example: A >>>2 will give 15 which is 0000 1111

The Logical Operators: The following table lists the logical operators: Assume Boolean variables A holds true and variable B holds false, then: Show Examples Operator Description && (logical and) 1

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. Example (A && B) is false. || (logical or)

2

Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. Example (A || B) is true.

3

! (logical not)

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. Example !(A && B) is true. The Assignment Operators: There are following assignment operators supported by Java language: Show Examples SR.NO Operator and Description = 1

Simple assignment operator, Assigns values from right side operands to left side operand. Example: C = A + B will assign value of A + B into C +=

2

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. Example: C += A is equivalent to C = C + A -=

3

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. Example:C -= A is equivalent to C = C - A *=

4

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand. Example: C *= A is equivalent to C = C * A /=

5

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand ExampleC /= A is equivalent to C = C / A %=

6

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand.

Example: C %= A is equivalent to C = C % A <<= 7

Left shift AND assignment operator. ExampleC <<= 2 is same as C = C << 2 >>=

8

Right shift AND assignment operator Example C >>= 2 is same as C = C >> 2 &=

9

Bitwise AND assignment operator. Example: C &= 2 is same as C = C & 2 ^=

10

bitwise exclusive OR and assignment operator. Example: C ^= 2 is same as C = C ^ 2 |=

11

bitwise inclusive OR and assignment operator. Example: C |= 2 is same as C = C | 2

Miscellaneous Operators There are few other operators supported by Java Language. Conditional Operator ( ? : ) 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: 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 : 20 instance of Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is wriiten as: ( Object reference variable ) instanceof (class/interface type) If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example: public class Test { public static void main(String args[]){ String name = "James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); }}This would produce the following result: true 5. Explain about Data types and variables? ANS:Java Is a Strongly Typed Language

It is important to state at the outset that Java is a strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact. Let’s see what this means. First, every variable has a type, every expression has a type, and every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any

type mismatches are errors that must be corrected before the compiler will finish compiling the class. The Primitive Types Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in four groups: • Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers. • Floating-point numbers This group includes float and double, which represent numbers with fractional precision. • Characters This group includes char, which represents symbols in a character set, like letters and numbers. • Boolean This group includes boolean, which is a special type for representingtrue/false values. Integers Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Many other computer languages support both signed and unsigned integers. However, Java’s designers felt that unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used mostly to specify the behavior of the high-order bit, which defines the sign of an integer value. As you will see in Chapter 4, Java manages the meaning of the highorder bit differently, by adding a special “unsigned right shift” operator. Thus, the need for an unsigned integer type was eliminated. The width of an integer type should not be thought of as the amount of storage it consumes, but rather as the behavior it defines for variables and expressions of that type. The Java run-time environment is free to use whatever size it wants, as long as the types behave as you declared them. The width and ranges of these integer types vary widely, as shown in this table: Name Width Range long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 –2,147,483,648 to 2,147,483,647 short 16 –32,768 to 32,767 byte 8 –128 to 127 Let’s look at each type of integer.

byte The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types. Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b and c: byte b, c; short short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the leastused Java type. Here are some examples of short variable declarations: short s; short t; int The most commonly used integer type is int. It is a signed 32-bit type that has a range from – 2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Although you might think that using a byte or short would be more efficient than using an int in situations in which the larger range of an int is not needed, this may not be the case. The reason is that when byte and short values are used in an expression they are promoted to int when the expression is evaluated. (Type promotion is described later in this chapter.) Therefore, int is often the best choice when an integer is needed. long long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed. For example, here is a program that computes the number of miles that light will travel in a specified number of days: // Compute distance light travels using long variables. class Light { public static void main(String args[]) { int lightspeed; long days; long seconds;

long distance; // approximate speed of light in miles per second lightspeed = 186000; days = 1000; // specify number of days here seconds = days * 24 * 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance System.out.print("In " + days); System.out.print(" days light will travel about "); System.out.println(distance + " miles."); } } This program generates the following output: In 1000 days light will travel about 16070400000000 miles. Clearly, the result could not have been held in an int variable. Floating-Point Types Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floatingpoint type. Java implements the standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here: Name Width in Bits Approximate Range double 64 4.9e–324 to 1.8e+308 float 32 1.4e–045 to 3.4e+038 Each of these floating-point types is examined next. float The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. For example, float can be useful when representing dollars and cents. Here are some example float variable declarations: float hightemp, lowtemp;

double Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice. Here is a short program that uses double variables to compute the area of a circle: // Compute the area of a circle. class Area { public static void main(String args[]) { double pi, r, a; r = 10.8; // radius of circle pi = 3.1416; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); } } Characters In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability. Here is a program that demonstrates char variables: // Demonstrate char data type.

class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } This program displays the following output: ch1 and ch2: X Y Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. For this reason, all the “old tricks” that you may have used with characters in other languages will work in Java, too. Although char is designed to hold Unicode characters, it can also be used as an integer type on which you can perform arithmetic operations. For example, you can add two characters together, or increment the value of a character variable. Consider the following program: // char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; // increment ch1 System.out.println("ch1 is now " + ch1); } } The output generated by this program is shown here: ch1 contains X ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence Booleans: Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. Here is a program that demonstrates the boolean type: // Demonstrate boolean values. class BoolTest { public static void main(String args[]) { boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println("b is " + b); // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed.");

Reference Data Types:  Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.  Class objects, and various type of array variables come under reference data type.  Default value of any reference variable is null.  A reference variable can be used to refer to any object of the declared type or any compatible type.

 Example: Animal animal = new Animal("giraffe"); Java Literals: A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. For example: byte a = 68; char a = 'A' byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals. For example: int decimal = 100; int octal = 0144; int hexa = 0x64; String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are: "Hello World" "two\nlines" "\"This is in quotes\"" String and char types of literals can contain any Unicode characters. For example: char a = '\u0001'; String a = "\u0001"; Java language supports few special escape sequences for String and char literals as well. They are:

Notation \n

Character represented Newline (0x0a)

\r

Carriage return (0x0d)

\f

Formfeed (0x0c)

\b

Backspace (0x08)

\s

Space (0x20)

\t

Tab

\"

Double quote

\'

Single quote

\\

Backslash

\ddd

Octal character (ddd)

\uxxxx

Hexadecimal UNICODE character (xxxx)

data type variable [ = value][, variable [= value] ...] ; Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list. Following are valid examples of variable declaration and initialization in Java: 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 = 3.14159;

// declares and assigns a value of PI.

char a = 'a';

// the char variable a iis initialized with value 'a'

Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value ][, identifier [= value ] …]; The type is one of Java’s atomic types, or the name of a class or interface. (Class and interface types are discussed later in Part I of this book.) The identifier is the name of the variable. You can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable. To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of variable declarations of various types. Note that some include an initialization int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. The identifiers that you choose have nothing intrinsic in their names that indicates their type. Java allows any properly formed identifier to have any declared type.

Types of variables in java Three types of variables injava 1.Local Variables 2. Instance Variables (Non-static variables) 3.Class Variables (Static Variables) Declaration of variable:

int data=50;//Here data is variable

Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the methodhas completed. Instance variables: Instance variables are variables within a class but outside any method. These variables

are instantiated when the class is loaded. Instance variables can be accessed from inside any method,constructor or blocks of that particular class. Class variables: Class variables are variables declared within a class, outside any method, with the static keyword.s

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOP THROUGH JAVA Tutorial Sheet: UNIT I-II Classes and objects Short answer questions 1. Explain about public,static,void,main,string[],System.out.println()? 2. Define objects in java? 3. Define Classes in Java? 4. Write a Simple Example of class and object? 5. What are the types of constructors? 6. Can constructor perform other tasks instead of initialization? 7. Difference between constructor and method in java? 8. Define “this” keyword in java? 9. Explain about Java Garbage Collection? 10. Illustrate Method Overloading in Java? 11. Can main () method be overloaded? 12. If Java uses the pass-by reference, why won't a swap function work? 13. Why string objects are immutable in java? 14. Define String and String Buffer? 15. Define Immutable string in java? Descriptive questions/programs/experiments 1. Explain about Method Overloading in java? 2. Explain about Constructor overloading in java? 3. Explain about Parameter passing? Does Java pass parameters by value or by reference? 4. Explain about String Buffer in java? 5. Explain about String Tokenizer in java? Tutor

Faculty

HOD

1. Explain about public, static, void, main, string [], System.out.println ()? Let's see what is the meaning of class, public, static, void,main,String[],System.out.println(). 

class keyword is used to declare a class in java.



public keyword is an access modifier which represents visibility, it means it is visible to all.



static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.



void is the return type of the method, it means it doesn't return any value.



main represents startup of the program.



String[] args is used for command line argument. We will learn it later.



System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.

2. Define objects in java? An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system. create an object you use the syntax = new (<arguments>); Example: creating a Player object player = new Player(); // creates object An object has three characteristics: 

state: represents data (value) of an object.



behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.



identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

3. Define Classes in Java? A class is a group of objects that has common properties. It is a template or blueprint from which objects are created. A class in java can contain: 

data member



method



constructor



block



class and interface

Syntax to declare a class: 1. Class { 2. data member; 3. method; 4. } 4.Write a Simple Example of Object and Class Ans: In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value. 1. Class Student1{ 2. int id;//datamember(alsoinstance variable) 3. String name;//datamember(alsoinstance variable) 4. public static void main(String args[]){

5. Student1 s1=new Student1();//creating an object of Student 6. System.out.println(s1.id); 7. System.out.println(s1.name); 8. } 9. } Output:0 null 5.What are the types of constructors? 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. Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Syntax: (){} Example of constructor: In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. 1. Class Bike1{ 2. Bike1(){System.out.println("Bike iscreated");} 3. public static void main(String args[]){ 4. Bike1 b=new Bike1(); 5. }} Output: Bike is created

6. Can constructor perform other tasks instead of initialization?

Ans: Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method. 7. Difference between constructor and method in java? Ans: There are many differences between constructors and methods. They are given below. Java Constructor

Constructor is used to initialize the state of an object.

Java Method Method is used to expose behaviour of an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler don't have any constructor.

Constructor name must be same as the class name.

in any case. Method name may or may not be same as class name.

8. Define “this” keyword in java? Ans: There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword Here is given the 6 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. //example of this keyword

1. class Student11{ 2. int id; 3. String name; 4. Student11(int id,String name){ 5. this.id=id; 6. this.name=name; 7. } 8. void display(){System.out.println(id+" "+name);} 9. public static void main(String args[]){ 10. Student11 s1=new Student11(111,"Karan"); 11. Student11 s2=new Student11(222,"Aryan"); 12. s1.display(); 13. s2.display(); 14. } Output111 Karan 222 Aryan

9. Explain about Java Garbage Collection? Ans: In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management. Advantage of Garbage Collection 

It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.



It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Simple Example of garbage collection in java 1. Public class TestGarbage1{ 2. publicvoidfinalize(){System.out.println("object isgarbagecollected");} 3. public static void main(String args[]){ 4. TestGarbage1 s1=new TestGarbage1(); 5. TestGarbage1 s2=new TestGarbage1(); 6. s1=null; 7. s2=null; 8. System.gc(); 9. } 10. } Output: object is garbage collected object is garbage collected

10. Illustrate Method Overloading in Java? Ans: If a class have 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 behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly. 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 1. By changing number of arguments By changing the data type 11. Can main () method be overloaded? Ans: Yes. the main() method is a special method for a program entry. You can overload

main() method in any ways. But if you change the signature of the main method, the entry point for the program will be gone. 12. If Java uses the pass-by reference, why won't a swap function work? Ans: Java does manipulate objects by reference, and all object variables are references.

However, Java doesn't pass method arguments by reference; it passes them by value.

13.Why string objects are immutable in java?

Ans: Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java. 14.Difference between String and String Buffer? Ans: There are many differences between String and StringBuffer. A list of differences

between String and StringBuffer are given below: String 1) String class is immutable.

StringBuffer StringBuffer class is mutable.

String is slow and consumes more memory when you StringBuffer is fast and consumes 2) concat too many strings because every time it creates less memory when you cancat new instance.

strings.

String class overrides the equals() method of Object StringBuffer class doesn't override 3) class. So you can compare the contents of two strings the equals() method of Object by equals() method.

class.

15.Define Immutable String in Java? In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created. Let's try to understand the immutability concept by the example given below: 1. class Testimmutablestring{ 2. public static void main(String args[]){ 3. String s="Sachin"; 4.

s.concat(" Tendulkar");//concat() method appends the string at the end

5.

System.out.println(s);//will print Sachin because strings are immutable objects

6. } 7. } Output:Sachin

1. Explain about Method Overloading in java? Ans: If a class have 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 behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly. 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 1. By changing number of arguments

2. By changing the data type a) Example of Method Overloading by changing the no. of arguments In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers. 1. Class Calculation{ 2. void sum(int a,int b){System.out.println(a+b);} 3. void sum(int a,int b,int c){System.out.println(a+b+c);} 4. public static void main(String args[]){ 5. Calculation obj=new Calculation(); 6. obj.sum(10,10,10); 7. obj.sum(20,20); 8. } 9. } Output:30 40 b) 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. 1. class Calculation2{ 2. void sum(int a,int b){System.out.println(a+b);} 3. void sum(double a,double b){System.out.println(a+b);} 4. public static void main(String args[]){ 5. Calculation2 obj=new Calculation2(); 6. obj.sum(10.5,10.5); 7. obj.sum(20,20); 8. } 9. } Output:21.0 40

2. Explain about Constructor methods in java? 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. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Java Default Constructor A constructor that has no parameter is known as default constructor. In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. Syntax of default constructor: (){} 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

Java parameterized constructor A constructor that has 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 have 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(); s2.display();}} Output: 111ran 222 Aryan 3.Explain about Parameter passing? Does Java pass parameters by value or by reference? Ans: The answer to this question can be a little controversial, as there is some misunderstanding around how Java works this out. A lot of developers have the wrong idea

that Java treats primitives and objects differently, so you often hear things like “Java passes primitives by value and object by reference”. Although, this is not entirely true. The reality is that Java always passes parameters by value Call by Value and Call by Reference in Java There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method. Example of call by value in java In case of call by value original value is not changed. Let's take a simple example 1. class Operation{ 2. int data=50; 3. void change(int data){ 4. data=data+100;//changes will be in the local variable only 5. } 6. public static void main(String args[]){ 7.

Operation op=new Operation();

8. 9.

System.out.println("before change "+op.data);

10. op.change(500); 11. System.out.println("after change "+op.data); 12. } 13. } Output: Before change:50 After change:50 Another Example of call by value in java In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:

1. class Operation2{ 2. int data=50; 3. void change(Operation2 op){ 4. op.data=op.data+100;//changes will be in the instance variable 5. } 6. public static void main(String args[]){ 7.

Operation2 op=new Operation2();

8.

System.out.println("before change "+op.data);

9.

op.change(op);//passing object

10. System.out.println("after change "+op.data); 11. } 12. } Output: before change 50 after change 150

3.Explain about String Buffer in java?

Ans: Java String Buffer class Java String Buffer class is used to created mutable (modifiable) string. The String Buffer class in java is same as String class except it is mutable i.e. it can be changed. Important Constructors of String Buffer class 1. StringBuffer(): creates an empty string buffer with the initial capacity of 16. 2. StringBuffer(String str): creates a string buffer with the specified string. 3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length. Important methods of StringBuffer class 1. public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. 2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is

overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. 3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex. 4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex. 5. public synchronized StringBuffer reverse(): is used to reverse the string. 6. public int capacity(): is used to return the current capacity. 7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum. 8. public char charAt(int index): is used to return the character at the specified position. 9. public int length(): is used to return the length of the string i.e. total number of characters. 10. public String substring(int beginIndex): is used to return the substring from the specified beginIndex. 11. public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex. Mutable string: A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. 1) StringBuffer append() method The append() method concatenates the given argument with this string. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer("Hello "); 4. sb.append("Java");//now original string is changed 5. System.out.println(sb);//prints Hello Java 6. } 7. }

2) StringBuffer insert() method The insert() method inserts the given string with this string at the given position. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer("Hello "); 4. sb.insert(1,"Java");//now original string is changed 5. System.out.println(sb);//prints HJavaello 6. } 7. } 3) StringBuffer replace() method The replace() method replaces the given string from the specified beginIndex and endIndex. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer("Hello"); 4. sb.replace(1,3,"Java"); 5. System.out.println(sb);//prints HJavalo 6. } 7. } 4) StringBuffer delete() method The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer("Hello"); 4. sb.delete(1,3); 5. System.out.println(sb);//prints Hlo 6. } 7. }

5) StringBuffer reverse() method The reverse() method of StringBuilder class reverses the current string. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer("Hello"); 4. sb.reverse(); 5. System.out.println(sb);//prints olleH 6. } 7. } 6) StringBuffer capacity() method The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. 1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer(); 4. System.out.println(sb.capacity());//default 16 5. sb.append("Hello"); 6. System.out.println(sb.capacity());//now 16 7. sb.append("java is my favourite language"); 8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 9. } 10. } 7) StringBuffer ensureCapacity() method The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

1. class A{ 2. public static void main(String args[]){ 3. StringBuffer sb=new StringBuffer(); 4. System.out.println(sb.capacity());//default 16 5. sb.append("Hello"); 6. System.out.println(sb.capacity());//now 16 7. sb.append("java is my favourite language"); 8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 9. sb.ensureCapacity(10);//now no change 10. System.out.println(sb.capacity());//now 34 11. sb.ensureCapacity(50);//now (34*2)+2 12. System.out.println(sb.capacity());//now 70 13. } 14. } 5. Explain about String Tokenizer in java? Ans:The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like Stream Tokenizer class. We will discuss about the Stream Tokenizer class in I/O chapter. Constructors of String Tokenizer class: There are 3 constructors defined in the String Tokenizer class. Constructor

Description

StringTokenizer(String str)

creates StringTokenizer with specified string.

StringTokenizer(Stringstr,

creates StringTokenizer with specified string and

String delim)

delimeter. creates

StringTokenizer

with

specified

string,

StringTokenizer(Stringstr,String

delimeter and returnValue. If return value is true,

delim, boolean returnValue)

delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Methods of String Tokenizer class: The 6 useful methods of StringTokenizer class are as follows: Public method

Description

boolean hasMoreTokens()

checks if there is more tokens available.

String nextToken()

returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter. boolean hasMoreElements()

same as hasMoreTokens() method.

Object nextElement()

same as nextToken() but its return type is Object.

int countTokens()

returns the total number of tokens.

Simple example of StringTokenizer class Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace. 1. import java.util.StringTokenizer; 2. public class Simple{ 3. public static void main(String args[]){ 4.

StringTokenizer st = new StringTokenizer("my name is khan"," ");

5.

while (st.hasMoreTokens()) {

6.

System.out.println(st.nextToken());

7.

}

8.

}

9. } Output:my Name Is khan

Example of nextToken(String delim) method of StringTokenizer class 1. import java.util.*; 2. public class Test { 3.

public static void main(String[] args) {

4.

StringTokenizer st = new StringTokenizer("my,name,is,khan");

5. s

// printing next token

6. 7.

System.out.println("Next token is : " + st.nextToken(",")); }

8. } Output:Next token is : my s

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: Object-Oriented Programming through JAVA Tutorial Sheet: UNIT IV-1 Applets Short answer questions 1. Write short notes on JAVA applet: 2. Write the advantages and drawbacks of applet. 3. Who is responsible to manage the life cycle of an applet? 4. How to run an Applet? 5. What are the two types of Applets: 6. What are two important packages you need to import during applet creation? 7. What is the difference between an Applet and an Application? 8. What are the Applet’s Life Cycle methods? Explain them? 9. What are the Applet’s information methods? 10. What is AppletStub Interface? 11. How to display Image in Applet. 12. How to get the object of Image: 13. What are the other required methods of Applet class to display image: 14. What are the interfaces defined by java.applet? 15. Show the Hierarchy of Applet classes Descriptive Questions: 1. Explain about Applet Class. 2. How do you invoke an applet? 3. Write the steps for converting a JAVA application into an applet. 4. How to Display Graphics in Applet. 5. Show an Example of using parameter in Applet:

Faculty

Tutor

HoD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: Object-Oriented Programming through JAVA Tutorial Sheet: UNIT IV-1 Applets Short answer questions 1.Write short notes on JAVA applet: Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. 2.Write the advantages and drawbacks of applet. There are many advantages of applet. They are as follows: o

It works at client side so less response time. o Secured o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc. Drawback of Applet Plugin is required at client browser to execute applet. 3. Who is responsible to manage the life cycle of an applet? Java Plug-in software. 4. How to run an Applet? There are two ways to run an applet 1. By html file. 2. By appletViewer tool (for testing purpose). 5. What are the two types of Applets: 1. First type of applets based directly on the Applet class,these applets use the AWT to provide GUI. 2. Second type applets are based on Swing Class Japplet. 6. What are two important packages you need to import during applet creation? These import statements bring the classes into the scope of our applet class:  java.applet.Applet.  java.awt.Graphics. Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.

7. What is the difference between an Applet and an Application? 1. Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading. 2. Applets can only be executed inside a java compatible container, such as a browser or appletviewer whereas Applications are executed at command line by java.exe or jview.exe. 3. Applets execute under strict security limitations that disallow certain operations(sandbox model security) whereas Applications have no inherent security restrictions. 4. Applets don't have the main() method as in applications. Instead they operate on an entirely different mechanism where they are initialized by init(),started by start(),stopped by stop() or destroyed by destroy(). 8. What are the Applet’s Life Cycle methods? Explain them? Ans :  init( ) method - Can be called when an applet is first loaded.  start( ) method - Can be called each time an applet is started.  paint( ) method - Can be called when the applet is minimized or refreshed.  stop( ) method - Can be called when the browser moves off the applet’s page.  destroy( ) method - Can be called when the browser is finished with the applet. 9. What are the Applet’s information methods? Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy right information, etc. getParameterInfo( ) method : Returns an array of string describing the applet’s parameters. 10. What is AppletStub Interface? Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface 11. How to display Image in Applet Applet is mostly used in games and animation. For this purpose image is required to be displayed. The java.awt.Graphics class provide a method drawImage() to display the image. Syntax of drawImage() method: 1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image. 12. How to get the object of Image: The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax: public Image getImage(URL u, String image){} 13.What are the other required methods of Applet class to display image: 1. public URL getDocumentBase(): is used to return the URL of the document in which applet is embedded. 2. public URL getCodeBase(): is used to return the base URL. 14. What are the interfaces defined by java.applet? 1. AppletContext 2. AudioClip

3. AppletStub 15. Show the Hierarchy of Applet classes

Descriptive Questions: 1. Explain about Applet Class. Ans: The Applet CLASS: Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context. These include methods that do the following:  Get applet parameters  Get the network location of the HTML file that contains the applet  Get the network location of the applet class directory  Print a status message in the browser  Fetch an image  Fetch an audio clip  Play an audio clip  Resize the applet Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet's execution. The viewer may:  request information about the author, version and copyright of the applet  request a description of the parameters the applet recognizes  initialize the applet  destroy the applet  start the applet's execution  stop the applet's execution The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary. 2.How do you invoke an applet? Ans:Invoking an Applet: An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. The tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet:

The Hello, World Applet
If your browser was Java-enabled, a "Hello, World" message would appear here.
Note: You can refer to HTML Applet Tag to understand more about calling applet from HTML. The code attribute of the tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with a tag. If an applet takes parameters, values may be passed for the parameters by adding <param> tags between and . The browser ignores text and other tags between the applet tags. Non-Java-enabled browsers do not process and . Therefore, anything that appears between the tags, not related to the applet, is visible in non-Java-enabled browsers. The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the tag as shown: If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to separate package/class components. For example:

3. Write the steps for converting a JAVA application into an applet. Ans: It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can start with the java program launcher) into an applet that you can embed in a web page. Here are the specific steps for converting an application to an applet.  Make an HTML page with the appropriate tag to load the applet code.  Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded.

 

   

Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser. Move any initialization code from the frame window constructor to the init method of the applet. You don't need to explicitly construct the applet object. The browser instantiates it for you and calls the init method. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.) Don't call setVisible(true). The applet is displayed automatically.

4. How to Display Graphics in Applet

Ans:java.awt.Graphics class provides many methods for graphics programming. Commonly used methods of Graphics class: 1. public abstract void drawString(String str, int x, int y): is used to draw the specified string. 2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height. 3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height. 4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height. 5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height. 6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2). 7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image. 8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc. 9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc. 10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color. 11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font. 5.Show an Example of using parameter in Applet: Ans: We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getParameter(). Syntax: public String getParameter(String parameterName)

Example: import java.applet.Applet; import java.awt.Graphics; public class UseParam extends Applet{ public void paint(Graphics g){ String str=getParameter("msg"); g.drawString(str,50, 50); } } myapplet.html <param name="msg" value="Welcome to applet">

Faculty

Tutor

HoD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16 Tutorial Sheet –IV-2

Topics: Event Handling, AWT Short Questions: 1. What is an event? What is event handler? 2. Discuss about the Types of Event 3. What is the advantage of the event-delegation model over the earlier event-inheritance model? 4. What is the purpose of the enableEvents() method? 5. Write code for the Item event handler of a checkbox (namely incCB) that increments a variable total and display it on a label (namely count) if the checkbox is selected. 6. What is the difference between a Choice and a List? 7. How would you ensure that in a list (i) Only a single item gets selected (ii) Only a single range of items gets selected iii) Multiple ranges of items get selected 8. What is the significance of a button group? How do you create a button group? 9. Compare and contrast a list box and a combo box. 10. What method obtains the current selection of a combo box? Give a code-example. 11. Write code for the Item event handler of a checkbox (namely incCB) that increments a variable total and display it on a label (namely count) if the checkbox is selected. 12. Write code for the event handler of a radio button so that when it is selected/unselected, its text changes to “ I am selected” or “I am unselected”). 13. Show the Java AWT Hierarchy 14. Write short notes on Adapter Classes 15. Where the Event Handling Codes can be placed: Descriptive Questions: 1. Discuss about some commonly used properties of lists and combo boxes. 2. Write code for event handler of each of the buttons in following application: 3. What major events are associated with the following? (i) Text Field ii)Password Field iii)Check Box (iv)Radio Button (v)Scroll Bar (vi) Slider 4. List the Event classes and Listener interfaces 5. How to register an event handler for the object Faculty

Tutor

HOD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / I

Academic year: 2015-16 Tutorial Sheet –IV-2

Topics: Event Handling, AWT Short Questions and Answers: 1. What is an event? What is event handler? o Event is an occurrence of an activity. o Event handler is a method that understands the event and processes it. The event handler method takes the event object as a parameter. 2. Discuss about the 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.

3. What is the advantage of the event-delegation model over the earlier eventinheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. 4. What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their eventdispatch methods

5. Write code for the Item event handler of a checkbox (namely incCB) that increments a variable total and displays it on a label (namely count) if the checkbox is selected. private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) { int total=5; if(jCheckBox1.isSelected()==true) { total=total+1; jLabel4.setText(Integer.toString(total)); } else { jLabel4.setText(Integer.toString(total)); } } 6. What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. 7. How would you ensure that in a list (iii) Only a single item gets selected (iv) Only a single range of items gets selected iii) Multiple ranges of items get selected Following values of selectionMode are used to ensure that in a list (i) Only a single item gets selected - SINGLE (ii) Only a single range of items gets selected – SINGLE_INTERVAL iii) Multiple ranges of items get selected- MULTIPLE_INTERVAL 8. What is the significance of a button group? How do you create a button group?  A button group is a group control out of which only one can be selected at a time.  A button group is created through JButtonGroup component class of java Swing.

In a button group we can put radio buttons or push buttons. Although checkboxes can also be put in a button group but it is not recommended. 9. Compare and contrast a list box and a combo box. Compare  List boxes and combo boxes

present a list of choices to the user.

Contrast  In a list, the user must select items

directly from the list whereas in a combo box user can edit it if he/she whishes.  List allow us to select more than one item but a combobox allows only single item selection.

10. What method obtain the current selection of a combo box? Give a codeexample.  getSelectedItem()

Example private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { String dur=(String)jComboBox1.getSelectedItem(); jLabel1.setText(dur); } 11. Write code for the Item event handler of a checkbox (namely incCB) that increments a variable total and displays it on a label (namely count) if the checkbox is selected. Ans: private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) { int total=5; if jCheckBox1.isselected()==true) { total=total+1; jLabel4.setText(Inte ger.toString(total)); } else { jLabel4.setText(Integer.toString(total)); } }

12. Write code for the event handler of a radio button so that when it is selected/unselected, its text changes to “ I am selected” or “I am unselected”). Ans: private void jRadioButton1ActionPerformed(java.awt.event.Acti onEvent evt) { if(jRadioButton1.isSelected()==true) { jLabel4.setText("i am selected"); } else { jLabel4.setText("i am unselected"); } }

13. Show the Java AWT Hierarchy The hierarchy of Java AWT classes are given below.

14. Write short notes on Adapter Classes Ans: An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you. 15. Where the Event Handling Codes can be placed: We can put the event handling code into one of the following places: 1. Same class 2. Other class 3. Anonymous class Descriptive Questions & Answers: Discuss about some commonly used properties of lists and combo boxes. 1. Lists  model : The object containing the data to be exhibited by the list.  selectionMode : Describes the mode used for selecting listy items. It defines three modes of selection: SINGLE, SINGLE_INTERVAL, MULTIPLE_INTERVAL.  selectedIndex : Return the index of selected item. Default is -1 i.e., initially no item is selected. If, however, yopu want a specific item to appear selected, you may set this property to a valid index.  selectedIndices : Returns the indices of selected item in form an array. Default is -1 i.e., no item is by default selected.  visibleRowCount : sets the preferred numbers of rows to display without requiring scrolling. 2. Combo boxes  editable : if true, the user can type a new value in the text field of combo

box.  maximumRowCount : Defines the maximum number of rows the popup should have.  model : The object containing the data to be exhibited by the combo box.  selectedIndex : Returns the index of selectede item or -1 if there is none. selectedItem : Returns the selected item. 2.Write code for event handler of each of the buttons in following application:

Button1 Initializes the value of label to 0 (zero) Button2 Increments the value of label by 1 (one) Button3 Decrements the value of label by 1 (one) Code: int i=0; // Button 1 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { i=0; jLabel1.setText(Integer.toString(i)); } //Button 2 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { i=i+1; jLabel1.setText( Integer.toString( i)); } //Button 3 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { i=i-1; jLabel1.setText( Integer.toString(

i)); } 3. What major events are associated with the following? 1. Text Field 2. Password Field 3. Check Box 4. Radio Button 5. Scroll Bar 6. Slider Do write the actions that trigger these events Ans: (i) (ii) (iii) (iv) (v)

(vi) is dragged.

Text Field: Action Event is associated with text field and triggered when user presses enter in a text field. Password Field: Action Event is associated with Password field and triggered when user presses enter in a Password field. Check Box: Item Event is associated with Check Box and triggered when a check box is clicked. Radio Button: Item Event is associated with Radio Button and triggered when a radio button is clicked. Scroll Bar: Adjustment Event is associated with scroll bar and triggered when knob of a scroll bar is dragged. Slider: Change Event is associated with slider and triggered when knob of a slider

4. List the Event classes and Listener interfaces 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

5. How to Register an event handler for the object Ans: To listen to an event, an object must register to be that event’s listener. The following code creates a JButton and registers an ActionListener for it. JButton button = new JButton("I'm a Swing button!"); button.addActionListener(this); 3 Steps to Implement an Event Handler To implement an event handler, you must take the following three steps: 1. Implement a listener interface: public class MyClass implements ActionListener 2. Add the listener to an object: button.addActionListener(this) 3. Define the methods of the listener interface: public void actionPerformed(ActionEvent e){ ...//code that reacts to the action.. }

Faculty

Tutor

HOD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOP THROUGH JAVA UNIT-I Assignnment questions: 1.Write about any six distinct features in Java programming.? 2. Explain the String class methods with a sample JAVA program. 3.Explain the benefits are of object oriented programming? 4.Write a Java program to reverse of a given long integer?. 5.Discuss difference between object oriented laanguage and procedural languages? 6.How java language overcome the other programming languages? 7. if one is familiar with two or more distinct computer programming languages,give an example showing how one language would direct the programmer to one type of solution and a different language would encourage an alternative solution? 8. Compare in terms of their functions,the following pair of statements i) while and do while ii)while and for 9.What kind of things can become objects in java? 10.Can a java run on any machine? what is needed to run java on a computer? 11.How compiler and JVM can differentiate constructor and method definitions of both have same class name? 12. How compiler and JVM can differentiate constructor and method invocations of both have same class name? 13. Is java Pass by value or pass by reference? 14. How do compiler differentiate overloaded methods from duplicate methods? 15. ) Can we declare one overloaded method as static and another one as non-static? 16.Explain about operator precedence? 17. Explain about narrowing conversion?

18.Write a program to print all permutation of string? 19. Which methos is used to perform comparision between the strings that ignores case difference? 20.Differences between string and string tokenizer?

Faculty

Tutor

HOD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester : II / II

Academic year: 2015-16

Subject: Object oriented programming through java

Assignment Sheet-UNIT-2 1. What is inheritance? What are the types of inheritances? Discuss the advantages & disadvantages of inheritance? 2. What is multiple inheritance? How can multiple inheritance be implemented in JAVA? Explain with example? 3. What is the name of the root class for all objects in JAVA? 4. How can you prevent a method for overriding(Final)? 5. Define abstract class & interface and what is the difference between them? 6. What is an abstract class? What is it importance? How is it designed in JAVA? Explain with suitable example? 7. What is package? Explain the procedure to create/Define and accessing a package with the help of an example? 8. Example briefly member access rules? Where are they used? 9. What is the super key word? Where they are used? 10. What is meant by polymorphism? Explain types of polymorphism? 11. What is meant by method signature? 12. Define the term subclass? Why super class members are available to subclass? 13. What does it mean to override a method? 14. How can you call the garbage collector? Explain with example? 15. Explain usage of import statement? Explain with suitable example? 16. Explain any three packages with their classes? 17. Explain briefly java.io.package? 18. Explain in detail the various forms of interface implements? 19. How does package resolve name space problems? 20. What is a class path? How the class path is set?

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: OOPS THROUGH JAVA Tutorial Sheet: UNIT III EXCEPTION HANDLING AND MULTITHREDDING Short answer questions 1. What is Exception Handling and list different types of exceptions 2. What is Unchecked and checked exception list any 3 in each exception. 3. Draw and Explain Exception Hierarchy 4. List and explain the clauses in exception handling along with syntax of each clause 5. Describe built-in exception in detail 6. Explain the syntax of multiple catch block with necessary example 7. Explain and list out about compile time errors and runtime errors 8. Explain about re-throwing an exception and how to create own exception classes 9. Explain about process and thread in detail? 10. What the differences between multicasting and multithreading? 11. List and explain the imported methods defined by a thread class 12. Explain thread life cycle? 13. Write a short notes on creation of thread 14. What is synchronization? 15. What is deadlock? How is it resolved 16. Explain ThreadGroup class. List some methods defined by it? 17. Explain inter-thread communication? 18. Describe about thread priorities? 19. Explain in detail about creating threads and synchronizing threads? 20. Explain in detail about Daemon threads? Tutor

Faculty

HOD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II SUB:JAVA

Academic year: 2015-16 Assignment Sheet: UNIT-4

Descriptive questions/Programs/Experiments 1. Write an applet which displays multiple lines of text in the applet window? 2. What is meant by AWT? How will you create User Interfaces for applets? 3. Design an application having interface as shown below:

4. Develop a simple integer calculator. It has two text fields, a label that displays the result, and 4 radio buttons (+, -, *, /). Here is how it works:  Input numbers in the text fields, e.g. 10 .. 10  Choose the operation by selecting one of the radio buttons, e.g. +  The label will display the result based on the selected operation, e.g. 20 5. 6. 7. 8.

Explain in detail about handling mouse and keyboard events. Discuss about AWT text components with examples. Write and Explain an Applet program to check the input number is Even or Odd. What are the methods supported by KeyListener interface and MouseListener interface. Explain each of them with examples 9. Write a Sample program for event handling classes placed in anonymous class.

10. Design a screen in JAVA which accepts text in text box. If the left mouse button is clicked, convert the text to upper case, if right mouse button is clicked, convert the text to lower case. 11. Write a Java program to create a combo box to list of subjects. Copy the subjects in text field on click using applet 12. Explain any 5 component of AWT 13. Write a program to create a screen which contains 3 check boxes(Dos,Linux,Windows) and displays selected items in text box. 14. Explain in detail Event handling mechanism in JAVA with suitable example 15. How to play audio in Applet. Write a sample code 16. Explain the process of creating an applet and Passing parameters to applets. 17. Explain the process of creating an applet and Passing parameters to applets. 18. 17. Briefly explain AWT class hierarchy. 19. How do you create, load and display an image 20. Write JAVA code to demonstrate an Adapter Faculty

Tutor

HOD

Gokaraju Rangaraju Institute of Engineering and Technology Department of Computer Science and Engineering Year/Semester: II / II

Academic year: 2015-16

SUB: JAVA Assignment Sheet: UNIT-V Descriptive questions/Programs/Experiments 1.What is a Swing?What is the difference between Swing and AWT?Describe,in detail, about various components in Swing 2.Explain in detail about AWT Class hierarchy 3.Explain the functionality of JComponent with an example. 4.Discuss about merits and demerits of JApplet 5.Explain the steps in creating a Subclass of Frame with an example. 6. Explain about Jcombobox 7.Write a program for creation of labels in the applet window 8.Discuss about merits and demerits of JFrame 9. Discuss about merits and demerits of JComponent. 10.How are the elements of different layouts organized? 11.What advantage do Java's layout managers provide over traditional windowing systems? 12.What is the difference between a Window and a Frame? 13.What do heavy weight components mean? 14.What is the preferred size of a component? 15.Which containers use a FlowLayout as their default layout? 16. Implement a program with a GUI that looks like the one shown below. Put the main method in a class named MyDemo1.

39

17.Explain the Swing Action architecture? 18.Explain layout managers? 19.Explain the Swing delegation event model? 20.How will you go about building a Swing GUI client?

40

Related Documents

Jntuh Java Notes
March 2021 0
Java
January 2021 4
Java
January 2021 3
Java
February 2021 4
Java
January 2021 15

More Documents from "Leimonis Tasos"