Object Oriented Programming - JAVA and VISUAL BASIC, lecture notes, A. SINGH, Study notes for Object Oriented Programming. Biyani Girls College

Object Oriented Programming

Description: Object Oriented Programming (Java and Visual Basic) (BCA Part-II) Shipra Rastogi GNIIT, 'A' Level Lecturer Deptt. of Information Technology Biyani Girls College, Jaipur Hastlipi, Jaipur //////////////////////////////////////////////// Syllabus B.C.A. Part-II Object Oriented Programming Through Java Constants, Variables, Data Types, Arithmetic Operations, Relational Operators, Logical Operators, Assignment Operators, Increment and Decrement Operator, Conditional Operator, Bit-wise Operator, Arithmetic Expression, Type Conversion in Expressions, Mathematical Functions, Decision Control Structure, Loop Control Structure, Classes, Objects and Methods, Boolean Methods, Void Methods, Overloading, Nesting of Methods, Constructors, Class Invariants, Composition, Recursive Classes, Extending a Class, Overriding Method, Inheritance versus Compositions, Class Hierarchies, Arrays and Vector, String Arrays, Wrapper (Classes), Defining, Extending and Implementing Interfaces, Accessing Interface Variables, Graphics, Managing Layouts, Event Driven Programming, Applets, Thread and Exceptions, Managing Input Output Files, Reusable Classes, Searching, Sorting and Recursive Algorithims. Object Oriented Programming Through Visual Basic Object Model, Visual Basic Environment, Visual Basic Code Statements, Controls, Coding for the Controls, Variables, Constants and Calculations, Decision Control Structure, Loop Control Structure, Nested Ifs Statement, Input Validations, Calling Event Procedures, Menus, Sub Procedures and Sub Functions, Multiple Forms, Variables and Constants in Multiple Form Projects, List Boxes and Combo Boxes, Using Mfg Box and String Function, Arrays, Using List Boxes and Arrays, Multidirectional Arrays, Classes, Initializing and Terminating Events, Collections, Using the Object Browser, Data Files, Sequential File Organisation, Random Data Files, Accessing Database Files, Navigation the Database in Code, Displaying Data in Grids, Validation and Error Trapping, Dragging and Dropping Multiple Objects, Graphics, Layering, Simple Animation, Active X, Dynamic Link Libraries, Object Linking and Optimizing VB Code, OLE Automation and VBA, Automating Word, Excel and Outlook 98. Show more
Showing pages  1  -  2  of  16
The preview of this document ends here! Please or to read the full document or to download it.
Document information
Embed this document:
Microsoft Word - Object Oriented Programming JAVA A. SINGH.docx

Object Oriented Programming (Java and Visual Basic) (BCA Part-II) Shipra Rastogi GNIIT, 'A' Level Lecturer Deptt. of Information Technology Biyani Girls College, Jaipur

Hastlipi, Jaipur

I

Syllabus B.C.A. Part-II Object Oriented Programming Through Java Constants, Variables, Data Types, Arithmetic Operations, Relational Operators, Logical Operators, Assignment Operators, Increment and Decrement Operator, Conditional Operator, Bit-wise Operator, Arithmetic Expression, Type Conversion in Expressions, Mathematical Functions, Decision Control Structure, Loop Control Structure, Classes, Objects and Methods, Boolean Methods, Void Methods, Overloading, Nesting of Methods, Constructors, Class Invariants, Composition, Recursive Classes, Extending a Class, Overriding Method, Inheritance versus Compositions, Class Hierarchies, Arrays and Vector, String Arrays, Wrapper (Classes), Defining, Extending and Implementing Interfaces, Accessing Interface Variables, Graphics, Managing Layouts, Event Driven Programming, Applets, Thread and Exceptions, Managing Input Output Files, Reusable Classes, Searching, Sorting and Recursive Algorithims. Object Oriented Programming Through Visual Basic Object Model, Visual Basic Environment, Visual Basic Code Statements, Controls, Coding for the Controls, Variables, Constants and Calculations, Decision Control Structure, Loop Control Structure, Nested Ifs Statement, Input Validations, Calling Event Procedures, Menus, Sub Procedures and Sub Functions, Multiple Forms, Variables and Constants in Multiple Form Projects, List Boxes and Combo Boxes, Using Mfg Box and String Function, Arrays, Using List Boxes and Arrays, Multidirectional Arrays, Classes, Initializing and Terminating Events, Collections, Using the Object Browser, Data Files, Sequential File Organisation, Random Data Files, Accessing Database Files, Navigation the Database in Code, Displaying Data in Grids, Validation and Error Trapping, Dragging and Dropping Multiple Objects, Graphics, Layering,

