JAVA PROGAMMING MATERIAL

Size: px
Start display at page:

Download "JAVA PROGAMMING MATERIAL"

Transcription

1 JAVA PROGAMMING MATERIAL (as per autonomous syllabus) Prepared by, P. Kiran, Assistant Professor, CSE Department, QISCET.

2 :JAVA PROGRAMMING SYLLABUS: UNIT I: Introduction to OOP Need for Object Oriented Programming paradigm, Principles of OOP, Java Characteristics, Java program Compilation and Execution Process, Java Virtual Machine, Installation of JDK1.6. Java Basics Identifiers, Variables, Datatypes, Literals, Keywords, Operators, Expressions, Precedence and Associability, Primitive Type Conversion and Casting, Decision making and Looping statements. UNIT II: Classes and Objects- classes, Creating Objects, Methods, constructors, overloading methods and constructors, garbage collection, static keyword, this keyword, parameter passing, recursion, Arrays, Strings, Command line arguments. Inheritance: Types of Inheritance, Deriving classes using extends keyword, concept of overriding, super keyword, final keyword. UNIT III: Interfaces: Interfaces - Interfaces vs. Abstract classes, defining an interface, implementing interfaces, extending interfaces. Packages - Defining, Creating and Accessing a Package, Understanding CLASSPATH, Access protection. importing packages. UNIT IV: Exceptions - Introduction, Exception handling techniques-try...catch, throw, throws, finally block, user defined exception. Multithreading: Introduction, Differences between multi threading and multitasking, The main Thread, Creation of new threads, Thread priority, Multithreading- Using isalive() and join(), Synchronization, suspending and Resuming threads, Communication between Threads UNIT V: File Handling: Streams, Byte streams, Character streams and File streams. Networking: TCP, UDP, URL Connection Class, Inet Address Class, Socket Programming. Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet, types of applets, creating applets, passing parameters to applets, Applet to applet communication. UNIT VI: GUI Programming with Java - The AWT class hierarchy, Components and Containers, Introduction to Swing, Swing vs AWT, Hierarchy for Swing Components, Containers - JFrame, JApplet, JDialog, JPanel, Swing components- Jbutton, JLabel, JTextField, JTextArea, JRadio buttons, JList, JTable, Layout manager, executable jar file in Java. Event Handling - Events, Event sources, Event classes, Event Listeners, Delegation event model, handling mouse and keyboard events, Adapter classes, Inner classes. TEXT BOOK: 1. Herbert Schildt, Java The Complete Reference, 8 th edition, TMH. 1

3 UNIT-1 Introduction to OOP and Java Basics History of Java: Java is an efficient powerful Object-Oriented Programming language developed in the year of 1991 by James Gosling and his team members at Sun micro systems. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June The small team of sun engineers called Green Team. Initially Java is called with a name Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania etc. In 1995, Oak was renamed as "Java". Java is an island of Indonesia where first coffee was produced (called java coffee). Sun micro systems purchased by Oracle Corporation in the year of JDK (Java Development tool Kit) 1.0 released in (January 23, 1996). Java Version History There are many java versions that has been released. Current stable release of Java is Java SE JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan, 1996) 3. JDK 1.1 (19th Feb, 1997) 4. J2SE 1.2 (8th Dec, 1998) 5. J2SE 1.3 (8th May, 2000) 6. J2SE 1.4 (6th Feb, 2002) 7. J2SE 5.0 (30th Sep, 2004) 8. Java SE 6 (11th Dec, 2006) 9. Java SE 7 (28th July, 2011) 10. Java SE 8 (18th March, 2014) Where it is used?according to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows: 1. Desktop Applications such as acrobat reader, media player, antivirus etc. 2. Web Applications such as irctc.co.in, javatpoint.com etc. 3. Enterprise Applications such as banking applications. 4. Mobile 5. Embedded System 6. Smart Card 7. Robotics 8. Games etc. 2

4 Types of Java Applications There are mainly 4 type 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 *********** Need for Object Oriented Programming paradigm: Computer programs consist of two elements: code and data. Furthermore a program can be conceptually organized around its code or around its data. These are the two paradigms that govern how a program is constructed. 1) Procedure-Oriented Programming model. 2) Object-Oriented Programming model. Procedure Oriented Programming(POP): In the Procedure oriented programming model importance is not given to data but to functions as well as sequence of actions to be done. C, Pascal, Fortran etc are called procedure oriented programming languages. In POP a programmer uses procedures or functions to perform a task. When the programmer wants to write a program, he will first divide the task into separate sub tasks i.e as functions. In C programming several functions are controlled from a main() function. function1 main() method function2 function3 Even though POP is a efficient approach but if program size increases the Complexity (readability is difficult) also increased. In the POP approach there is no data hiding concept i.e security for the data is less. 3

5 Object Oriented Programming(OOP): In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. In the object oriented programming classes and objects are used inside programs. A class is a module or template contains data and methods ( functions) to achieve the task. The main task is divided into several modules, these modules are called classes, each class can perform some tasks for which several methods are written in a class. In the OOP approach we can achieve security for the data using data hiding concept. In java we can develop efficient programs using the concepts encapsulation, polymorphism and inheritance etc. class with main() method class1 class2 data methods data methods class3 data methods *********** Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP): Divided Into Importance Procedure Oriented Programming In POP, program is divided into small parts called functions. In POP, Importance is not given to data but to functions as well as sequence of actions to be done. Object Oriented Programming In OOP, program is divided into parts called objects. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach. Access Specifiers Data Moving POP does not have any access specifier. In POP, Data can move freely from function to function in the system. OOP has access specifiers named public, private, protected, etc. In OOP, objects can move and communicate with each other through member functions. 4

6 Expansion Data Access Data Hiding To add new data and function in POP is not so easy. In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. POP does not have any proper way for hiding data so it is less secure. OOP provides an easy way to add new data and function. In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data. OOP provides Data Hiding so provides more security. Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Examples Examples of POP are: C, VB, FORTRAN and Pascal. Examples of OOP are: C++, JAVA, VB.NET, C#.NET. Principles of OOP: *********** The object-oriented paradigm supports four major principles,they are also known as four pillars of the object-oriented paradigm. 1. Abstraction 2. Encapsulation 3. Inheritance 4. Polymorphism Abstraction: Abstraction means hiding the implementation details from the user and gives only functionality details. For example, when you drive your car you do not have to be concerned with the exact internal working of your car. What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Here the knowledge you have of your car is abstract. In java abstraction can be achieved using abstract class and interfaces. Encapsulation: Wrapping data(variables) and methods(code acting on data) within classes in combination with implementation hiding (through access control) is often called encapsulation. In java encapsulation can be achieved using classes. Using this encapsulation we can provide security for the data inside a class using object reference, this is called Data hiding. 5

7 Example: class Sample int a; float b; public void add() //body of method Inheritance: Inheritance in java is a mechanism in which one object acquires the properties and behaviors of parent object. It s essentially creating parent-child relationship between classes. In java, you will use inheritance mainly for code re-usability and maintainability. In java inheritance is also called as IS-A relation ship, and it can be achieved using extends key word. Example: class A //members of a class A class B extends A // members of class B Polymorphism: The word polymorphism came from two greek words poly meaning many and morphos meaning forms. Polymorphism represents the ability to assume several different forms. Polymorphism is the ability by which, we can create functions or reference variables which behaves differently in different programmatic context. In java language, polymorphism is essentially considered into two versions: Compile time polymorphism (static binding or method overloading) Runtime polymorphism (dynamic binding or method overriding) ****************

8 Java Characteristics (or) Features of java (or) Java Buzz words: There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand. 1. Simple 2. Object-Oriented 3. Platform independent 4. Secured 5. Robust 6. Architecture neutral 7. Portable 8. Dynamic 9. Interpreted 10. High Performance 11. Multithreaded 12. Distributed Simple According to Sun, Java language is simple because: syntax is based on C++ (so easier for programmers to learn it after C++). removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc. No need to remove unreferenced objects because there is Automatic Garbage Collection in java. Object-oriented Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour. Object-oriented programming(oops) is a methodology that simplify software development and maintenance by providing some rules. Basic concepts of OOPs are: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation. 7

9 Platform Independent A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides softwarebased platform. The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on the top of other hardware-based platforms. It has two components: Runtime Environment API(Application Programming Interface) Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platformindependent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA). Secured Java is secured because: No explicit pointer Java Programs run inside virtual machine sandbox Robust Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust. Architecture-neutral There are no implementation dependent features e.g. size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures. 8

10 Portable: We may carry the java bytecode to any platform. High-performance Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++) Distributed We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet. Multi-threaded A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multithreading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications etc. ****** ****** Java program Compilation and Execution Process: Sample java program: import java.lang.*; // package import section class Sample // creating a class public static void main(string args[]) // main() execution starts from here System.out.println( Hello world ); // writing Hello world on console Save the above program with an extension.java i.e Sample.java in a specific location. Compilation: for compilation of java program we use javac keyword. javac Sample.java Execution: After successful compilation of java program.class file will be created. This is called bytecode. for executing java program we use.class file name with java keyword as follows. Sample.java Compiler Sample.class JVM (java virtual Machine) Output ******* ******* 9

11 Java Virtual Machine(JVM): JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). The JVM performs following operations: Loads code,verifies code, Executes code and Provides runtime environment Internal Archietecture of JVM: Classloader: Classloader is a subsystem of JVM that is used to load class files. Class(Method) Area: Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. Heap: It is the runtime data area in which objects are allocated. Stack: Java Stack stores frames.it holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes. Program Counter Register: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. Native Method Stack: It contains all the native methods used in the application. Execution Engine: It contains A virtual processor Interpreter: Read byte code stream then execute the instructions. 10

12 Just-In-Time(JIT) compiler: It is used to improve the performance.jit compiles parts of the byte code that have similar functionality at the same time, and Hence reduces the amount of time needed for compilation. Here the term compiler refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. ****** ****** Installation of JDK: The JDK software has two different versions: a 32-bit Windows version and a 64-bit Windows version. Before you download the software, you will need to know which version of Windows you are using. If you don t already know what version of Windows you have, you can find out fairly quickly! On older systems find your Computer icon from the Start menu or on your desktop. Right-click on this icon and select Properties. You can then read the System Type to determine if you have a 32 or 64-bit operating system On Windows 7 you can open the Start menu and choose Computer from the list. On the Computer screen, click on the button that says System Properties, as seen below: 11

13 This will bring up a screen with information about your computer and your version of Windows. Look for a section titled System. This section will easily tell you what version of Windows you have installed next to the System Type label: Keep this information handy! We will use it to determine which version of the JDK to download. Downloading the JDK To download the Java Development Kit (JDK), launch your web browser (e.g. Internet Explorer) and goto address: This page shows many download options. The top of the page shows the most common JDK download options: For this course, you can select either JDK version 6 (which we have chosen in the textbook) or JDK version 7 (which is newly released). Select the JDK download button for the corresponding version further down on the screen: 12

14 Or if you prefer JDK 6.0 (1.6): The Download button will open another page which will list the various JDK installation files. You must choose Accept License Agreement in order to continue with the download and installation. Once you have accepted the license agreement, you will need to choose a file to download. The Windows files are at the bottom of the screen. If you have a 32-bit Windows system, you will choose the Windows x86 file. If you have a 64-bit Windows system, you will need to choose the Windows x64 file. As soon as you click to download the file, a pop-up window will appear asking you to either Save or Run the program. The look of this window will depend on what version of Windows and which Internet browser you are using to download the file. The following screenshots are from Mozilla Firefox and Internet Explorer: 13

15 Select Save File or Save to save the file to a location on your local hard drive. You can save it to your Desktop or some other file folder. Remember this location so you can find it later! Oracle updates the exact version of the JDK frequently. Our examples show JDK version (6.0.29), but keep in mind that the version available to you at the time of download will likely be different! Or you may choose JDK 1.7.X (7.0.X) if you prefer. Once the file is saved, use your Windows Explorer to find and run the program by doubleclicking in it. Depending on your version of Windows and security settings you may get a security popup as shown below. Click on Run to continue. When setup is launched you should see the following screen: This is the first screen in the install process. Click Next to continue. 14

16 This next screen lists all of the possible JDK options that can be installed. Since we will be covering the basics of Java in this course, you can just accept the defaults and simply click on the Next button to continue. There is no need to make any changes on this screen. The next screen will display a simple progress bar while the JDK files are being installed. This process could take anywhere from seconds to minutes, depending on the speed of your computer. 15

17 When the JDK is finished installing, the installation program will install the JRE files. The screen above will allow you to choose the directory where the JRE will be located. We recommend that you allow the files to install in the default directory, as shown below. Once you choose the Next button, the installation will display another progress bar. This will show the progress of the installation of the JRE files. The next screen will simply show the progress of your JRE installation. In this first step, the installation program will automatically download additional files from the Oracle website. This is a large program and will take some time! 16

18 At this point, the installation of the JDK files is complete. When you click on the Finish button on this screen, a browser window will appear, displaying registration information for Java. Registration for the JDK software is optional and is not necessary for the completion of this course. If you choose not to register, simple close this window. Congratulations! You have finished the installation of the JDK and JRE in your Windows computer. ****** ****** 17

19 Java Basics : Identifiers: Variables: Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not begin with a number, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are: AvgTemp count a4 $test this_is_ok Invalid variable names include: 2count high-temp Not/ok 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. 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],... ; 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 = ; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. Types of Variable: There are three types of variables in java: local variable: declared inside the method is called local variable. instance variable: declared inside the class but outside the method, is called instance variable. It is not declared as static. static variable: declared as static is called static variable. It cannot be local. Example: class A int data=50;//instance variable static int m=100;//static variable void method() int n=90;//local variable 18

20 Data types: Data types represent the different values to be stored in the variable. In java, there are two types of data types: o Primitive data types o Non-primitive data types Data Type Default Value Default size Range boolean false 1 bit - char '\u0000' 2 byte 0 to 65,536 byte 0 1 byte 128 to 127 short 0 2 byte 32,768 to 32,767 int 0 4 byte 2,147,483,648 to 2,147,483,647 long 0L 8 byte 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 0.0f 4 byte 1.4e045 to 3.4e+038 double 0.0d 8 byte 4.9e 324 to 1.8e+308 Why char uses 2 byte in java and what is \u0000? It is because java uses Unicode system than ASCII code system. The \u0000 is the lowest range of Unicode system. To get detail explanation about Unicode visit next page. 19

21 Example on variables: class Simple public static void main(string[] args) Literals: int a=10; int b=10; int c=a+b; float f1=10.25f; double d= ; char ch= a ; boolean b1=true; boolean b2=false; System.out.println( int c= +c); System.out.println( float f1= +f1); System.out.println( double d = +d); System.out.println( char ch = +ch); System.out.println( boolean b1= + b1); System.out.println( boolean b2= + b2); 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"; 20