Simple Animation, Active X, Dynamic Link Libraries, Object Linking and Optimizing VB Code, OLE Automation and VBA, Automating Word, Excel and Outlook 98. □ □ □

Content Part-I (Java) S.No. Name of Topic Page No. 1. Basics of Object Oriented Programming 9-11 1.1 Necessity of Object Oriented Programming over Procedural Programming 1.2 Essentials of Object Oriented Programming 2. Applets 12-13 2.1 Web Programming through Applets 2.2 Processing Input with Applets 3. Java Interpreter and Runtime Environment 14-16 3.1 Memory Management 4. Basic Features of Java Language 17-31 4.1 Constants 4.2 Variables 4.3 Data Types 4.4 Different Types of Operators 4.5 Boolean Methods 4.6 Classes and Objects 5. Declaration of Arrays 32-33 5.1 Arrays Declaration 5.2 String Arrays 6. Control Structures of Java Language 34-41 6.1 Decision Control Structure 6.2 Loop Control Structure S.No. Name of Topic Page No. 7. Constructors in JAVA 42-44 7.1 Constructors Declaration 8. Nesting of Classes 45-47 8.1 Nested Classes 9. Interfaces and Inheritance 48-64 9.1 Interfaces 9.2 Inheritance 9.3 Method Overloading 9.4 Method Overriding 9.5 Abstract Methods and Classes 10. Strings and their Manipulation 65-66 10.1 Strings Declaration 11. Packages in ‘JAVA’ 67-68 11.1 Classes and Packages

12. Basic Input/Output Streams 69-73 12.1 Managing Input/Output Files 13. Threads and their working 74-77 13.1 Lifecycle of a Thread 13.2 Multithreading 14. Exception Handling 78-81 14.1 Exceptions 15. Graphics Programming 82-84 15.1 Graphics Functions Part-II (Visual Basic) S.No. Name of Topic Page No. 1. Integrated Development Environment 87-90 1.1 Visual Basic Environment 2. Basic Programming Concepts 91-94 2.1 Controls 2.2 Properties 2.3 Variables Constants 3. Array Declaration 95-96 3.1 Arrays 3.2 Multidimensional Arrays 4. Procedural Programming 97-98 4.1 Objects and Modules 4.2 Procedures (Sub Procedures and Sub Functions) 4.3 Functions 5. Branching and Looping Constructs 99-103 5.1 Loop Control Structures 5.2 Decision Control Procedures 6. Forms 104-105 6.1 Multiple Forms S.No. Name of Topic Page No. 7. Programming Methodologies and Controls available in VB 106-116 7.1 Global and Public Variables 7.2 Active and Deactivate Events 7.3 Active X Controls 7.4 List Box, Combo Box and Text Box Controls 8. Active X Components and Data Objects 117-119 8.1 Object Linking and Optimizing VB Code 8.2 Active X Data Objects Examination Paper 2008 120-126 Chapter-1 Basics of Object Oriented Programming