22 In java we have some escape sequences. Keywords: There are 49 reserved keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used as names for a variable,class, or method. The keywords const and goto are reserved but not used. In the early days of Java, several other keywords were reserved for possible future use. However, the current specification for Java only defines the keywords shown above. The assert keyword was added by Java 2, version 1.4 In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these words for the names of variables, classes, and so on. 21

23 Operators: 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 Boolean Logical Operators 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: Operator Result + Addition Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment = Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment Decrement The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int. Example program: class Test public static void main(string args[]) int a = 10; int b = 20; int c = 25; int d = 25; System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); System.out.println("c % a = " + (c % a) ); System.out.println("a++ = " + (a++) ); 22

24 System.out.println("b-- = " + (a--) ); // Check the difference in d++ and ++d System.out.println("d++ = " + (d++) ); System.out.println("++d = " + (++d) ); This will produce the following result: a + b = 30 a - b = -10 a * b = 200 b / a = 2 b % a = 0 c % a = 5 a++ = 10 b-- = 11 d++ = 25 ++d = 27 Compound assignment: Compound assignment opaerators are +=, -=, *=, /=, %= Examples: int a=10; a=a+10; (or) Relational Operators: int a=10; a+=10; int a=20; a=a/10; (or) int a=20; a/=10; The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here: Operator Result == Equal to!= Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to The outcome of these operations is a boolean value. The relational operators are most frequently used in the expressions that control the if statement and the various loop statements. Any type in Java, including integers, floating-point numbers, characters, and Booleans can be compared using the equality test, ==, and the inequality test,!=. int a = 4; int b = 1; boolean c = a < b; // c is false Example program: class Test public static void main(string args[]) int a = 10; int b = 20; 23

25 System.out.println("a == b = " + (a == b) ); System.out.println("a!= b = " + (a!= b) ); System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); Output: a == b = false a!= b = true a > b = false a < b = true b >= a = true b <= a = false Bit wise operators: Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following table: Operator Result ~ Bitwise unary NOT & Bitwise AND Bitwise OR ^ Bitwise exclusive OR >> Shift right >>> Shift right zero fill << Shift left &= Bitwise AND assignment = Bitwise OR assignment BITWISE LOGICAL OPERATORS The bitwise logical operators are &,, ^, and ~. The bitwise operators are applied to each individual bit within each operand. A B A B A & B A ^ B ~A The Bitwise NOT Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand. For example, becomes (after the NOT operator is applied.) The Bitwise AND The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases. Here is an example: 24

26 Left Shift & The Bitwise OR The OR operator,, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here: The Bitwise XOR The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise, the result is zero ^ The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has this general form: value << num Here, num specifies the number of positions to left-shift the value in value. That is, the << moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right. byte a = 64, b; int i; i = a << 1; b = (byte) (a << 2); After shifting operation i =128 and b=0 ( because byte takes only 8-bits) a<<1 : a is left shifted by one position a=(64) i=(a<<1) a<<2 : a is left shifted by 2 positions a=(64) b=(byte)(a<<2)

27 Right Shift The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form is shown here: value >> num Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves all of the bits in the specified value to the right the number of bit positions specified by num. The following code fragment shifts the value 32 to the right by two positions, resulting in a being set to 8: int a = 32; a = a >> 2; // a now contains 8 a>>2 : a is right shifted by two positions a= a=a>> Bitwise Operator Assignments: All of the binary bitwise operators have a shorthand form similar to that of the algebraic operators, which combines the assignment with the bitwise operation. For example, the following two statements, which shift the value in a right by four bits, are equivalent: a = a >> 4; a >>= 4; Likewise, the following two statements, which result in a being assigned the bitwise expression a OR b, are equivalent: a = a b; a = b; Example program: class OpBitEquals public static void main(string args[]) int a = 1; int b = 2; int c = 3; a = 4; b >>= 1; c <<= 1; a ^= c; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); output : a = 3 b = 1 c = 6 26

28 Boolean Logical operators: The Boolean logical operators operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. Operator Result & Logical AND Logical OR ^ Logical XOR (exclusive OR) Short-circuit OR && Short-circuit AND! Logical unary NOT &= AND assignment = OR assignment ^= XOR assignment == Equal to!= Not equal to?: Ternary if-then-else The logical Boolean operators, &,, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical! operator inverts the Boolean state:!true == false and!false == true. The following table shows the effect of each logical operation: Short-Circuit Logical Operators(&&, ): Java provides two interesting Boolean operators not found in many other computer languages. These are secondary versions of the Boolean AND and OR operators, and are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. Example: class Test public static void main(string args[]) int a=10,b=30; if(a<10 && b<40) //false System.out.println( Hello ); 27

29 Output: Hai The? Operator: if(a>5 b>40) //true System.out.println( Hai ); Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. The? has this general form: expression1? expression2 : expression3 In the above form expression1 results a Boolean value either true or false. If it is true expression2 evaluated otherwise epression2 evaluated. Example: class Ternary public static void main(string args[]) int i, k; i = 10; k = i < 0? -i : i; System.out.print("Absolute value of "); System.out.println(i + " is " + k); Output : Absolute value of i is 10 Operator Precedence: Bellow table shows the order of precedence for Java operators, from highest to lowest. 28

30 This expression first adds 3 to b and then shifts a right by that result. That is, this expression can be rewritten using redundant parentheses like this: a >> (b + 3) However, if you want to first shift a right by b positions and then add 3 to that result, you will need to parenthesize the expression like this: (a >> b) + 3 The given expression a 4 + c >> b & 7 can be evaluated as follows (a (((4 + c) >> b) & 7)) ********** *********** Typecasting:( primitive type conversion): Typecasting means converting one data type to another data type. Typecasting can be done in two ways 1. Implicit typecasting 2. Explicit typecasting Implicit typecasting: Compliler perform implicit typecasting automatically when smaller data type value into larger data type. In implicit type casting there is no loss of information. Implicit typecasting also called as widening or up casting. Example: int n= a ; System.out.println(n); //97 byte short char int long float double Explicit typecasting: Programmer performs explicit typecasting when larger data type value into smaller data type. In explicit type casting there may be chance of loss of information. Implicit typecasting also called as narrowing or down casting. Example: double d=10.5; int n=(int)d; // n becomes 10 byte short int long float double char 29

31 Decision making and Looping statements: if-else: General form of if-else is if ( condition ) // true action else // false action In the above general form condition must be Boolean type either true or false. Example: int a=10,b=20; if (a<b) System.out.println( a is smaller than b ); // executes else System.out.println( a is larger than b ); 30

32 Nested if- else: switch: int a=10,b=20,c=30; if (a<b && a<c) System.out.println( a is largest ); // executes else if( b<a && b<c ) System.out.println( b is largest ); else System.out.println( c is largest ); The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. Syntax: switch(expression) case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional... default: //code to be executed if all cases are not matched; Example: int choice=2; switch(choice) case 1: System.out.println( this is case 1 ); break case 2: System.out.println( this is case 2 ); break; case 3: System.out.println( this is case 3 ); break; Output: this is case 2 for loop: default: System.out.println( this is default case ); The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loop in java. o o o Simple For Loop For-each or Enhanced For Loop Labeled For Loop 31

33 Simple for Loop The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value. Syntax: for(initialization;condition;incr/decr) //code to be executed Example: class ForExample public static void main(string[] args) for(int i=1;i<=10;i++) System.out.print(i+ ); for-each Loop The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined variable. Syntax: for(type var:array) //code to be executed Example: class ForEachExample public static void main(string[] args) int arr[]=12,23,44,56,78; for(int i:arr) 32

34 System.out.println(i+ ); Labeled for Loop We can have name of each for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop. Normally, break and continue keywords breaks/continues the inner most for loop only. Syntax: labelname: for(initialization;condition;incr/decr) //code to be executed Example: class LabeledForExample public static void main(string[] args) aa: for(int i=1;i<=3;i++) bb: for(int j=1;j<=3;j++) if(i==2&&j==2) break aa; System.out.println(i+" "+j); Output:

35 While Loop: The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop. Syntax: while(condition) //code to be executed Example: class WhileExample public static void main(string[] args) int i=1; while(i<=10) System.out.print(i+ ); i++; Output: do-while Loop: The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop. The Java do-while loop is executed at least once because condition is checked after loop body. Syntax: do //code to be executed while(condition); Example: class DoWhileExample public static void main(string[] args) int i=1; do System.out.print(i); i++; while(i<=10); Output: 34

36 break Statement: The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. Syntax: Example: jump-statement; break; class BreakExample public static void main(string[] args) for(int i=1;i<=10;i++) if(i==5) break; System.out.print(i); Output: continue Statement: The Java continue statement is used to continue loop. It continues the current flow of the program and skips the remaining code at specified condition. In case of inner loop, it continues only inner loop. Syntax: Example: jump-statement; continue; class ContinueExample public static void main(string[] args) for(int i=1;i<=10;i++) if(i==5) continue; System.out.print(i); Output: ******* ********** 35

37 UNIT- 2 Classes, Objects and Inheritance Syllabus: Classes and Objects- classes, Creating Objects, Methods, constructors, overloading methods and constructors, garbage collection, static keyword, this keyword, parameter passing, recursion, Arrays, Strings, Command line arguments. Inheritance: Types of Inheritance, Deriving classes using extends keyword, concept of overriding, super keyword, final keyword. Class: A class is a group of objects that has common properties. It is a template or blueprint from which objects are created. Simple classes may contain only code or only data, most real-world classes contain both. A class is declared by use of the class keyword. The general form of a class is class classname type instance-variable1; type instance-variable2; //. type instance-variablen; type methodname1(parameter-list) // body of method type methodname2(parameter-list) // body of method //... type methodnamen(parameter-list) // body of method The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. Simple Class like as bellow class Box double width; double height; double depth; 1

38 In the above, a class defines a new type of data. In this case, the new data type is called Box. You will use this name to declare objects of type Box. a class declaration only creates a template; it does not create an actual object. For creating a Box object we use, Box mybox = new Box(); // create a Box object called mybox Here mybox will be an instance of Box. To acces variables, methods inside a class we have to use.(dot) operator. The dot operator links the name of the object with the name of an instance variable. to assign the width variable of mybox the value 100, you would use the following statement: mybox.width=100; Example: class Box double width; double height; double depth; class BoxDemo public static void main(string args[]) Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); The above program must save with BoxDemo.java ( because BoxDemo contains main()) After compiling the program two class files are created one is Box.class and other one is BoxDemo.class At the time of running BoxDemo.class file will be loaded by JVM For compilation: javac BoxDemo.java For Running: java BoxDemo Output: Volume is

39 We can create multiple objects for the same class Example Objects: class Box double width; double height; double depth; class BoxDemo public static void main(string args[]) Box mybox1 = new Box(); Box mybox1 = new Box(); double vol1,vol2; mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; vol1 = mybox1.width * mybox1.height * mybox1.depth; mybox1.width = 10; mybox1.height = 15; mybox1.depth = 5; vol2= mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume of mybox1 is " + vol1); System.out.println("Volume of mybox2 is " + vol2); Output Volume of mybox1 is Volume of mybox2 is Class is a template or blueprint from which objects are created. So object is the instance(result) of a class. for creating objects we have to use following code. Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object Here new keyword is allocating memory of Box object. 3

40 Assigning Object Reference Variables: For example see the following code Box b1 = new Box(); Box b2 = b1; In the above code b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. Methods: ****** ******* In java, a method is like function i.e. used to expose behavior of an object. The advantages of methods are code reusability and code optimization This is the general form of a method: type name(parameter-list) // body of method Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value; Here, value is the value returned. 4

41 Example program for usage of method: class Box double width; double height; double depth; void volume() // method double vol=width*height*depth; System.out.println("Volume is " + vol); class BoxDemo public static void main(string args[]) Box mybox = new Box(); mybox.width = 10; mybox.height = 20; mybox.depth = 15; mybox.volume(); Output: Volume is Example program for return a value from method : class Box double width; double height; double depth; double volume() // method return type is double return width*height*depth; class BoxDemo public static void main(string args[]) Box mybox = new Box(); mybox.width = 10; mybox.height = 20; mybox.depth = 15; double vol= mybox.volume(); System.out.printlln( volume is + vol); Output: Volume is

42 Example program for method with parameters: class Values void add(int a,int b) int c=a+b; System.out.printlln( addition of a, b is +c); class Addition public static void main(string args[]) Addition ad=new Addition(); ad.add(10,20); Output: addition of a, b is 30 Returning values from a method: class Values void add(int a,int b) c=a+b; return c; class Addition public static void main(string args[]) int res; Addition ad=new Addition(); res=ad.add(10,20); System.out.printlln( addition of a, b is +res); Output: addition of a, b is 30 6

43 Constructors: A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Constructors do not any return type, not even void. This is because the implicit return type of a class constructor is the class type itself. Example: class Addition Addition() System.out.println( This is Default constructor ); class ConstructorDemo public static void main(string args[]) Addition ad=new Addition(); Output: This is Default constructor Now we can understand why the parentheses are needed after the class name. What is actually happening is that the constructor for the class is being called. Thus, in the line Addition ad=new Addition(); new Addition( ) is calling the Addition( ) constructor. When we do not explicitly define a constructor for a class, then Java creates a default constructor for the class. Parameterized Constructors: We can pass parameters to the constructor class Addition Addition(int a,int b) int c; c=a+b; System.out.println( Tha addition of a, b is ); System.out.println(c); 7

44 Method Overloading: class ParameterConstructor public static void main(string args[]) Addition ad=new Addition(10,20); Output: Tha addition of a, b is 30 ****** ******* In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. These methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. Method overloading is also called as Static binding or Compile time polymorphism or Early binding. display() display(int a) display(duble d) display(string s) Example for method overloading class Overload void dispaly() System.out.println("No parameters"); void display(int a) System.out.println("integer a: " + a); void display(double d) System.out.println("double d: " + d); void display(string s) System.out.println("String s:" + s); 8

45 class OverloadDemo public static void main(string args[]) OverloadDemo ob = new OverloadDemo(); ob.display(); ob. display(10); ob. display(10.325); ob. display( hello ); Output: No parameters integer a: 10 double d: String s: hello Constructor overloading: In addition to overloading normal methods, you can also overload constructor methods. In Java it is possible to define two or more constructors within the same class that share the same name, as long as their parameter declarations are different. Example class Display Dispaly() System.out.println("No parameters"); Dispaly(int a) System.out.println("integer a: " + a); Dispaly(double d) System.out.println("double d: " + d); Display(String s) System.out.println("String s:" + s); class OverloadDemo public static void main(string args[]) Display ds=new Display(); Display ds1=new Display(10); Display ds2=new Display(10.325); Display ds3=new Display( hello ); 9

46 Output: No parameters integer a: 10 double d: String s: hello Java Garbage Collection 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 o o 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. How can an object be unreferenced? There are many ways: o o o By nulling the reference By assigning a reference to another By annonymous object etc. 1) By nulling a reference: Employee e=new Employee(); e=null; 2) By assigning a reference to another: Employee e1=new Employee(); Employee e2=new Employee(); e1=e2;//now the first object referred by e1 is available for garbage collection 3) By annonymous object: new Employee(); 10

47 static keyword: It is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. We can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. Methods declared as static have several restrictions: They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. We can declare a static block which gets executed exactly once, when the class is first loaded. Example class UseStatic static int a = 3; static int b; static void display(string s) System.out.println( Static method invoked String s= +s); static System.out.println("Static block initialized."); b = a * 4; class StaticDemo public static void main(string args[]) System.out.println( static variable a= + UseStatic.a); System.out.println( static variable b= +UseStatic.b); UseStatic. Display( JAVA ); Ouput: Static block initialized. static variable a= 3 static variable b= 12 static method invoked String s= JAVA 11

48 this keyword: In java, this is a reference variable that refers to the current object. Usage of this keyword Here some usages of this keyword. 1. To refer current class instance variable. 2. To Invoke current class constructor. To refer current class instance variable: If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. class Student int id; String name; Student10(int id,string name) this.id = id; this.name = name; void display() System.out.println(id+" "+name); public static void main(string args[]) Student s1 = new Student10(111,"Karan"); Student s2 = new Student10(321,"Aryan"); s1.display(); s2.display(); Output: 111 Karan 321 Aryan To invoke current class constructor The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor. Example: class Student1 int id; String name; Student1() System.out.println("default constructor is invoked"); Student1(int id,string name) this ();//it is used to invoked current class constructor. this.id = id; 12

49 this.name = name; void display() System.out.println(id+" "+name); public static void main(string args[]) Student1 e1 = new Student13(111,"karan"); Student1 e2 = new Student13(222,"Aryan"); e1.display(); e2.display(); Output: default constructor is invoked default constructor is invoked 111 Karan 222 Aryan ********** ********* parameter passing techniques: call by value (or) pass by value call by reference (or) pass by reference Call by value: In call by value we are passing only value to the method. If we perform any changes inside method that changes will not reflected to main method. Example: class CallByVal public static void main(string args[]) int x=20; System.out.println("Before method calling value= "+x); display(x); System.out.println("After method calling value= "+x); public static void display(int y) y=y+1; System.out.println("Inside method value= "+y); 13

50 Output: Before method calling value= 20 Inside method value= 21 After method calling value= 20 Call by reference: In call by reference we are passing reference i.e an object to the method. In this case, If we perform any changes inside method that changes will not reflected to main method. Example: class CallByRef int x; public static void main(string args[]) CalByRef c=new CalByRef(); c.x=20; System.out.println("Before method calling value= "+c.x); display(c); System.out.println("After method calling value= "+c.x); public static void display(calbyref m) m.x=m.x+1; System.out.println("Inside method value= "+m.x); Output: Before method calling value= 20 Inside method value= 21 After method calling value= 21 ******------****** 14

51 Recursion: Recursion is the process of method calling itself. A method calling itself is called as recursive method. The classic example of recursion is the computation of the factorial of a number. class Factorial int fact(int n) if(n==1) return 1; else n*fact(n-1) ; class Recursion public static void main(string args[]) Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); Output: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 Recursion process of fact(5) is given bellow. ******------****** 15

52 Arrays: An array is a group of similar data elements that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. The advantage of an array is code optimization and random access. Types of Array in java There are two types of array. o Single Dimensional Array o Multidimensional Array Single Dimensional Array Syntax for declare an array datatype[] arr; (or) datatype []arr; (or) datatype arr[]; Instantiation of an Array arr=new datatype[size]; Example class Testarray public static void main(string args[]) int a[]=new int[3]; a[0]=10; a[1]=20; a[2]=70; for(int i=0;i<a.length;i++) System.out.println(a[i]); Output:

53 Declaration, Instantiation and Initialization of an Array: datatype arr[]=val1,val2,val3, ;//declaration, instantiation and initialization Example: class Testarray1 public static void main(string args[]) int a[]=33,3,4,5; for(int i=0;i<a.length;i++) System.out.print(a[i]+ ); Output: Multidimensional array data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array datatype[][] arrayrefvar; (or) datatype [][]arrayrefvar; (or) datatype arrayrefvar[][]; (or) datatype []arrayrefvar[]; To instantiate Multidimensional Array int[][] arr=new int[3][3];//3 row and 3 column To initialize Multidimensional Array arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4;.arr[2][2]=9; Example: class Testarray3 public static void main(string args[]) int arr[][]=1,2,3,2,4,5,4,4,5; for(int i=0;i<3;i++) for(int j=0;j<3;j++) System.out.print(arr[i][j]+" "); System.out.println(); Output: ****** ****** 17

54 Strings: Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.string class is used to create string object. Strings are immutable in nature, i.e once an object created that object doesn t allow any changes to it. String is basically an object that represents sequence of char values. An array of characters works same as java string. For example: char[] ch='j','a','v','a'; String s=new String(ch); is same as: String s="java"; There are two ways to create String object: 1. By string literal 2. By new keyword String Literal Java String literal is created by using double quotes. For Example: String s="welcome"; The advantage of string literal usage is memory efficiency. By new keyword String s=new String("Welcome"); Example: class StringExample public static void main(string args[]) String s1="java";//creating string by java string literal char ch[]='s','t','r','i','n','g','s'; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); Output java strings example 18

55 String handling methods: S.N Method name General form Example 1 length() int length( ) String s = new String( hello ); System.out.println(s.length()); 2 charat( ) char charat(int where) char ch; 3 getchars( ) void getchars (int sourcestart, int sourceend, char target[ ], int targetstart) 4 equals( ) boolean equals(object str) 5 equalsignorecase( ) boolean equalsignorecase (String str) ch = "abc".charat(1); String s = "This is a demo of the getchars method."; int start = 10; int end = 14; char buf[] = new char[10]; s.getchars(start, end, buf, 0); System.out.println(buf); 6 substring( ) String substring(int startindex) String substring(int startindex, int endindex) 7 concat( ) String concat(string str) String s1 = "one"; String s1 = "Hello"; String s2 = "hello"; System.out.println( s1 and s2 are equal " +s1.equals(s2)); System.out.println("s1 and s2 are equal" +s1.equalsignorecase(s4)); String s1= hello java ; System.out.println(substring(1,4)); String s2 = s1.concat("two"); String s = "Hello".replace('l', 'w'); 8 replace( ) String replace(char original, char replacement) 9 trim( ) String trim( ) String s = " Hello World "; 10 tolowercase( ) touppercase( ) String tolowercase( ) String touppercase( ) System.out.println(s.trim()); String s1 = " HELLO"; String s2= hello ; System.out.println(s1.toLowerCase( )); System.out.println(s2.toUpperCase( )); Example program String handling methods: class StringDemo1 public static void main(string args[]) String s1="hello qiscet"; String s2="hello QISCET"; System.out.println("length of string s1= "+s1.length()); System.out.println("index of 'o' is: "+s1.indexof('o')); System.out.println("String s1 in Uppercase: "+s1.touppercase()); System.out.println("String s1 in Uppercase: "+s2.tolowercase()); System.out.println("s1 equals to s2?: "+s1.equals(s2)); System.out.println("s1 is equal to s2 after ignoring case: +s1.equalsignorecase(s2)); int result=s1.compareto(s2); if(result==0) 19

56 System.out.println("s1 is equals to s2"); else if(result>0) System.out.println("s1 is greater than s2"); else System.out.println("s1 is smaller than s2"); System.out.println("character at index of 6 in s1: "+s1.charat(6)); String s3=s1.substring(2,8); System.out.println("substring s3 in s1 is: "+s3); System.out.println("repalcing 'e' with 'a' in s1: "+s1.replace('e','a')); String s4=" qiscet "; System.out.println("string s4: "+s4); System.out.println("string s4 after trim: "+s4.trim()); Output: StringBuffer: ******* ******* StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. General form of StringBuffer StringBuffer sb=new StringBuffer( Hello World ); StringBuffer class exists in java.lang package. StringBuffer is immutable that means, any changes performed to the StringBuffer object that changes will reflect to object. 20

57 S. N StringBuffer Methods: Method name General form Example 1 length( ) int length( ) StringBuffer sb = newstringbuffer("hello"); 2 capacity( ) int capacity( ) System.out.println("buffer = " + sb); System.out.println("length="+sb.length()); System.out.println("capacity="+ sb.capacity()); 3 ensure void ensurecapacity sb.ensurecapacity(30)); Capacity( ) (int capacity) 4 setlength( ) void setlength(int len) StringBuffer sb = new StringBuffer("Hello"); 5 charat( ) char charat(int where) 6 setcharat( ) void setcharat(int where, char ch) 7 getchars( ) void getchars(int sourcestart, int sourceend, char target[ ], int targetstart) 8 append() StringBuffer append(string str) StringBuffer append(int num) 9 insert( ) StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charat(1)); sb.setcharat(1, 'i'); sb.setlength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charat(1)); StringBuffer sb=new StringBuffer("This is a demo of the getchars method."); int start = 10; int end = 14; char buf[] = new char[10]; sb.getchars(start, end, buf, 0); System.out.println(buf); StringBuffer sb = new StringBuffer(40); s = sb.append("is a number"); System.out.println(s); StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); 10 reverse( ) StringBuffer reverse( ) StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); 11 delete( ) and deletecharat( ) StringBuffer delete(int startindex, int endindex) StringBuffer deletecharat(int loc) 12 replace( ) StringBuffer replace(int startindex, int endindex, String str) 13 substring( ) String substring(int startindex) String substring(int startindex, int endindex) StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deletecharat(0); System.out.println("After deletecharat: " + sb); StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); StringBuffer sb = new StringBuffer( hello java ); String s= substring(1,4); System.out.println(s); ****** ******* 21

58 Command line arguments: A command-line argument is the information that directly follows the program s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy they are stored as strings in the String array passed to main( ). Forexample, class CommandLine public static void main(string args[]) for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " +args[i]); Compilation and Execution: javac CommandLine.java java CommandLine this is a test Output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1 ******* ******** 22

59 INHERITANCE Inheritance: Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. One class acquiring or inheriting the properties of another class is called inheritance. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When we inherit from an existing class, we can reuse methods and fields of parent class, and add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. Using inheritance we can achieve code reusability and method overriding. A class that is inherited is called a Super class or Parent class or Base class. The class that does the inheriting is called a Sub class or Child class or Derived class In java inheritance can be achieved by using extends keyword. General form of inheritance is class Parent // members of parent class Child extends Parent /*members of Child + members of parent*/ Parent Child extends The extends keyword indicates that,making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. Once Child class extends Parent class we can access members of Parent class by object of Child class. In the above general form members inside Parent class are inherited into Child class. Here members mean variables and methods inside a class. Example: class Parent public void m1() System.out.println("parent method m1");

60 class Child extends Parent public void m2() System.out.println("child method m2"); class InheritDemo public static void main(string args[]) // creating object for Child class Child c=new Child(); c.m1(); c.m2(); //creating object for parent class Parent p=new Parent(); p.m1();// we can only access m1 but not m2. Output: parent method m1 child method m2 parent method m1 In java we have different types of inheritance Simple inheritance (or) Single inheritance Multi level inheritance Multiple inheritance ( not supported at class level ) Hierarchical inheritance Note: In java Multiple inheritance is not supported at class level but it can be achieved by using interfaces.

61 Simple inheritance: Only one class acquiring the properties of another class. Example: class A public void m1() System.out.println("A class method m1"); class B extends A public void m2() System.out.println("B class method m2"); class SimpleInheritance public static void main(string args[]) B b=new B(); b.m1(); b.m2(); Output: A class method m1 B class method m2 Multilevel inheritance: class A public void m1() System.out.println("A class method m1"); class B extends A public void m2() System.out.println("B class method m2");

62 class C extends B public void m3() System.out.println("C class method m3"); class MultiLevelInheritance public static void main(string args[]) C c=new C(); c.m1(); c.m2(); c.m3(); Output: A class method m1 B class method m2 C class method m3 Hierarchical inheritance: class A public void m1() System.out.println("A class method m1"); class B extends A public void m2() System.out.println("B class method m2"); class C extends A public void m3() System.out.println("C class method m3"); class HierarchicalInheritance public static void main(string args[]) B b=new B(); C c=new C();

63 b.m1(); b.m2(); c.m1(); c.m3(); Output: A class method m1 B class method m2 A class method m1 C class method m3 Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java at class level. 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. class A void msg() System.out.println("Hello"); class B void msg() System.out.println("Welcome"); class C extends A,B //suppose if it were public Static void main(string args[]) C obj=new C(); obj.msg();//now which msg()method would be invoked? ***********

64 Method Overriding: If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding 1. Used to provide specific implementation of a method that is already provided by its super class. 2. Used for runtime polymorphism Rules for Java Method Overriding 1. Method must have same name as in the parent class 2. Method must have same parameter as in the parent class. 3. must be IS-A relationship (inheritance). 4. Method can t be static Example: class Bank // ROI means Rate Of Interest int getroi() return 0; class SBI extends Bank int getroi() return 8; class ICICI extends Bank int getroi() return 7; class OverrideBank public static void main(string args[]) SBI s=new SBI(); ICICI i=new ICICI(); System.out.println("SBI ROI(%):"+s.getROI()); System.out.println("ICICI ROI(%):"+i.getROI()); Output: SBI ROI(%):8 ICICI ROI(%):7 ***********

65 super keyword: The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of java super Keyword super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor. To refer immediate parent class instance variable: class Parent String s; class Child extends Parent String s; void show(string s1,string s2) super.s=s1; s=s2; System.out.println("Parent string s: "+super.s); System.out.println("Child string s: "+s); class SuperMemberDemo public static void main(string args[]) Child c=new Child(); c.show("java","programming"); Output: Parent string s: java Child string s: programming To refer immediate parent class method: class Parent void m1() System.out.println("this is parent method m1()");

66 class Child extends Parent void showm1() //calling Parent m1 inside showm1() using super super.m1(); class SuperMethodDemo public static void main(string args[]) Child c=new Child(); c.showm1(); Output: this is parent method m1() To invoke immediate parent class constructor: class Parent Parent(String s) System.out.println("Hello from Parent: "+s); class Child extends Parent Child(String s1) super(s1); class SuperTest public static void main(string args[]) Child ch=new Child("Java"); Output: Hello from Parent: Java ***********