Q.1 What is the difference between Procedural and Object Oriented Programming? Ans.: The different languages reflect the different styles of programming. Procedural programming decomposes a program into various different functional units, each of which can gather and manipulate data as needed. Object-oriented programming, on the other hand, decomposes a program into various different data-oriented units or other conceptual units; each unit contains data and various operations that may be performed on that data. Procedural programming forced developers to write highly interdependent code. A minor change in any part of the code may end up with a bigger modification of large pieces of code. This way of programming is not up to the mark when the user interactivity is higher.Using OOP, a developer can break down any real world item into a collection of objects. These individual objects can be used separately and collectively to accomplish the requirements. We can summarize the differences as follows : • Procedural Programming – top down design – create functions to do small tasks – communicate by parameters and return values • Object Oriented Programming – design and represent objects – determine relationships between objects – determine attributes each object has – determine behaviours each object will respond to – create objects and send messages to them to use or manipulate their attributes Q.2 What are the basic features of Object Oriented Programming? Ans.: Object Oriented Programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including encapsulation, modularity, polymorphism, and inheritance. Inheritance : ‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own. Inheritance is inheriting a class into another class. Encapsulation : Encapsulation conceals the functional details of a class from objects that send messages to it. This is hiding the internal details. Abstraction : Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem. Building class is an abstraction process. Polymorphism : Multiple objects exhibiting similar features in different ways is known as polymorphism. Polymorphism is the process of using an operator or function in different ways for different set of inputs given. Q.3 What are the basic differences between C++ and Java? Ans.: C++ and Java both are Object Oriented Languages but some of the features of

both languages are different from each other. Some of these features are : o All stand-alone C++ programs require a function named main and can have numerous other functions, including both stand-alone functions and functions, which are members of a class. There are no stand-alone functions in Java. Instead, there are only functions that are members of a class, usually called methods. Global functions and global data are not allowed in Java. o All classes in Java ultimately inherit from the Object class. This is significantly different from C++ where it is possible to create inheritance trees that are completely unrelated to one another. o Java does not support multiple inheritance. To some extent, the interface feature provides the desirable features of multiple inheritance to a Java program without some of the underlying problems. o Java does not support operator overloading. □ □ □ Chapter-2 Applets Q.1 What are the differences between Applications and Applets? OR Explain Java Applets? Ans.: Java is a general-purpose, object-oriented programming language. We can develop two types of Java programs : Stand alone Applications : Programs written in Java to carry out certain tasks on a stand alone local computer. Executing stand alone java programs involves two steps : (a) Compiling through javac compiler. (b) Executing the byte code using java interpreter. Web Applets : Programs that are developed for Internet based applications. An applet located on a distant computer (Server) can be downloaded via Internet and executed on a local computer (Client) using a java capable browser. From the user’s point of view, Java applications can be compared to compiled C programs since they are started from a command line just like any compiled program would be started. However, there is a major difference: Java applications, as well as applets, are interpreted. Applications are started on the command-line by calling the Java Interpreter with the name of the application as an argument. Applets, in contrary to applications, are small programs which can be included in web pages and run inside the user's browser. Alternatively, applets can be run in the applet viewer that comes with the JDK, which has advantages for debugging. □ □ □ Chapter-3

Java Interpreter and Runtime Environment Q.1 What is JVM? Ans.: A Java Virtual Machine (JVM) is a set of computer software programs and data structures which use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. This language conceptually represents the instruction set of a stack-oriented, capability architecture. Java Virtual Machines operate on Java bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a JVM. JVMs can also be released by other companies besides Sun (the developer of Java) -- JVMs using the "Java" trademark may be developed by other companies as long as they adhere to the JVM specification published by Sun (and related contractual obligations). The JVM is a crucial component of the Java Platform. Because JVMs are available for many hardware and software platforms, Java can be both middleware and a platform in its own right — hence the expression "write once, run anywhere." The use of the same bytecode for all platforms allows Java to be described as "compile once, run anywhere", as opposed to "write once, compile anywhere", which describes cross-platform compiled languages. The JVM also enables such unique features as Automated Exception Handling which provides 'root-cause' debugging information for every software error (exception) independent of the source code. Q.2 What is Automatic Memory Management? Ans.: Automatic memory management, also known as automatic garbage collection, is the practice of allowing the language implementation to keep track of used and unused memory, freeing the programmer from this burden. In languages without automatic memory management, the programmer must reserve memory when it is required and mark it as free once its contents no longer have effect in the running program. For example, in the C programming language (probably the most commonly used of those without automatic memory management) this is achieved by using the functions malloc, calloc, realloc, alloc and free. On the other hand, languages (or implementations) with automatic memory management automatically reserve memory when it is required for storing new values and reclaim it (free it) when their contents can no longer affect future computations (1) Java automatically does the Garbage collecting and probably does a better job than most developers on the down side. (2) By auto Garbage collecting it takes away an opportunity for developers to