67 final keyword: The final keyword in java is used to restrict the user. The java final keyword can be used in many context. final can be: 1. variable 2. method 3. class final variable: If you make any variable as final, you cannot change the value of final variable (It will be constant). Example of final variable, There is a final variable speed limit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed. class Bike final int speedlimit=90;//final variable void run() speedlimit=400; // not allowed to change public static void main(string args[]) Bike obj=new Bike(); obj.run(); //end of class Output: Compile Time Error final method: If you make any method as final, you cannot override it. Example of final method class Bike final void run() System.out.println("running"); class Honda extends Bike void run()// not allowed to override System.out.println("running safely with 100kmph"); public static void main(string args[]) Honda h= new Honda(); h.run(); Ouput: Compile time error

68 final class: If you make any class as final, you cannot extend it. Example of final class final class Bike class Honda1 extends Bike // not allowed to extend void run() System.out.println("running safely with 100kmph"); public static void main(string args[]) Honda1 h= new Honda1(); h.run(); Ouput: Compile time error ***********

69 UNIT-3 Interfaces and Packages Syllabus: Interfaces: Interfaces - Interfaces vs. Abstract classes, defining an interface, implementing interfaces, extending interfaces. Packages - Defining, Creating and Accessing a Package, Understanding CLASSPATH, Access protection. Importing packages. abstract class: A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract methods, non-abstract methods (method with body), variables and constructor. Abstraction is a process of hiding the implementation details and showing only functionality to the user. It shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. Ways to achieve Abstraction There are two ways to achieve abstraction in java 1. Abstract class 2. Interface (fully abstraction) A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. abstract class A // may contain abstract and normal methods A method that is declared as abstract and does not have implementation is known as abstract method. abstract void print();//no implementation Example : abstract class Base abstract void print1(); void print2() System.out.println( Normal method ); 1

70 class Derived extends Base void print1() System.out.println("abstract method"); public static void main(string args[]) Derived obj = new Derived(); obj.print1(); obj.print2(); Output: Normal method abstract method **************** Interface: An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, Interface fields are public, static and final by default, and methods are public and abstract. Relationship between classes and interfaces a class extends another class, an interface extends another interface but a class implements an interface. 2

71 Implementing interface: interface implementation provided inside a class using implements keyword Example (Implementing interfaces): interface ISample int i=10; void display(); class Sample implements ISample public void display() System.out.println("display method i="+ i); class InterfaceDemo public static void main(string args[]) Sample s=new Sample(); s.display(); Output: display method i=10 Extending interfaces: interfaces can extended by another interface with extends keyword, but the extending interface implementation provided by a class by using implements keyword. Example (extending interfaces): interface ISample1 int i=10; void display1(); interface ISample2 extends ISample1 int j=20; void display2(); 3

72 class Sample1 implements ISample2 public void display1() System.out.println("display1 method i="+ i); public void display2() System.out.println("display2 method j="+ j); class InterfaceDemo1 public static void main(string args[]) Sample s=new Sample(); s.display1(); s.display2(); Output: display1 method i=10 display2 method j=20 Interface vs abstract class: Abstract class 1) Abstract class can have abstract and nonabstract methods. 2) Abstract class doesn't support multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. 4) Abstract class can have static methods, main method and constructor. 5) Abstract class can provide the implementation of interface. 6) The abstract keyword is used to declare abstract class. Interface Interface can have only abstract methods. Interface supports multiple inheritance. Interface has only static and final variables. Interface can't have static methods, main method or constructor. Interface can't provide the implementation of abstract class. The interface keyword is used to declare interface. 4

73 7) Example: abstract class Sample abstract void show(); Example: interface ISample void show(); ***************** Q: Is it possible an abstract class can implement interface? Answer: Yes, it is possible, An abstract class can implement any interface. But we can t create an object for an abstract class. So it is compulsory to extend abstract class by another class. Now by creating object for extending class, we can invoke members of abstract class. Example: interface ISample int i=10; void display(); abstract class Sample implements ISample public void display() System.out.println("display method i= "+ i); class SampleDemo extends Sample public static void main(string args[]) SampleDemo s=new SampleDemo(); s.display(); Output: display method i= 10 ***************** 5

74 Packages: A package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. User-defined packages that are created by programmer by using package keyword. package packname; Advantages of Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. Creating a package: The package keyword is used to create a package in java. //save as Simple.java package mypack; public class Simple public static void main(string args[]) System.out.println("Welcome to package"); 6

75 Compilation process of package program: Following is the procedure for compiling the program For example javac -d directory javafilename javac -d. Simple.java The -d specifies the destination where to put the generated class file. We can use any directory name d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use. (dot). To run java package program we need to use fully qualified name like packagename.javafile Example: mypack.simple to run the class. To compile and execute above simple package program: Compile: javac -d. Simple.java 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. (dot) represents the current folder. ******************* Importing or accessing packages: Generally if we want to access any class belongs to specific package, then it is compulsory to import package that contain class. Example: suppose if we want to access Scanner class, we have to import java.util package. import java.util.scanner; Similar to built-in package we have to import user defined packages. There are three ways to access the package from outside the package. 1. import package.*; 2. import package.classname; 3. fully qualified name. 7

76 Using packagename.*: If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. Example //save by A.java package pack; public class A public void msg() System.out.println("Hello"); //save by B.java package mypack; import pack.*; class B public static void main(string args[]) A obj = new A(); obj.msg(); Output: Hello Using packagename.classname: If you import package.classname then only declared class of this package will be accessible. Example //save by A.java package pack; public class A public void msg() System.out.println("Hello"); 8

77 //save by B.java package mypack; import pack.a; class B public static void main(string args[]) A obj = new A(); obj.msg(); Output: Hello Using fully qualified name: If we use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. Example //save by A.java package pack; public class A public void msg() System.out.println("Hello"); //save by B.java package mypack; class B public static void main(string args[]) // using fully classified name pack.a obj = new pack.a(); obj.msg(); Output: Hello 9

78 Access protection: There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: 1. private 2. default 3. protected 4. public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. For class we have two access modifiers i.e. public and default. The following diagram shows class member access. Example: package mypack1; public class Sample int a=10; // accessible within same package public int b=20; // accessible any where private int c=30; // we can t access outside of class protected int d=40; //only accessible by inherited class void print1() // accessible within same package System.out.println("this is default method"); public void print2()// accessible any where System.out.println("this is public method"); 10

79 private void print3() // we can t access outside of class System.out.println("this is private method"); protected void print4() // only accessible by inherited class System.out.println("this is protected method"); Note: Save as Sample.java package mypack2; import mypack1.*; class AccessModiefier extends Sample public static void main(string args[]) AccessModiefier ac=new AccessModiefier(); /*we can't access default and private members outside of package*/ System.out.println("default a="+ac.a); //Compile time error System.out.println("private c="+ac.c); //Compile time error ac.print1(); //Compile time error ac.print3(); //Compile time error /*can access public members and protected members(only by using inheritance) outside of package*/ System.out.println("public a="+ac.b); //Executes System.out.println("protected d="+ac.d); //Executes ac.print2(); //Executes ac.print4(); //Executes Note: save as AccessModiefier.java Compilation: javac d. Sample.java javac d. AccessModiefiers.java Execution: java mypack2.java Output: Compile time errors ********************** 11

80 Understanding CLASSPATH: Consider the following program. //save as Simple.java package mypack; public class Simple public static void main(string args[]) System.out.println("Welcome to package"); If we want to compile the above program in current working directory (Assume D:\packages) To Compile: D:\packages>javac d. Simple.java To run: D:\packages>javac mypack.simple Suppose if we want to compile the above program in some other directory (Assume C:\packages) To compile: D:\packages> javac -d C:\packages Simple.java To run: C:\packages>java mypack.simple To run this program from D:\packages directory, you need to set classpath of the directory where the class file resides. To set class path: D:\packages>set classpath=c:\packages;.; To run: D:\packages>java mypack.simple Another way to run this program by -classpath switch of java: D:\packages> java -classpath c:\packages mypack.simple Output: Welcome to package **************************** 12

81 UNIT-4 Exception handling and Multithreading Syllabus: Exceptions - Introduction, Exception handling techniques-try...catch, throw, throws, finally block, user defined exception. Multithreading: Introduction, Differences between multi threading and multitasking, The main Thread, Creation of new threads, Thread priority, Multithreading- Using isalive() and join(), Synchronization, suspending and Resuming threads, Communication between Threads Exception handling: The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. Exception: In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Generally exception is an abnormal condition. The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc. The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario: statement 1; statement 2; statement 3; statement 4; statement 5;//exception occurs statement 6; statement 7; statement 8; statement 9; statement 10; Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.

82 Hierarchy of Java Exception classes Types of Exception: There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception 3. Error Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions Examples: IOException, SQLException etc. Checked exceptions are checked at compile-time. Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Error: Error is irrecoverable Examples: OutOfMemoryError, VirtualMachineError, AssertionError etc.

83 Common scenarios where exceptions may occur: There are given some scenarios where unchecked exceptions can occur as follows: Where ArithmeticException occurs? If we divide any number by zero, there occurs an ArithmeticException. int a=50/0;//arithmeticexception Where NullPointerException occurs? If we have null value in any variable, performing any operation by the variable occurs an NullPointerException String s=null; System.out.println(s.length());//NullPointerException Where NumberFormatException occurs? The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException. String s="abc"; int i=integer.parseint(s);//numberformatexception Where ArrayIndexOutOfBoundsException occurs? If we are given any value in the wrong index, result ArrayIndexOutOfBoundsException as shown below: int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException Java Exception Handling Keywords There are 5 keywords used in java exception handling. 1. try 2. catch 3. finally 4. throw 5. throws

84 try-catch block: try block is used to enclose the code that might throw an exception. It must be used within the method. catch block is used to handle the Exception. It must be used after the try block only. We can use multiple catch block with a single try and try block must be followed by either catch or finally block. Syntax of try-catch try //code that may throw exception catch(exception_class_name ref) Problem without try-catch class Testtrycatch public static void main(string args[]) int data=50/0;//may throw exception System.out.println("rest of the code..."); Output: Exception in thread main java.lang.arithmeticexception:/ by zero In the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed). There can be 100 lines of code after exception. So all the code after exception will not be executed. Solution by try-catch class Testtrycatch 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...

85 Now, as displayed in the example, rest of the code is executed i.e. rest of the code... statement is printed. Internal working of java try-catch block The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: o o o Prints out exception description. Prints the stack trace (Hierarchy of methods where the exception occurred). Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed. **********************

86 Nested try block: The try block within a try block is known as nested try block. Why we use nested try block? Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntax: try // statements try // statements catch(exception e) catch(exception e) Example: class NestedTry public static void main(string args[]) try int a=args.length; int data=50/a; System.out.println("a= "+a); try if(a==1) int[] c=1; c[30]=101; catch(arrayindexoutofboundsexception e1) System.out.println(e1); catch(arithmeticexception e2) System.out.println(e2);

87 finally block: finally block is a block that is used to execute important code such as closing connection, stream etc. finally block is always executed whether exception is handled or not. finally block follows try or catch block. Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc. Usage of finally block: Case 1: Example where exception doesn't occur. class TestFinallyBlock public static void main(string args[]) try int data=25/5; System.out.println(data); catch(exception e) System.out.println(e);

88 finally System.out.println("finally block is always executed"); System.out.println("rest of the code..."); Test it Now Output: 5 finally block is always executed rest of the code... Case 2: Example where exception occurs and not handled. class TestFinallyBlock public static void main(string args[]) try int data=25/0; System.out.println(data); catch(nullpointerexception e) System.out.println(e); finally System.out.println("finally block is always executed"); System.out.println("rest of the code..."); Test it Now Output: finally block is always executed Exception in thread main java.lang.arithmeticexception:/ by zero

89 Case 3: example where exception occurs and handled. class TestFinallyBlock public static void main(string args[]) try int data=25/0; System.out.println(data); catch(arithmeticexception e) System.out.println(e); finally System.out.println("finally block is always executed"); System.out.println("rest of the code..."); Test it Now Output: Exception in thread main java.lang.arithmeticexception:/ by zero finally block is always executed rest of the code... *********************

90 throw keyword: The throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later. The syntax of throw keyword is given below. throw new Exception_Name("message ); Example: In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. class TestThrow static void validate(int age) if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); public static void main(string args[]) validate(13); System.out.println("rest of the code..."); Output: Exception in thread main java.lang.arithmeticexception:not valid *********************

91 throws keyword: The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used. Syntax of throws returntype methodname() throws exception_class_name //method code Example-1: import java.io.*; class Testthrows void m()throws IOException throw new IOException("device error");//checked exception void p() try m(); catch(exception e) System.out.println("exception handled"); public static void main(string args[]) Testthrows obj=new Testthrows(); obj.p(); System.out.println("normal flow..."); Test it Now Output: exception handled normal flow...

92 Example-2: import java.util.*; class ThrowsExceptionClass public static void main(string args[])throws InputMismatchException int a,b; Scanner s=new Scanner(System.in); System.out.println("Enter a, b values"); try a=s.nextint(); b=s.nextint(); catch(inputmismatchexception e) System.out.println(e); Output: Enter a, b values java.util.inputmismatchexception *********************** User defined Exception (or) Custom Exception: If we are creating our own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need. By the help of custom exception, we can have our own exception and message. If we want to create a user defied eeptio, that ust eteds Eeptio lass General form is class CustomExceptionName extends Exception CustomExceptionName(String s) super(s);//calling constructor of Exception class

93 Example class OwnException extends Exception OwnException(String s) super(s); class OwnExceptionDemo static void validate(int age)throws OwnException if(age<18) throw new OwnException("age is not valid"); else System.out.println("Welcome to vote"); public static void main(string args[]) try validate(13); catch(ownexception e) System.out.println(e); Output: OwnException: age is not valid *****************

94 Difference between throw and throws: Throw throw keyword is used to explicitly throw an exception. Checked exception cannot be propagated using throw only. throw is followed by an instance. throw is used within the method. We cannot throw multiple exceptions. Example: void m() throw new ArithmeticException("sorry"); throws throws keyword is used to declare an exception. Checked exception can be propagated with throws. throws is followed by class. throws is used with the method signature. We can declare multiple exceptions Ex: public void method()throws IOException,SQLException Example: void m()throws ArithmeticException //method code

95 Multithreading: Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and contextswitching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread. Multitasking: Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: o Process-based Multitasking(Multi processing) o Thread-based Multitasking(Multi threading) Process-based Multitasking (Multiprocessing) o Process of executing multiple tasks simultaneously where each task is a individual process. o This type of multitasking mostly used in Operating System level. o Example: Typing program in editor, listening audio songs and downloading files from internet simultaneously. Thread-based Multitasking (Multithreading) o Executing several tasks simultaneously or parallely where each task is a individual process in a single program or application. o Here each process is independent to each other there is no dependency. o Each individual process is called as Thread. o Example: Gmail Server Gmail Thread-1: Request from India Thread-3: Request from UK Thread-2: Request from US

96 Thread: A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area. Thread Life cycle: A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New (or) Born 2. Runnable (or) Ready 3. Running 4. Blocked (or) Non-Runnable 5. Dead (or) Terminated 1. Newborn State: When a thread object is created a new thread is born and said to be in Newborn state. 2. Runnable State: If a thread is in this state it means that the thread is ready for execution and waiting for the availability of the processor. If all threads in queue are of same priority then they are given time slots for execution in round robin fashion

97 3. Running State: It means that the processor has given its time to the thread for execution. A thread keeps running until the following conditions occurs a. Thread give up its control on its own and it can happen in the following situations i. A thread gets suspended using suspend() method which can only be revived with resume() method ii. A thread is made to sleep for a specified period of time using sleep(time) method, where time in milliseconds iii. A thread is made to wait for some event to occur using wait () method. In this case a thread can be scheduled to run again using notify () method. b. A thread is pre-empted by a higher priority thread 4. Blocked State: If a thread is prevented from entering into runnable state and subsequently running state, then a thread is said to be in Blocked state. 5. Dead State: A runnable thread enters the Dead or terminated state when it completes its task or otherwise terminates. ******************** The main Thread: When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins. Although the main thread is created automatically when our program is started, it can be controlled through a Thread object. To do so, we must obtain a reference to it by calling the method currentthread( ), which is a public static member of Thread. Its general form is shown here: static Thread currentthread( ) This method returns a reference to the thread in which it is called. Once we have a reference to the main thread, we can control it just like any other thread. class CurrentThreadDemo public static void main(string args[]) Thread t = Thread.currentThread(); // getting name of thread System.out.println("Current thread: " + t.getname()); // change the name of the thread t.setname("my Thread"); System.out.println("name of Thread:" + t.getname());

98 for(int n = 5; n > 0; n--) System.out.println(n); Output: Current thread: main name of Thread:My Thread ******************** Creation of new threads: For creating threads we have two ways 1. By extending Thread class 2. By implementing Runnable interface Creating a thread by extending Thread class: For creating a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. class MyThread extends Thread public void run() overrides //body of method class Thread public void run() Example: class MyThread extends Thread public void run() for(int i=1;i<=4;i++) System.out.println("MyThread: "+i);

99 class ThreadCreationDemo public static void main(string s[]) MyThread t=new MyThread(); t.start(); Output: MyThread: 1 MyThread: 2 MyThread: 3 MyThread: 4 Creating a thread by implementing Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. class MyThread implements Runnable public void run() implements //body of method interface Runnable public void run(); After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread t=new Thraed(obj); Here oj is the istae of lass that ipleets Ruale interface. Example: class MyThread implements Runnable public void run() for(int i=1;i<=4;i++) System.out.println("MyThread: "+i); class ThreadCreationDemo public static void main(string s[]) MyThread mt=new MyThread(); Thread t=new Thread(mt);

100 t.start(); Output: MyThread: 1 MyThread: 2 MyThread: 3 MyThread: 4 Creating multiple threads: class MyThread1 extends Thread public void run() for(int i=1;i<=4;i++) System.out.println("MyThread1: "+i); class MyThread2 extends Thread public void run() for(int i=1;i<=4;i++) System.out.println("MyThread2: "+i); class MultiThreadDemo public static void main(string s[]) MyThread1 t1=new MyThread1(); MyThread2 t2=new MyThread2(); t1.start(); t2.start(); Output: Output may be changed from run to run. Because both threads executes simultaneously.

101 Getting and setting names of Thread: For getting name of thread we use following method public final String getname() For getting name for a thread we use following method public final void setname(string name) Example class MyThread1 extends Thread public void run() class GettingSettingName public static void main(string s[]) MyThread1 t1=new MyThread1(); System.out.println(Thread.currentThread().getName()); Thread.currentThread().setName( my main ); System.out.println(Thread.currentThread().getName()); t1.start(); System.out.println(t1.getName()); t1.setname( my thread ); System.out.println(t1.getName()); Output: main my main Thread0 my thread **********************

102 Thread Priorities: In java every thread has some priority. Based on priority thread scheduler allocates processor for each thread. The default priority of main thread is 5 The thread priorities are within a range of 1 to 10. If we create any thread, then the priority of thread is main thread priority i.e. 5, because the default parent of Thread is main thread. We have 3 types of priorities 1. Minimum priority: 1 2. Normal priority: 5 3. Maximum priority: 10 To display priorities of thread the following code is suitable class ThreadPriorities public static void main(string args[]) System.out.println(Thread.MIN_PRIORITY); //1 System.out.println(Thread.NORM_PRIORITY); //5 System.out.println(Thread.MAX_PRIORITY); //10 Getting and setting priorities of Thread: For getting name of thread we use following method public final int getpriority () For getting name for a thread we use following method public final void setpriority (int value) Example class MyThread1 extends Thread public void run() class GettingSettingName public static void main(string s[]) MyThread1 t1=new MyThread1(); System.out.println(Thread.currentThread().getPriority()); System.out.println(t1.getPriority ()); t1.setpriority (8); System.out.println(t1.getPriority ()); Output: 5 5 8

103 isalive(): This method is returns status of a thread i.e. returns Boolean values either true or false. The general form of method is public final Boolean isalive() Example: class MyThread extends Thread public void run() class ThreadCreationDemo public static void main(string s[]) MyThread t=new MyThread(); System.out.println(Thread.currentThread().isAlive()); t.start(); System.out.println(t.isAlive()); Output: true true sleep(): The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here: static void sleep(long milliseconds) throws InterruptedException The number of milliseconds to suspend is specified in milliseconds. This method may throw an InterruptedException. The sleep( ) method has a second form, which allows you to specify the period in terms of milliseconds and nanoseconds: static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

104 Example: class MyThread1 extends Thread public void run() for(int i=1;i<=4;i++) try Thread.sleep(1000); // sleeps for 1 second System.out.println("Child Thread "+i); catch(interruptedexception e) class ThreadSleepDemo public static void main(string args[])throws InterruptedException MyThread1 t1=new MyThread1(); t1.start(); Output:(for each line printing it takes 1 sec time) Child Thread: 1 Child Thread: 2 Child Thread: 3 Child Thread: 4 join(): join method can be used to pause the current thread execution until unless the specified thread is completed. There are three overloaded join methods. public final void join() public final void join(long millis) public final void join(long millis, int nanos) Join method throws InterruptedException. Because when ever join method call then thread execution interrupted for some time.

105 Example1: class MyThread31 extends Thread public void run() for(int i=1;i<=5;i++) try sleep(2000); System.out.println("Child Thread : "+i); catch(interruptedexception e) class ThreadJoinDemo public static void main(string args[]) MyThread22 t=new MyThread31(); t.start(); try t.join(); catch(interruptedexception e) for(int j=1;j<=5;j++) System.out.println("Main Thread : "+j); Output: Child Thread : 1 Child Thread : 2 Child Thread : 3 Child Thread : 4 Child Thread : 5 Main Thread : 1 Main Thread : 2 Main Thread : 3 Main Thread : 4 Main Thread : 5

106 Example2: class MyThread11 extends Thread public void run() String name= Thread.currentThread().getName(); System.out.println("Thread started: "+name)); try sleep(4000); catch (InterruptedException e) System.out.println("Thread ended:"+name); class ThreadJoinExample public static void main(string[] args) MyThread11 t1 = new MyThread11(); MyThread11 t2 = new MyThread11(); t1.start(); //starts second thread after completing t1 thread try t1.join(); catch (InterruptedException e) t2.start(); try t2.join(); catch (InterruptedException e) System.out.println("t1,t2 are completed,exiting main thread"); Output: Thread started: Thread-0 Thread ended:thread-0 Thread started: Thread-1 Thread ended:thread-1 t1,t2 are completed,exiting main thread ***********************

107 Thread Synchronization: If multiple threads want to execute simultaneously in some cases we may get data inconsistency problem. To overcome data inconsistency problem we use Thread synchronization. In java Synchronization can be achieved by using synchronized keyword synchronized keyword is applicable for only methods and blocks but not for classes and variables. General form of synchronized method and block. synchronized return_type method_name(arguments) synchronized(object) In java every object has two areas synchronized area and non-synchronized area. In multithreading at a time only one thread can execute synchronized area, in this scenario thread acquires the lock of object. Once thread completes execution then it releases lock. The released lock is allotted to another thread by Thread Scheduler. While executing one thread executing synchronized area the remaining threads are in waiting state until current thread completes its execution. The non-synchronized area can execute multiple threads simultaneously. Example: class Table synchronized void printtable(int n) System.out.println("Multiplication table for :"+n); for(int i=1;i<=5;i++) System.out.println(n+"*"+i+"="+n*i); try Thread.sleep(500); catch(exception e) System.out.println(e); System.out.println("Thread execution completed\n");

108 class MyThread11 extends Thread Table t; int n; MyThread11(Table t,int n) this.t=t; this.n=n; public void run() t.printtable(n); class ThreadSynchronization1 public static void main(string args[]) Table obj = new Table();//only one object MyThread11 t1=new MyThread11(obj,10); MyThread11 t2=new MyThread11(obj,20); t1.start(); t2.start(); Output: Multiplication table for :10 10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 Thread execution completed Multiplication table for :20 20*1=20 20*2=40 20*3=60 20*4=80 20*5=100 Thread execution completed *************************

109 Suspending and Resuming and stopping threads: For suspending, resuming and stopping threads we use suspend(), resume(), stop(). stop(), suspend(), resume() methods are called as deprecated methods. These methods are not recommended to use in multithreading. The general form of these methods final void suspend( ) final void resume( ) void stop() Example: class Thread1 extends Thread public void run() try for(int i=1;i<=3;i++) sleep(1000); System.out.println("this is Thread1 :"+i); catch(exception e) class SuspendResumeDemo public static void main(string args[])throws Exception Thread1 t1=new Thread1(); t1.start(); t1.suspend();//its suspends the current thread. for(int j=0;j<=3;j++) Thread.sleep(1000); System.out.println("I am main thread: "+j); t1.resume();//its resume the suspended thread. Output: Compilation: javac SuspendResumeDemo.java Note: SuspendResumeDemo.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. Running: java SuspendResumeDemo I am main thread: 1 I am main thread: 2 I am main thread: 3 this is Thread1 :1 this is Thread1 :2 this is Thread1 :3

110 Thread Communication: In multithreading thread communication can be achieved using three methods. 1. wait() : waits for some time until it receives notification from thread 2. notify() : gives notification to waiting thread 3. notifyall() : gives notifications to all waiting threads. The general forms final void wait( ) throws InterruptedException final void notify( ) final void notifyall( ) the aove ethods eist iside Ojet lass. These methods should be called inside synchronized area i.e. either synchronized method or synchronized block. Example: class NotifyThread extends Thread int total; public void run() System.out.println("NotifyThread starts updation"); synchronized(this) for(int i=1;i<=100;i++) total=total+i; System.out.println("NotifyThread giving nofication"); this.notify(); class WaitNotifyDemo public static void main(string s[])throws InterruptedException NotifyThread t1=new NotifyThread(); t1.start(); synchronized(t1) System.out.println("Main thread going to waiting state"); t1.wait(); System.out.println("Main thread recieves notification"); System.out.println("Total is:"+t1.total); OutPut: Main thread going to waiting state NotifyThread starts updation NotifyThread giving nofication Main thread recieves notification Total is:5050 ************************

111 UNIT-V File handling, Networking and Applets Syllabus: File Handling: Streams, Byte streams, Character streams and File streams. Networking: TCP, UDP, URL Connection Class, Inet Address Class, Socket Programming. Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet, types of applets, creating applets, passing parameters to applets, Applet to applet communication. File Handling: Streams: Streams facilitate transporting data from one place to another. Different streams are needed to send or receive data through different sources, such as to receive data from keyboard, we need a stream and to send data to a file, we need another stream. Without streams, it is not possible to move data in Java. Streams can be categorized as 'input streams' and 'output streams'. Input streams are the streams which receive or read data while output streams are the streams which send or write data. All streams are represented by classes in java.io (input- output) package. input stream reads data. So, to read data from keyboard, we can attach the keyboard to an input stream, so that the stream can read the data typed on the keyboard. DatalrtputStream dfs = new DataInputStream(System.in); In the above statement, we are attaching the keyboard to DatalnputStream object. The keyboard is represented by System.in. DatalnputStream object can read data coming from the keyboard. Here, System is a class and in is a field in System class. In fact, the System class has the following 3 fields: System.in: Represents InputStream object This object represents the standard input device, that is keyboard by default. System.out: Represents PrintStream object, This object by default represents the standard output device, that is monitor. System.err: Represents PrintStream object. This object by default represents the standard output device, that is monitor, Keyboard is an InputStream. Similarly, the monitor represented by PrintStream. 1

112 Classification of Streams: Streams can be classified into types 1. Byte streams 2. Text streams (or) Character streams Byte streams represent data in the form of individual bytes. Text streams represent data as characters of each 2 bytes. If a class name ends with the word 'Stream', then it comes under byte streams, InputStream reads bytes and OutputStream writes bytes. For example; FileInputStream FileOutputStream BufferedInputStream BufferedOutputStream If a class name ends with the word 'Reader or Writer' then it is taken as a text stream. Reader reads text and Writer writes text. For example, FileReader FileWriter BufferedReader BufferedWriter Byte streams are used to handle any characters (text), images, audio, and video files. For example, to store an image file (.gif or \ jpg), we should go for a byte stream. Byte stream classes for reading the data Byte stream classes for writing the data 2

113 Character or text streams can always store and retrieve data in the form of characters or text only. It means text streams are more suitable for handling text fijes like the ones we create in Notepad. They are not suitable to handle the images, audio, or video files. Character streams classes for reading data Character streams classes for writing data Creating a file using FileOutputStream: FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes. DataInputStream is used to read data from keyboard. It can be used to create text files. We know that a file represents storage of data on a second storage media like a hard disk or CD. 3