optimise garbage collecting and auto Garbage collecting can be seen as a constraint not a benefit. In the most part it is a benefit because it simplifies programming in Java and is probably more efficient at garbage collecting than self regulated Garbage collecting, unless people spent time researching the best way to garbage collect. Garbage collection concerns objects with dynamic extent (allocated with a new statement in these languages). Java uses various techniques to automatically discover when these objects are no longer referred to, and to reclaim them. In contrast, C++ programmers manually specify where an object with dynamic extent is to be reclaimed by coding a delete statement. _ Java classes can have a finalize function. _ Java uses run-time processing to discover dead objects (which are eligible for reclamation). Q.3 What is JRE? OR What is Java Runtime Environment? Ans.: The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. (a) Java Plug-in : Java Plug-in technology, included as part of the Java Runtime Environment, Standard Edition (Java SE), establishes a connection between popular browsers and the Java platform. This connection enables applets on Web sites to be run within a browser on the desktop. (b) Java Web Start : Using Java Web Start technology, standalone Java software applications can be deployed with a single click over the network. Java Web Start ensures the most current version of the application will be deployed, as well as the correct version of the Java Runtime Environment (JRE). □ □ □ Chapter-4 Basic Features of Java Language Q.1 What are Command Line Arguments? Ans.: Command line arguments are parameters that are supplied to the application program at the time of invoking it for execution. We can write Java programs that can receive and use the arguments provided in the command line. e.g. public static void main (String args[]). args is declared as an array of strings and arguments provided in the command line are passed to the array args as its elements. A Java application can accept any number of arguments from the command line.

This allows the user to specify configuration information when the application is launched. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort.java sorts lines in a file. To sort the data in a file named friends.txt, a user would enter : java Sort friends.txt When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt". The Echo example displays each of its command-line arguments on a line by itself : public class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } } The following example shows how a user might run Echo. User input is in italics. java Echo Drink Hot Java Drink Hot Java Note that the application displays each word — Drink, Hot, and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink, Hot, and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks. java Echo "Drink Hot Java" Drink Hot Java Q.2 Explain Type Casting? OR What is the process of Automatic Type Conversion? Ans.: It is sometimes necessary to convert a data item of one type to another type. For example when it is necessary to perform some arithmetic using data items of different types (so called mixed mode arithmetic). Under certain circumstances Type conversion can be carried out automatically, in other cases it must be "forced" manually (explicitly). Automatic Conversion : In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign: byte -> short -> int -> long -> float - > double. For example :

//64 bit long integer long myLongInteger; //32 bit long integer int myInteger; myLongInteger=myInteger; The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros. Explicit Conversion (Casting) : The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast : myInteger = (int) myLongInteger This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment. Java type casts have the following form: (T) N where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T. Q.3 What is an Object? Ans.: Objects are key to understand object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. So, anything that exists in real world is an object. In other words an object is a real life entity. Real-world objects share two characteristics: They all have identity, state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. Real-world objects vary in complexity. e.g. your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). Some objects, in turn, will also contain other objects. These real-world observations all translate into the world of objectoriented programming. A software Object. Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's

methods is known as data encapsulation — a fundamental principle of objectoriented programming. Consider a bicycle, for example: A Bicycle Modeled as a Software Object By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. Q.4 What is a Class? Ans.: In the real world, you'll often find many individual objects all of the same kind. All the objects that have similar properties and similar behavior are grouped together to form a class. In other words we can say that a class is a user defined data type and objects are the instance variables of class. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created. The following Bicycle class is one possible implementation of a bicycle : class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void printStates() { System.out.println("cadence:"+cadence+"speed:"+speed+" gear:"+gear); } } The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world. You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods : class BicycleDemo {

public static void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changeCadence(50); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.changeGear(2); bike2.changeCadence(40); bike2.changeGear(3); bike2.printStates(); } } The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles : Cadence : 50 speed : 10 gear : 2 Cadence : 40 speed : 20 gear : 3 Q.5 How many types of variables are available in Java? Ans.: A variable is a place in memory where we can store a value. The Java programming language defines the following kinds of variables : Instance Variables (Non-Static Fields) : Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. Class Variables (Static Fields) : A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Local Variables : Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Q.6 Explain Data Types in Java?