114 Program: import java.io.*; class CreateFile public static void main(string args[])throws IOException DataInputStream dis=new DataInputStream(System.in); FileOutputStream fout=new FileOutputStream("myfile.txt"); System.out.println("enter at end)"); char ch; while((ch=(char)dis.read())!='@') fout.write(ch); fout.close(); Compilation: javac CreateFile.java Execution: java CreateFile enter at end) hello this is file handling To see file content: type myfile.txt Ouput: hello this is file handling concept. Appending text to already existing file: For appending text to already existing file we have use the following form FileOutputStream fout=new FileOutputStream("myfile.txt",true); Program: import java.io.*; class CreateFile1 public static void main(string args[])throws IOException DataInputStream dis=new DataInputStream(System.in); FileOutputStream fout=new FileOutputStream("myfile.txt",true); System.out.println("enter at end)"); char ch; while((ch=(char)dis.read())!='@') fout.write(ch); fout.close(); Compilation: javac CreateFile1.java Execution: java CreateFile1 enter at end) hello this is appended To see file content: type myfile.txt Ouput: hello this is file handling concept.hello this is appended text 4

115 Creating a file using BufferedOutputStream: While creating a file using BufferedOutputStream class the efficiency of the program is improved. BufferedOutputStream takes argument as FileOutputStream as reference for creating a Buffer. The default size of Buffer is 512 bytes. The general form of BufferedOutputStream class is BufferedOutputStream bout=new BufferedOutputStream(fout,1024); In the above form fout means reference of FileOutputStream class and 1024 is bytes. Example Program: import java.io.*; class CreateFile2 public static void main(string args[])throws IOException DataInputStream dis=new DataInputStream(System.in); FileOutputStream fout=new FileOutputStream("myfile1.txt"); BufferedOutputStream bout=new BufferedOutputStream(fout,1024); System.out.println("enter at end)"); char ch; while((ch=(char)dis.read())!='@') bout.write(ch); bout.close(); Compilation: javac CreateFile2.java Execution: java CreateFile2 enter at end) hello this is BufferedOutputStream To see file content: type myfile1.txt Ouput: hello this is BufferedOutputStream class. ********************************* 5

116 Reading data from a file using FileInputStream: FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible read data from a text file using FilelnputStream. FileInputStream fin=new FileInputStream("myfile.txt") Program: import java.io.*; class ReadFile public static void main(string args[])throws IOException FileInputStream fout=new FileInputStream("myfile.txt"); System.out.println("File contents:"); int ch; while((ch=fin.read())!=-1) System.out.print((char)ch); fin.close(); Compilation: javac CreateFile1.java Execution: java CreateFile1 Ouput: File contents: hello this is file handling concept.hello this is appended text. Creating a file using FileWriter: FileWriter is useful to create a file by writing characters into it. The following program how to create a text file using FileWriter. Program: import java.io.*; class CreatingFile public static void main(string args[])throws IOException DataInputStream dis=new DataInputStream(System.in); FileWriter fw=new FileWriter("myfile2.txt"); System.out.println("enter at end)"); char ch; while((ch=(char)dis.read())!='@') fw.write(ch); fw.close(); 6

117 Compilation: javac CreatingFile.java Execution: java CreatingFile enter at end) hello we are CSE To see file content: type myfile2.txt hello we are CSE students Reading data from a file using FileReader: File class: FileReader is useful to read data in the form of characters from a 'text' file. Program: import java.io.*; class ReadingFile public static void main(string args[])throws IOException FileReader fout=new FileReader("myfile2.txt"); System.out.println("File contents:"); int ch; while((ch=fr.read())!=-1) System.out.print((char)ch); fr.close(); Compilation: javac ReadingFile.java Execution: java ReadingFile Output: hello we are CSE students ********************* File class of java.io package provides some methods to know the properties of a file or a directory. Creating the File object by passing the filename or directory name to it. File obj=new File( filename ); Fiel obj=new File( directory name ); File obj=new File( path, filename ); File obj=new File( path, directoryname ); We can create text files using File class by replacing FileOutputStream and FileWriter class with File class. 7

118 Creating file using File class: import java.io.*; class CreateFile2 public static void main(string args[])throws IOException DataInputStream dis=new DataInputStream(System.in); File f=new File("myfile1.txt"); System.out.println("enter at end)"); char ch; while((ch=(char)dis.read())!='@') f.write(ch); f.close(); ********************************* Creating directories using File class: import java.io.file; class CreateDirectoryExample public static void main(string[] args) // creating a directory in current working directory File file = new File("mydir"); // exists() returns Boolean value true or false if (!file.exists()) // mkdir() returns Boolean value true or false if (file.mkdir()) System.out.println("Directory is created!"); else System.out.println("Failed to create directory!"); // creating multiple directories in specified path File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2"); if (!files.exists()) if (files.mkdirs()) System.out.println("Multiple directories are created!"); else System.out.println("Failed to create multi directories!"); ********************************* 8

119 Counting number of lines, words and characters in a text file: import java.io.*; class WordCountInFile public static void main(string[] args)throws IOException BufferedReader reader = null; int charcount = 0; int wordcount = 0; int linecount = 0; try FileReader fr=new FileReader("myfile.txt"); reader = new BufferedReader(fr); String currentline = reader.readline(); while (currentline!= null) linecount++; String[] words = currentline.split(" "); wordcount = wordcount + words.length; for (String word : words) charcount = charcount + word.length(); currentline = reader.readline(); System.out.println("Chars In a File: "+charcount); System.out.println("Words In a File: "+wordcount); System.out.println("Lines In a File: "+linecount); catch (IOException e) System.out.println(e); finally reader.close(); Compilation: javac WordCountInFile.java Execution:java WordCountInFile Output: //Based on your file data displays output. ********************************* 9

120 Reading data from console using BufferedReader: import java.io.*; class ReadFromConsole public static void main(string args[])throws Exception DataInputStream dis=new DataInputStream(System.in); BufferedReader br=new BufferedReader(dis); System.out.println("Enter your name"); String name=br.readline(); System.out.println("Welcome "+name); Compilation: javac ReadFromConsole.java Execution:java ReadFromConsole Output: Enter your name Sachin Tendulkar Welcome Sachin Tendulkar ********************************* 10

121 Networking: Network: Two or more systems that are inter connected to each other is called a network. To establish a network we have 3 requirements Hardware: includes computers, cables, modems, hubs etc. Software: includes programs provide communication between client and server Protocol: includes set of rules for sending and receiving data. TCP/IP Protocol A protocol represents a set of rules to be followed by every computer on the network, Protocol is useful to physically move data from one place to another place on a network. TCP (Transmission Control Protocol) / IP (Internet Protocol) is the standard protocol model used on any network, including Internet. Before TCP/IP, we have OSI (Open Systems Interconnection) reference model. Based on OSI model TCP/IP Layer model is established. Application layer provides applications the ability to access the services of the other layers and defines the protocols that applications use to exchange data. There are many Application layer protocols and new protocols are always being developed. The most widely-known Application layer protocols are those used for the exchange of user information: Hypertext Transfer Protocol (HTTP) is used to transfer files that make up the Web pages of the World Wide Web. File Transfer Protocol (FTP) is used for interactive file transfer. Simple Mail Transfer Protocol (SMTP) is used for the transfer of mail messages and attachments. Domain Name System (DNS) is used to resolve a host name to an IP address. 11

122 Transport layer (also known as the Host-to-Host Transport layer) is responsible for providing the Application layer with session and datagram communication services. The core protocols of the Transport layer are Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP). TCP(Transmission Control protocol): provides a one-to-one, connection-oriented, reliable communications service. TCP is responsible for the establishment of a TCP connection, the sequencing and acknowledgment of packets sent, and the recovery of packets lost during transmission. UDP(User Datagram Protocol): provides a one-to-one or one-to-many, connectionless, unreliable communications service. UDP is used when the amount of data to be transferred is small (such as the data that would fit into a single packet), when the overhead of establishing a TCP connection is not desired or when the applications or upper layer protocols provide reliable delivery. Internet layer or Network layer is responsible for addressing, packaging, and routing functions. The core protocol of the Internet layer is IP. Internet Protocol (IP) is a routable protocol responsible for IP addressing, routing, and the fragmentation and reassembly of packets. Network Interface layer (also called the Network Access layer) is responsible for placing TCP/IP packets on the network medium and receiving TCP/IP packets off the network medium. ************************ InetAddress class: InetAddress class represents an IP address. The java.net.inetaddress class provides methods to get the IP of any host name. for example etc. methods of InetAddress class: Method public static InetAddress getbyname(string host) throws UnknownHostException public static InetAddress getlocalhost() throws UnknownHostException public String gethostname() public String gethostaddress() Description it returns the instance of InetAddress containing LocalHost IP and name. it returns the instance of InetAdddress containing local host name and address. it returns the host name of the IP address. it returns the IP address in string format. 12

123 Example : import java.io.*; import java.net.*; public class InetDemo public static void main(string[] args) try InetAddress ip=inetaddress.getbyname(" System.out.println("Host Name: "+ip.gethostname()); System.out.println("IP Address: "+ip.gethostaddress()); catch(exception e) System.out.println(e); Output: Host Name: IP Address: URL class: ******************* The URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example 1. Protocol: In this case, http is the protocol. 2. Host name : In this case, is the Host name. 3. Port Number: It is an optional attribute. Here 80 is the port number. If port number is not mentioned in the URL, it returns File Name or directory name: In this case, index.html is the file name. Methods of URL class: Method Description public String getprotocol() public String gethost() public String getport() public String getfile() public URLConnection openconnection() it returns the protocol of the URL. it returns the host name of the URL. it returns the Port Number of the URL. it returns the file name of the URL. it returns the instance of URLConnection i.e. associated with this URL. 13

124 Example: import java.io.*; import java.net.*; public class URLDemo public static void main(string[] args) try URL url=new URL(" System.out.println("Protocol: "+url.getprotocol()); System.out.println("Host Name: "+url.gethost()); System.out.println("Port Number: "+url.getport()); System.out.println("File Name: "+url.getfile()); catch(exception e) System.out.println(e); Output: Protocol: http Host Name: Port Number: 80 File Name: /indjex.html URLConnection class: The URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL. The openconnection() method of URL class returns the object of URLConnection class. Syntax: public URLConnection openconnection()throws IOException The URLConnection class provides many methods, we can display all the data of a webpage by using the getinputstream() method. The getinputstream() method returns all the data of the specified URL in the stream that can be read and displayed. Example import java.io.*; import java.net.*; public class URLConnectionExample public static void main(string[] args) 14

125 try URL url=new URL( URLConnection urlcon=url.openconnection(); InputStream stream=urlcon.getinputstream(); int i; while((i=stream.read())!=-1) System.out.print((char)i); catch(exception e) System.out.println(e); Output: Source code of webpage is displayed Socket Programming: A socket is a point of connection between a client and server on a network. Each socket is given an identification number, which is called port number'. Port number takes 2 bytes and can be from 0 to 65,535. Establishing communication between a server and a client using sockets is called 'socket programming'. Socket programming can be connection-oriented or connection-less. Socket and ServerSocket classes are used for connection-oriented socket programming. The client in socket programming must know two information: IP Address of Server, and Port number. Socket class A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. Method Description 1) public InputStream getinputstream() returns the InputStream attached with this socket. 2) public OutputStream getoutputstream() returns the OutputStream attached with this socket. 3) public synchronized void close() closes this socket 15

126 ServerSocket class The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients. Method Description 1) public Socket accept() returns the socket and establish a connection between server and client. 2) public synchronized void close() closes the server socket. Example: MyServer.java import java.io.*; import java.net.*; public class MyServer public static void main(string[] args) try ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.getInputStream()); // UTF: Unicode Transformation Format String str=(string)dis.readutf(); System.out.println("message= "+str); ss.close(); catch(exception e) System.out.println(e); MyClient.java import java.io.*; import java.net.*; public class MyClient public static void main(string[] args) try Socket s=new Socket("localhost",6666); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeutf("hello Server"); dout.close(); s.close(); catch(exception e) System.out.println(e); 16

127 Execution process: To execute this program open two command prompts and execute each program at each command prompt as displayed in the below figure. After running the client application, a message will be displayed on the server console. ************************ 17

128 Applets: An applet is a small and portable application that runs under the restricted scope provided by JRE. It has dual compatibility as it can be executed on a web browser and also by applet viewer. JVM is required on the client machine to run an applet program. Applet represents Java byte code embedded in a web page. Applet= java byte code+ html page Differences between Applet and Application: Applet Application Small Program Large Program Can be executed on stand alone computer Used to run a program on client Browser system Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client machine. JAVA supported browser. Applet applications are executed in a Application can access all the resources of the Restricted Environment computer Applets are created by extending the Applications are created by writing java.applet.applet public static void main(string[] s) method. Applet application has 5 methods which will Application has a single start point which is be automatically invoked on occurance of main method specific event Example: import java.awt.*; import java.applet.*; public class Myclass extends Applet public void init() public void start() public void stop() public void destroy() public void paint(graphics g) public class MyClass public static void main(string args[]) //implementation 18