OR How many Primitive Data Types are there in Java? Ans.: The Java programming language is strongly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen : int gear = 1; Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are : byte : The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short : The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with int : The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else long : The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. float : The float data type is a single-precision 32-bit IEEE 754 floating point As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. double : The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. boolean : The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. char : The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.

Q.7 What are Default Values? Ans.: It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type The following chart summarizes the default values for the above data types. Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' string (or any object) null boolean false Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error. Q.8 Mention the different types of operators in Java? Ans.: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. The operators in the following table are listed according to precedence order Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. Operator Precedence Operators Precedence Postfix expr++ expr-- Unary ++expr --expr +expr -expr ~ ! Multiplicative * / % Additive + - Shift << >> >>> Relational < > <= >= instanceof Equality == != Operators Precedence Bitwise AND & Bitwise exclusive OR ^ Bitwise inclusive OR | Logical AND && Logical OR ||

Ternary ? : Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= Q.9 What are Enum Types and how they are helpful? Ans.: An enum type is a type whose fields consist of a fixed set of constants. Because they are constants, the names of an enum type's fields are in uppercase letters. In the Java programming language, you define an enum type by using the enum keyword. For example assuming that Day Enum has already been defined by user than you would specify a days-of-the-week enum type as : public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } } The output is : Mondays are bad.

Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best. Q.10 What are Boolean Methods? Ans.: Methods can return boolean values just like any other type, which is often convenient for hiding complicated tests inside methods. For example : public static boolean isSingleDigit (int x) { if (x >= 0 && x < 10) { return true; } else { return false; } } The name of this method is isSingleDigit. It is common to give boolean methods names that sound like yes/no questions. The return type is boolean, which means that every return statement has to provide a boolean expression. There is nothing wrong with returning it directly, and avoiding the if statement altogether: public static boolean isSingleDigit (int x) { return (x >= 0 && x < 10); } In main you can invoke this method in the usual ways : boolean bigFlag = !isSingleDigit (17); System.out.println (isSingleDigit (2)); The first line assigns the value true to bigFlag only if 17 is not a single-digit number. The second line prints true because 2 is a single-digit number. Yes, println is overloaded to handle booleans, too. The most common use of boolean methods is inside conditional statements if (isSingleDigit (x)) { System.out.println ("x is little"); } else { System.out.println ("x is big"); } □ □ □ Chapter-5 Declaration of Arrays Q.1 How Arrays are declared and initialized in Java? OR What is an Array and how it is declared and initialized? Ans.: An array is a group of contiguous or related data items that share a common name. For instance, we can define an array name sal to represent a set of salaries of a group of employees. A particular value is indicated by writing a number

called index number or subscript in brackets after the array name. For example : sal[10] represents the salary of the 10 employeeS. While the complete set of values is referred to as an array, the individual values are called elements. The arrays are of different types : One Dimensional (A list of items can be given one variable name using only one subscript and such a variable is called a single-subsubscripted variable or a onedimensional array.) Two Dimensional (Where a table of values will be stored and two subscripts are required to represent an element of array) Three Dimensional (Where many table of values will be stored and three subscripts are required to represent an element of an array) Creating an Array : It involves three steps : (1) Declaring the Array (2) Creating Memory Locations (3) Putting Values into the Memory Locations Declaring an Array : Arrays in Java are declared in one of the two forms : Form 1 type arrayname[]; Form 2 type[]arrayname; e.g. int number[]; int[] counter; Creating Memory Allocations : To create an array we use new operator : arrayname =new type[size]; e.g. number =new int[5]; Initialization of Array : The final step is to put values into the array created. arrayname[subscript]=value; e.g. number[0]=35; ………. ………... number[4]=55; Example of Two Dimensional Array : int a[][]=new int[3][3] ; creates a table that can store 9 integer values. Or int a[2][3]={0,0,0,1,1,1}; will initializes the elements of the first row to zero and the second row to one .

Docsity is not optimized for the browser you're using. In order to have a better experience please switch to Google Chrome, Firefox, Internet Explorer 9+ or Safari! Download Google Chrome