129 Types of Applets: Web pages can contain two types of applets which are named after the location at which they are stored. 1. Local Applet 2. Remote Applet Local Applets: A local applet is the one that is stored on our own computer system. When the Webpage has to find a local applet, it doesn't need to retrieve information from the Internet. A local applet is specified by a path name and a file name as shown below in which the codebase attribute specifies a path name, whereas the code attribute specifies the name of the byte-code file that contains the applet's code. <applet codebase="myapppath" code="myapp.class" width=200 height=200> </applet> Remote Applets: A remote applet is the one that is located on a remote computer system. This computer system may be located in the building next door or it may be on the other side of the world. No matter where the remote applet is located, it's downloaded onto our computer via the Internet. The browser must be connected to the Internet at the time it needs to display the remote applet. To reference a remote applet in Web page, we must know the applet's URL (where it's located on the Web) and any attributes and parameters that we need to supply. <applet codebase=" code="myapp.class" width=200 height=200> </applet> Applet life cycle: ******************************** consists of 5 methods which will be automatically invoked by JRE when some action is done on the application/browser. List of Methods: // exists insise java.applet.applet public void init() public void start() public void stop() public void destroy() //exist inside java.awt.component public void paint(graphics g) 19

130 init(): start() stop() Invoked only once when the application is launched using appletviewer or browser Should include code for component definition, Object creation, Layout settings, Basic look and feel Invoked when application is maximized, Default application state is Maximized window so this will also be invoked on launching. Should include code for starting/resuming thread, starting/resuming Graphical User Interface, etc Invoked when application is minimized, invoked also when the window is terminated while its in maximizes state. Should include code for pausing/stopping thread, pausing/stopping Graphical User Interface, etc destroy() Invoked when application is about to terminate (or) invoked when we close the application. Should include code for connection closing, file closing, etc paint() Invoked when application is to be refreshed in terms of GUI (or) invoked when we start, move or resize applet. Should include code for GUI design ********************* Creating an Applet: Five steps to be kept in mind when writing an applet program: 1. import java.applet.* (Need Applet class from java.applet package) 2. create a public class 3. extend the class from the base class Applet 4. do not write main method 5. write the applet life cycle methods (i.e. init, start, stop, destroy, paint) File name: abc.java import java.applet.*; public class abc extends Applet //methods of applet life cycle 20

131 Steps to compile and Run Applet program: Compile your java code using javac.exe on console/command prompt. To run the generated class file, we have to write <applet> tag in an additional file(e.g. abc.html). Later on that file name is to be passed as an argument to appletviewer.exe as shown below File name: abc.html <applet code="abc" width="500" height="500"></applet> Commands to be executed: c:> javac abc.java c:> appletviewer abc.html Example: MyApp.java import java.applet.*; import java.awt.*; public class MyApp extends Applet public void init() setbackground(color.yellow); public void paint(graphics g) g.drawstring("hello applet",100,100); MyApp.html <html> <applet code="myapp.class" height= 300 width= 400 > </applet> </html> Compilation: javac MyApp.java Execution: appletviewer MyApp.html Output: 21

132 we can also execute the above applet program without html file by including applet tag inside a program within comment section. MyApp.java import java.applet.*; import java.awt.*; public class MyApp extends Applet public void init() setbackground(color.yellow); public void paint(graphics g) g.drawstring("hello applet",100,100); /* <applet code="myapp.class" height="300" width="300"> </applet> */ Compilation: javac MyApp.java Execution: appletviewer MyApp.java Output: Example2: import java.applet.*; import java.awt.*; public class MyApp1 extends Applet public void init() setbackground(color.yellow); public void paint(graphics g) Font f=new Font("Arial",Font.BOLD,36); g.setfont(f); 22

133 g.setcolor(color.green); g.drawstring("hello applet",100,100); /* <applet code="myapp1.class" width="400" height="300"></applet> */ Compilation: javac MyApp.java Execution: appletviewer MyApp.java Output: java.awt.graphics class provides many methods for graphics programming. 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 setcolor(color c): is used to set the graphics current color to the specified color. 9. public abstract void setfont(font font): is used to set the graphics current font to the specified font. 23

134 Passing parameters to applet: We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getparameter(). Example: UseParam.java: public String getparameter(string parametername) 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); UseParam.html <html> <body> <applet code="useparam.class" width="300" height="300"> <param name="msg" value="welcome to applet"> </applet> </body> </html> Compilation: javac MyApp.java Execution: appletviewer MyApp.java Output: 24

135 Applet to applet Communication: java.applet.appletcontext class provides the facility of communication between applets. We provide the name of applet through the HTML file. It provides getapplet() method that returns the object of Applet. public Applet getapplet(string name) Example: RequestApp.java: import java.applet.*; import java.awt.*; import java.awt.event.*; public class RequestApp extends Applet implements ActionListener public void init() Button b=new Button("Click"); b.setbounds(50,50,50,50); add(b); b.addactionlistener(this); public void actionperformed(actionevent e) AppletContext ctx=getappletcontext(); Applet a=ctx.getapplet("response"); Font f=new Font("Arial",Font.BOLD,36); a.setfont(f); a.setbackground(color.green); ResponseApp.java: import java.applet.*; import java.awt.*; public class ResponseApp extends Applet public void paint(graphics g) g.drawstring("welcome to applet",150,150); CommApp.html: <html> <body> <applet code="requestapp.class" width="300" height="300" name="request"> </applet> <applet code="responseapp.class" width="300" height="300" name="response"> </applet> </body> </html> 25

136 Compilation: javac RequestApp.java javac ResponseApp.java Execution: appletviewer CommApp.html Output: Before button click: After button click: ***************************** 26

137 UNIT-6 GUI Programming with Java & Event Handling GUI Programming with Java - The AWT class hierarchy, Components and Containers, Introduction to Swing, Swing vs AWT, Hierarchy for Swing Components, Containers - JFrame, JApplet, JDialog, JPanel, Swing components- Jbutton, JLabel, JTextField, JTextArea, JRadio buttons, JList, JTable, Layout manager, executable jar file in Java. Event Handling - Events, Event sources, Event classes, Event Listeners, Delegation event model, handling mouse and keyboard events, Adapter classes, Inner classes. AWT: AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java. AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS. The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. AWT class Hierarchy The hierarchy of AWT classes are given below. 1

138 Container: The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. Window The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. Panel The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. Frame The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc. Methods of Component class Method public void add(component c) public void setsize(int width,int height) public void setlayout(layoutmanager m) public void setvisible(boolean status) Description inserts a component on this component. sets the size (width and height) of the component. defines the layout manager for the component. changes the visibility of the component, by default false. Creating a awt Frame with Button: There are two ways to create a frame in AWT. o By extending Frame class (inheritance) o By creating the object of Frame class (association) By extending Frame class import java.awt.*; class FirstFrame extends Frame FirstFrame() Button b=new Button("click me"); b.setbounds(30,100,80,30);// setting button position add(b);//adding button into frame setsize(300,300);//frame size 300 width and 300 height setlayout(null);//no layout manager setvisible(true);//frame will be visible, by default not visib le public static void main(string args[]) FirstFrame f=new FirstFrame(); 2

139 Output: By creating the object of Frame class: import java.awt.*; class FirstFrame public static void main(string args[]) Frame f=new Frame(); Button b=new Button("click me"); b.setbounds(30,100,80,30);// setting button position f.add(b);//adding button into frame f.setsize(300,300);//frame size 300 width and 300 height f.setlayout(null);//no layout manager f.setvisible(true);//frame will be visible,by default not visible Output: Note: awt Frames are not closed when clicked on close button. If we want to close awt frame we have to use Event handling concept. 3

140 Swings: Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. Difference between AWT and Swing Java AWT AWT components are platform-dependent. AWT components are heavyweight. AWT doesn't support pluggable look and feel. AWT provides less components than Swing. AWT doesn't follows MVC Java Swing Java swing components are platformindependent. Swing components are lightweight. Swing supports pluggable look and feel. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. Swing follows MVC. (Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. 4

141 Hierarchy of Java Swing classes 5

142 Containers: JFrame: The class JFrame is an extended version of java.awt.frame that adds support for the JFC/Swing component architecture. Example: import javax.swing.*; public class FirstSwingExample public static void main(string[] args) JFrame f=new JFrame();//creating instance of JFrame JButton b=new JButton("click");//creating instance of JButton b.setbounds(130,100,100, 40);//x axis, y axis, width, height OutPut: f.add(b);//adding button in JFrame f.setsize(400,500);//400 width and 500 height f.setlayout(null);//using no layout managers f.setvisible(true);//making the frame visible f.setdefaultcloseoperation(jframe.exit_on_close); //closing frame 6

143 JApplet: As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class extends the Applet class. Example: import java.applet.*; import javax.swing.*; import java.awt.event.*; public class EventJApplet extends JApplet implements ActionListener JButton b; JTextField tf; public void init() tf=new JTextField(); tf.setbounds(30,40,150,20); b=new JButton("Click"); b.setbounds(80,150,70,40); add(b);add(tf); b.addactionlistener(this); setlayout(null); public void actionperformed(actionevent e) tf.settext("welcome"); /* <applet code="eventjapplet.class" width="300" height="300"> </applet> */ Output: Before clicking the button After clicking the button 7

144 JDialog: The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class. Unlike JFrame, it doesn't have maximize and minimize buttons. JDialog Exists inside javax.swing package. Commonly used Constructors: Constructor JDialog() JDialog(Frame owner) JDialog(Frame owner, String title, boolean modal) Description It is used to create a modeless dialog without a title and without a specified Frame owner. It is used to create a modeless dialog with specified Frame as its owner and an empty title. It is used to create a dialog with the specified title, owner Frame and modality. Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DialogDemo DialogDemo() JDialog d = new JDialog(); JLabel l=new JLabel ("This is Dialog Box"); d.add(l); d.setlayout(new FlowLayout()); d.setsize(300,300); d.setvisible(true); d.setdefaultcloseoperation(jdialog.dispose_on_close); public static void main(string args[]) new DialogDemo(); Output: 8

145 JPanel: The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class. It doesn't have title bar. Commonly used Constructors: Constructor Description JPanel() JPanel(boolean isdoublebuffered) create a new JPanel with a double buffer and a flow layout. create a new JPanel with FlowLayout with some strategy. JPanel(LayoutManager layout) Example: import java.awt.*; import javax.swing.*; public class PanelExample PanelExample() JFrame f= new JFrame("Panel Example"); JPanel panel=new JPanel(); panel.setbounds(40,80,200,200); panel.setbackground(color.gray); JButton b1=new JButton("Button 1"); b1.setbounds(50,100,80,30); b1.setbackground(color.yellow); JButton b2=new JButton("Button 2"); b2.setbounds(100,100,80,30); b2.setbackground(color.green); panel.add(b1); panel.add(b2); f.add(panel); f.setsize(400,400); f.setlayout(null); f.setvisible(true); public static void main(string args[]) new PanelExample(); Output: create a new JPanel with the specified layout manager. 9

146 Swing components: JButton: The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class. Commonly used Constructors: Constructor Description JButton() JButton(String s) It creates a button with no text and icon. It creates a button with the specified text. JButton(Icon i) Commonly used methods: Methods void settext(string s) String gettext() void seticon(icon b) Icon geticon() void addactionlistener(actionlistener a) It creates a button with the specified icon object. Description It is used to set specified text on button It is used to return the text of the button. It is used to set the specified Icon on the button. It is used to get the Icon of the button. It is used to add the action listener to this object. Example import javax.swing.*; public class ButtonExample public static void main(string[] args) JFrame f=new JFrame("Button Example"); JButton b=new JButton("Click Here"); b.setbounds(50,100,95,30); f.add(b); f.setsize(400,400); f.setlayout(null); f.setvisible(true); Output: 10

147 JLabel The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class. Commonly used Constructors: Constructor Description JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(String s) Creates a JLabel instance with the specified text. JLabel(Icon i) Creates a JLabel instance with the specified image. Commonly used Methods: Methods Description String gettext() It returns the text string that a label displays. void settext(string text) It defines the single line of text this component will display. void sethorizontalalignment(int alignment) Example: import javax.swing.*; class LabelExample public static void main(string args[]) JFrame f= new JFrame("Label Example"); JLabel l1,l2; l1=new JLabel("First Label."); l1.setbounds(50,50, 100,30); l2=new JLabel("Second Label."); l2.setbounds(50,100, 100,30); f.add(l1); f.add(l2); f.setsize(300,300); f.setlayout(null); f.setvisible(true); It sets the alignment of the label's contents along the X axis. Output: 11

148 JTextField: The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class. Commonly used Constructors: Constructor Description JTextField() JTextField(String text) JTextField(String text, int columns) JTextField(int columns) Creates a new TextField Creates a new TextField initialized with the specified text. Creates a new TextField initialized with the specified text and columns. Creates a new empty TextField with the specified number of columns. Commonly used Methods: Methods Description void addactionlistener(actionlistener l) add the specified action listener to receive action events from this textfield. Action getaction() void setfont(font f) It returns the currently set Action for this ActionEvent source, or null if no Action is set. set the current font. void removeactionlistener(actionlistener l) remove the specified action listener so that it no longer receives action events from this Example: import javax.swing.*; class TextFieldExample public static void main(string args[]) JFrame f= new JFrame("TextField Example"); JTextField t1,t2; t1=new JTextField("Welcome to Javatpoint."); t1.setbounds(50,100, 200,30); t2=new JTextField("AWT Tutorial"); t2.setbounds(50,150, 200,30); f.add(t1); f.add(t2); f.setsize(300,400); f.setlayout(null); f.setvisible(true); Output: 12

149 JTextArea: The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits JTextComponent class Commonly used Constructors: Constructor Description JTextArea() JTextArea(String s) JTextArea(int row, int column) JTextArea(String s, int row, int column) Creates a text area that displays no text initially. Creates a text area that displays specified text initially. Creates a text area with the specified number of rows and columns that displays no text initially. Creates a text area with the specified number of rows and columns that displays specified text. Commonly used Methods: Methods void setrows(int rows) void setcolumns(int cols) void setfont(font f) Description It is used to set specified number of rows. It is used to set specified number of columns. It is used to set the specified font. void insert(string s, int position) It is used to insert the specified text on the specified position. void append(string s) It is used to append the given text to the end of the document. Example: import javax.swing.*; public class TextAreaExample JFrame f; JTextArea area; TextAreaExample() f= new JFrame(); area=new JTextArea("Welcome to javatpoint") Output: area.setbounds(10,30, 200,200); f.add(area); f.setsize(300,300); f.setlayout(null); f.setvisible(true); public static void main(string args[]) new TextAreaExample(); 13

150 JRadioButton: The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is widely used in exam systems or quiz. It should be added in ButtonGroup to select one radio button only. Commonly used Constructors: Constructor Description JRadioButton() JRadioButton(String s) Creates an unselected radio button with no text. Creates an unselected radio button with specified text. JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status. Commonly used Methods: Methods Description void settext(string s) String gettext() void setenabled(boolean b) void seticon(icon b) Icon geticon() void setmnemonic(int a) void addactionlistener(actionlistener a) It is used to set specified text on button. It is used to return the text of the button. It is used to enable or disable the button. It is used to set the specified Icon on the button. It is used to get the Icon of the button. It is used to set the mnemonic on the button. It is used to add the action listener to this object. Example: import javax.swing.*; public class RadioButtonExample JFrame f; RadioButtonExample() f=new JFrame(); JRadioButton r1=new JRadioButton("A) Male"); JRadioButton r2=new JRadioButton("B) Female"); r1.setbounds(75,50,100,30); r2.setbounds(75,100,100,30); ButtonGroup bg=new ButtonGroup(); bg.add(r1); bg.add(r2); f.add(r1); f.add(r2); f.setsize(300,300); 14

151 f.setlayout(null); f.setvisible(true); public static void main(string[] args) new RadioButtonExample(); Output: JList: The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class. Commonly used Constructors: Constructor Description JList() JList(ary[] listdata) Creates a JList with an empty, read-only, model. Creates a JList that displays the elements in the specified array. Commonly used Methods: Methods Void addlistselectionlistener (ListSelectionListener listener) Description It is used to add a listener to the list, to be notified each time a change to the selection occurs. int getselectedindex() It is used to return the smallest selected cell index. ListModel getmodel() It is used to return the data model that holds a list of items displayed by the JList component. void setlistdata(object[] listdata) It is used to create a read-only ListModel from an array of objects. 15

152 Example: import javax.swing.*; public class ListExample //DefaultListModel model; ListExample() JFrame f= new JFrame(); /* model=new DefaultListModel(); model.addelement("item1"); model.addelement("item2"); model.addelement("item3"); model.addelement("item4"); JList lst=new JList(model); */ String items[]="item1"," Item2", " Item3"," Item4"; JList lst=new JList(items); lst.setbounds(100,50,100,150); Output: f.add(lst); f.setsize(400,400); f.setlayout(null); f.setvisible(true); public static void main(string args[]) new ListExample(); JTable: The JTable class is used to display data in tabular form. It is composed of rows and columns. Commonly used Constructors: Constructor Description JTable() Creates a table with empty cells. JTable(Object[][] rows, Object[] columns) Creates a table with the specified data. 16

153 Example: import javax.swing.*; public class TableExample JFrame f; TableExample() f=new JFrame(); String data[][]= "101","Amit","670000", "102","Jai","780000", "103","Sachin","700000" ; String head[]="id","name","salary"; JTable jt=new JTable(data,head); jt.setbounds(30,40,200,300); JScrollPane sp=new JScrollPane(jt); f.add(sp); f.setsize(300,400); f.setvisible(true); public static void main(string[] args) new TableExample(); Output: *************************** 17

154 Layout managers: FlowLayout: Basically we have 3-types of Layout mangers in java. FlowLayout BorderLayout GridLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class: public static final int LEFT public static final int RIGHT public static final int CENTER Constructors of FlowLayout class: FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap. Example: import java.awt.*; import javax.swing.*; public class MyFlowLayout JFrame f; FlowLayout fl; MyFlowLayout() f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); f.add(b1);f.add(b2);f.add(b3); f.add(b4);f.add(b5); fl=new FlowLayout(FlowLayout.RIGHT); f.setlayout(fl); f.setsize(600,600); f.setvisible(true); public static void main(string[] args) new MyFlowLayout(); Output: 18

155 BorderLayout: The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region: public static final int NORTH public static final int SOUTH public static final int EAST public static final int WEST public static final int CENTER Constructors of BorderLayout class: BorderLayout(): creates a border layout but with no gaps between the components. JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components. Example: import java.awt.*; import javax.swing.*; public class Border JFrame f; Border() f=new JFrame(); JButton b1=new JButton("NORTH"); JButton b2=new JButton("SOUTH"); JButton b3=new JButton("EAST"); JButton b4=new JButton("WEST"); JButton b5=new JButton("CENTER"); f.add(b1,borderlayout.north); f.add(b2,borderlayout.south); f.add(b3,borderlayout.east); f.add(b4,borderlayout.west); f.add(b5,borderlayout.center); f.setsize(300,300); f.setvisible(true); public static void main(string[] args) new Border(); Ouput: 19

156 GridLayout: The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Constructors of GridLayout class: GridLayout(): creates a grid layout with one column per component in a row. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. Example: import java.awt.*; import javax.swing.*; import java.io.*; public class MyGridLayout JFrame f; MyGridLayout() f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3); f.add(b4);f.add(b5); f.add(b6);f.add(b7); f.add(b8);f.add(b9); //grid layout of 3 rows and 3 columns f.setlayout(new GridLayout(3,3)); f.setsize(300,300); f.setvisible(true); public static void main(string[] args) new MyGridLayout(); Output: 20

157 Executable jar file in Java: The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable jar file calls the main method of the class if you double click it. To create the executable jar file, you need to create.mf file, also known as manifest file. Creating manifest file To create manifest file, you need to write Main-Class, then colon, then space, then class name then enter. For example: myfile.mf (type the below in notepad save with an extention.mf) Main-Class: First Creating executable jar file using jar tool The jar tool provides many switches, some of them are as follows: 1. -c creates new archive file 2. -v generates verbose output. It displays the included or extracted resource on the standard output. 3. -m includes manifest information from the given mf file. 4. -f specifies the archive file name 5. -x extracts files from the archive file Write jar then swiches then mf_file then jar_file then.classfile as given below: jar -cvmf myfile.mf myjar.jar First.class It is shown in the image given below: Now it will create the executable jar file. If you double click on it, it will call the main method of the First class. We are assuming that a window based application using AWT or SWING. First.java ****************************** 21

158 Event handling: Event is the change in the state of Object or Source Event handling is the mechanism that controls the event and decides what should happen if an event occurs. Delegation event model: The event model is based on the Event Source and Event Listeners. Event Listener is an object that receives the messages / events. Event Source is any object which creates the message / event. The Event Delegation model is based on The Event Classes, The Event Listeners, Event Objects. There are three participants in event delegation model in Java; Event Source the class which broadcasts the events Event Listeners the classes which receive notifications of events Event Object the class object which describes the event. 22

159 Listener interfaces: 1. ActionListener 2. ItemListener 3. KeyListener 4. MouseMotionListener 5. MouseListener. ActionListener: registration method: public void addactionlistener(actionlistener a); performing event method: public void actionperformed(actionevent e) // event code Example: import java.awt.event.*; import javax.swing.*; public class ButtonExample1 implements ActionListener JTextField tf; ButtonExample1() JFrame f=new JFrame("Button Example"); tf=new JTextField(); tf.setbounds(50,50, 150,20); JButton b=new JButton("Click Here"); b.setbounds(50,100,95,30); f.add(b);f.add(tf); f.setsize(400,400); f.setlayout(null); f.setvisible(true); b.addactionlistener(this); public void actionperformed(actionevent e) tf.settext("welcome to ActionListener."); public static void main(string args[]) new ButtonExample1(); Before event generation: After event generation: 23

160 ItemListener: registration method: public void additemlistener(itemlistener i); performing event method: public void itemstatechanged(itemevent e) // event code KeyListener: registration method: public void addkeylistener(keylistener k); performing event methods: public void keypressed(keyevent e) // event code public void keyreleased(keyevent e) // event code public void keytyped(keyevent e) // event code Note: the above 3-methods should be overridden, other wise compile time error raised. i.e suppose if an interface having 4-methods, then for the all 4-methods implementation must be provide in a class. MouseMotionListener: registration method: public void addmousemotionlistener(mousemotionlistener mm); performing event methods: public void mousemoved(mouseevent me) // event code public void mousedragged(mouseevent e) // event code MouseListener: registration method: public void addmouselistener(mouselistener mm); performing event methods: public void mousepressed(mouseevent me) // event code public void mouseclicked(mouseevent e) // event code 24

161 public void mouseentered(mouseevent e) // event code public void mousereleased(mouseevent e) // event code public void mouseexited(mouseevent e) // event code The main drawback of Listener interfaces are we have to provide implementation part for every method inside a interface. This is overcome by using Adapter classes. Example program for MouseListener and MouseMotionListener to handle mouse events: import java.awt.*; import java.awt.event.*; import java.applet.applet; public class AppletMouseXY extends Applet implements MouseListener, MouseMotionListener int x, y; String str=""; public void init() addmouselistener(this); addmousemotionlistener(this); // override ML 5 abstract methods public void mousepressed(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Pressed"; repaint(); public void mousereleased(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Released"; repaint(); public void mouseclicked(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Clicked"; repaint(); 25

162 public void mouseentered(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Entered"; repaint(); public void mouseexited(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Exited"; repaint(); // override two abstract methods of MouseMotionListener public void mousemoved(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse Moved"; repaint(); public void mousedragged(mouseevent e) x = e.getx(); y = e.gety(); str = "Mouse dragged"; repaint(); // called by repaint() method public void paint(graphics g) g.setfont(new Font("Monospaced", Font.BOLD, 20)); g.filloval(x, y, 10, 10); g.drawstring(x + "," + y, x+10, y -10); g.drawstring(str, x+10, y+20); showstatus(str + " at " + x + "," + y); /* <applet code="appletmousexy.class" width="300" height="300"> </applet> */ Output: 26

163 Example for KeyListener to handle Keyboard events: import java.applet.*; import java.awt.*; import java.awt.event.*; public class AppletKeyListener extends Applet implements KeyListener char ch; String str; public void init() // link the KeyListener with Applet addkeylistener(this); // override all the 3 abstract methods of KeyListener interface public void keypressed(keyevent e) public void keyreleased(keyevent e) public void keytyped(keyevent e) ch = e.getkeychar(); str="you typed "+ch+" character"; repaint(); public void paint(graphics g) g.drawstring(str, 100, 150); /* <applet code="appletkeylistener.class" width="300" height="300"> </applet> */ Output: 27

164 Adapter classes: Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code. The adapter classes are foundin java.awt.event,and javax.swing.event packages. The Adapter classes with their corresponding listener interfaces are given below. java.awt.event Adapter classes Adapter class Listener interface WindowAdapter KeyAdapter MouseAdapter MouseMotionAdapter ComponentAdapter ContainerAdapter WindowListener KeyListener MouseListener MouseMotionListener ComponentListener ContainerListener Example program for MouseAdapter: Example: import java.awt.*; import java.awt.event.*; public class MouseAdapterExample extends MouseAdapter Frame f; MouseAdapterExample() f=new Frame("Mouse Adapter"); f.addmouselistener(this); f.setsize(300,300); f.setlayout(null); f.setvisible(true); public void mouseclicked(mouseevent e) Graphics g=f.getgraphics(); g.setcolor(color.blue); g.filloval(e.getx(),e.gety(),30,30); public static void main(string[] args) new MouseAdapterExample(); Output: 28

Answer1. Features of Java

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

More information

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

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

More information

JAVA OPERATORS GENERAL

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

More information

Prof. Navrati Saxena TA: Rochak Sachan

Prof. Navrati Saxena TA: Rochak Sachan JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

More information

STRUCTURING OF PROGRAM

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

More information

Java Overview An introduction to the Java Programming Language

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

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

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

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

More information

Index COPYRIGHTED MATERIAL

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

More information

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

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

More information

1 Shyam sir JAVA Notes

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

More information

Module - 2 Overview of Java History of Java Technology?

Module - 2 Overview of Java History of Java Technology? Overview of Java Module - 2 Java is an object-oriented programming language with its own runtime environment. Java is a programming language and a platform. Java is a high level, robust, secured and object-oriented

More information

Programming. Syntax and Semantics

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

More information

Sri Vidya College of Engineering & Technology

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

More information

Java Lecture Note. Prepared By:

Java Lecture Note. Prepared By: Java Lecture Note Prepared By: Milan Vachhani Lecturer, MCA Department, B. H. Gardi College of Engineering and Technology, Rajkot M 9898626213 milan.vachhani@yahoo.com http://milanvachhani.wordpress.com

More information

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

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

More information

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

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

More information

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

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

More information

3. Java - Language Constructs I

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

More information

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

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

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

More information

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

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

More information

Core JAVA Training Syllabus FEE: RS. 8000/-

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

More information

Chapter 1 Introduction to Java

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

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

Introduction to Programming Using Java (98-388)

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

More information

Special Topics: Programming Languages

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

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

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

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

More information

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must

More information

Pace University. Fundamental Concepts of CS121 1

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

More information

15CS45 : OBJECT ORIENTED CONCEPTS

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

More information

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

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

More information

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

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

More information

Full file at

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

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

More information

CS 231 Data Structures and Algorithms, Fall 2016

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

More information

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

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

More information

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

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

More information

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS Java language Part 1. Java fundamentals Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua What Java is? Programming language Platform: Hardware Software OS: Windows, Linux, Solaris,

More information

Program Fundamentals

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

More information

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

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

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

1 OBJECT-ORIENTED PROGRAMMING 1

1 OBJECT-ORIENTED PROGRAMMING 1 PREFACE xvii 1 OBJECT-ORIENTED PROGRAMMING 1 1.1 Object-Oriented and Procedural Programming 2 Top-Down Design and Procedural Programming, 3 Problems with Top-Down Design, 3 Classes and Objects, 4 Fields

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Java Professional Certificate Day 1- Bridge Session

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

More information

Operators and Expressions

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

More information

2 rd class Department of Programming. OOP with Java Programming

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

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

2. Introducing Classes

2. Introducing Classes 1 2. Introducing Classes Class is a basis of OOP languages. It is a logical construct which defines shape and nature of an object. Entire Java is built upon classes. 2.1 Class Fundamentals Class can be

More information

CSC 1214: Object-Oriented Programming

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

More information

Object Oriented Pragramming (22316)

Object Oriented Pragramming (22316) Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data

More information

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

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

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

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

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

More information

Course Outline. Introduction to java

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

More information

SELF-STUDY. Glossary

SELF-STUDY. Glossary SELF-STUDY 231 Glossary HTML (Hyper Text Markup Language - the language used to code web pages) tags used to embed an applet. abstract A class or method that is incompletely defined,

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

More information

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

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

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

CS11 Java. Fall Lecture 1

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

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

More information

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Introducing Classes A class defines a new data type (User defined data type). This

More information

JAVA Programming Fundamentals

JAVA Programming Fundamentals Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

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

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

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

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

More information

Java Programming Language. 0 A history

Java Programming Language. 0 A history Java Programming Language 0 A history How java works What you ll do in Java JVM API Java Features 0Platform Independence. 0Object Oriented. 0Compiler/Interpreter 0 Good Performance 0Robust. 0Security 0

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus PESIT Bangalore South Campus 15CS45 : OBJECT ORIENTED CONCEPTS Faculty : Prof. Sajeevan K, Prof. Hanumanth Pujar Course Description: No of Sessions: 56 This course introduces computer programming using

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information

Output :: /* display results */ System.out.print( Call Duration: );

Output :: /* display results */ System.out.print( Call Duration: ); Introduction 7 : JAVA BASICS Java is object oriented programming language developed by Sun Microsystems in 1991. A company best known for its high-end UNIX workstations. Modelled after C++ Java language

More information

Character Stream : It provides a convenient means for handling input and output of characters.

Character Stream : It provides a convenient means for handling input and output of characters. Be Perfect, Do Perfect, Live Perfect 1 1. What is the meaning of public static void main(string args[])? public keyword is an access modifier which represents visibility, it means it is visible to all.

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

13 th Windsor Regional Secondary School Computer Programming Competition

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

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Jagannath Institute of Management Sciences Lajpat Nagar

Jagannath Institute of Management Sciences Lajpat Nagar Jagannath Institute of Management Sciences Lajpat Nagar BCA Sem V JAVA UNIT I (8 Lectures) The Genesis of Java: Why Java? Flavors of Java. Java Designing Goal. Role of Java Programmer in Industry. Features

More information

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

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

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Introduction to Programming (Java) 2/12

Introduction to Programming (Java) 2/12 Introduction to Programming (Java) 2/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction

More information

Short Notes of CS201

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

More information

Lecture 1: Overview of Java

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

More information

Introduction to Java & Fundamental Data Types

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

More information

CS201 - Introduction to Programming Glossary By

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

More information

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

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

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

More information

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

VALLIAMMAI ENGINEERING COLLEGE

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

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Compaq Interview Questions And Answers

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

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

More information

CS201 Some Important Definitions

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

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information