CoreJava iNetSolv



Comments



Description

COREJAVAJAVA  Object Oriented Program is a programming approach in which a problem domain is characterized as a set of objects that have a specific attributes and behavior. The objects are manipulated with a collection of functions called methods or services. The objects are classified into classes and subclasses. (or)  An Object Oriented Programming organizes a program around its data, i.e., objects and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.  Java is an Object Oriented Programming (OOP) language used to design an application, which will run securely over the network1 and work on wide range of platforms. J2SE: - J2SE stands for Java 2 Standard Edition , it is a specification used to develop fundamental java application they may be standard or network. J2SE= Core Java + Advanced Java J2SE:- Java2 StandardEdition J2EE:- Java2 EnterpriseEdition J2EE: - J2EE stands for Java 2 Enterprise Edition, it is a specification used to develop business solutions for network (or) J2EE is a specification that provides an environment to run the web components and the enterprise components. J2ME:- Java2 MicroEdition J2ME: - J2ME stands for Java 2 Micro Edition, it is a specification used for developing wireless and Embedded System. Embedded System is software, which directly installed into hardware. Difference between Java1.4.1. and Java1.5 [www.sunjava.com,www.javasoft.com] Core Java – Desktop Java NIC– Network Interface Card NovelNetwork:- Net based softwaress Ex: - Windows NT, UNIX. Protocol: - This is also a program; it is a specification of set of rules to be followed by a computer in network. When to send/receive data How to send/receive data Hand Shaking: - This means two Computers establishing a connection communicating with each other and finally disconnecting is called Frame Hand shaking. A Packet represents a group of bytes. IP means Internet Protocol Packet address this is unique address this is given to Computers. TCP/IP:- Transmission Control Protocol/Internet Protocol. Client: - A Client is a machine that sends a request for some services to other Computer. Server: - Server is a machine that receives requests from the Clients and provides services to the Client requests. The main advantage of a network is resources sharing. Web application:- A web application is a collection of Servlets, HTML pages, Classes and other resources that can bundle and run on the multiple Containers from multiple Vendors. ResourcesSharing: Sharing memory 1 1 Network: - Complete network is interconnection & Autonomous systems that are used for communication or exchange of information between the two systems in the network, the systems, which are connected in the network, are called as hosts. Page 1 of 191 COREJAVA     Sharing data Sharing software Sharing hardware Sharing Processor 1969 Department of Defence (DOD), USA, Ken Thompsonis introduced network. This network is called ARPANET .    AT&T– Advanced Telephone Communication & Technology USA based Telephone Company. Hyundai, British Telecom are also Telephone companies, these three companies are giant of the Telephone.  Satellite AT & T Hyundai Server ISP Another Computer 50GBPS British Telecom ISP: - It stands for Internet Service Provider. ISP is a person or an organization, who provides connection into internet. ISP should take direct connection to internet. (www.internic.com).  Bandwidthis a group of frequency.  American Congress Library is a biggest Library in the World; the second biggest Library is Lenin Glad Library in Masco, (Russia). Q) Whatis an Interface?***** Ans: - An Interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but doesn’t implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. An interface is a named collection of method definitions (without implementations). An interface can also declare constants. Internet: - Internet is a network of Computers existing on the earth. Internet is a global network of all networks existing on the earth. ConnectingInternettypes:DialupConnection: Dialup connection main advantage is affordable to any one.  Disadvantage of Dialup connection is slow.  There is no security for data. 2. Leasedline Connection:- It is a direct connection to internet. Page 2 of 191 COREJAVA Advantages: High Security for data  Lightening Speed (i.e. high speed) Disadvantages: Highly expensive. The web browser2 software is installed on Internet Client. Ex: - Internet Explorer, Mozilla, Fire fox, Netscape Navigator etc… The software that should be installed on Internet Server is Web Server. WebServer:- A web server is a server that provides the implementation of HTTP protocol. Ex: - Internet information Server (IIS), Apache Web Server, etc… Application Server: - An Application Server is a product that provides the facilities like taking care of transactions, taking care of security and simplifies the development of business logic (or) Application servers provides you with common middleware services, such as resource pooling, networking and more. Application server allows you to focus on your application and not worry about the middleware you need for a robust server side deployment. Ex: - Microsoft Transactions Server (MT Server) from Microsoft, EJB containers like WebLogic, WebSphere, JBoss etc…  Hypertext Transfer Protocol (HTTP) is widely used protocol on internet.  File Transfer Protocol (FTP) , when we download a file from Internet.  Simple Mail Transfer Protocol (SMTP) is used to send mails on the internet.  Post Office Protocol (POP) is used to receive mails. Programmerhas: 1. To develop a web browser 2. To increase the capabilities of web browser 3. To develop a web server 4. To increase the capabilities of the web server 5. To develop protocol Translator is a program that converts a computer program into machine language (Electric Pulses). There are 3 types of translators 1. Interpreter Interpreter translates line by line of computer program 2. Compiler Compiler translates all lines of program at a single time 3. Assembler Assembler translates assembly language into machine language x.c x.obj Machine code Convert the Header file x.exe Full pledged machine code language instructions   C, C++, are not portable3 programs, they are system dependent because they can be executed only on that system where they are developed. The first microprocessor is - 4 0 0 4 The next microprocessors are follows as below 8008 8085 8086 80286 2 Web browser: - The web browser is a GUI based software is installed on Internet Client that allows the user to navigate www and web pages on Computer screen. 3 Portability: - Yielding on any Computer Page 3 of 191 PI.class JVM PIV It consists byte code format Celeron JVM JVM  The size of eachinstructionis 1 byte or 8 bits. Celeron. PIV.  JVM convert byte codeinstructioninto machinecode. PIII.java x.  JVM understand every byte code instructions. AMD. PII. Componentsof JVM JVM Class Execution Engine Byte code verifier Security Manager Garbage Collector  Sun Microsystems is developed the JVM program. It is not a machine.  There are around 210 byte codeinstructionsare available    Cyrix  Byte code instruction is understand by JVM4 (JavaVirtualMachine). PIV Pro WhyJavais suitablefor Internet x.Java Virtual Machine is a program.COREJAVA 80386 80486 8 0 5 8 6x. Page 4 of 191 . 4 JVM:. Tampering:. but *.  JVMis systemdependent.  Depending on operating system we have to download the operating system related JVM program. Java= C++. 4. 5 6 TCP/IP:.  For impersonation.Not only reading others data but also modifying it on Internet. Objectinitializationprocess:Default values → initialization expressions → initialization blocks → constructors Defaultvalues:float.Java is a simple programming language. Security manager is program that identifies illegal code and information security polices.  JVM is making as Java system independent. A . 3.0. HTTP:.classfile is systemindependent.Virus is a harmful program that can damage data.  Solution for virus is . SecurityProblemson Internet:1. solution is digital signature file.0 boolean false Reference variable null (not referring any object) Char ‘\u000’ (or) a space String Null My class Null 3. Page 5 of 191 .  Solution for eves dropping & tampering encryption/decryption.sys. An object has properties & performs actions. software & hardware of a system.Complexity “An object is existing of everything in the world is an Object”. C++. by that time some company is registered Oak name. for this reason they named as “Java”. 2. It has extensive libraries.exe. Encryption means converting data into understandable data.0F. In 1993. Sun world conference has given entire details of Java. Java is executable on any platform.Transmission Control Protocol/Internet Protocol. Sun Microsystems inc. Oak language is developed.  .txt files cannotcarryvirus. ObjectOriented:.  Javaprogramssystemindependent. Impersonation:. Distributed: .class file. In 1990. learning and practicing java is easy because of its resemblance (Similarity) with C.COREJAVA  JVM will understand the byte code instruction & it will convert the byte code instructions into P IV processor understandable machine language instructions. (James Gosling).doc.A person acting as another person on Internet is called impersonation.Java is designed for use on networks. Simple: .  Portability means giving same results on any type of system or machine..classis a text file viruscan’t be affected.  JVM will convert the byte code instructions into any type of processor understandable machine language instructions . USA is developed software for remotes. 2. Virus will spread to *.Unlike C++. Java is a purely object oriented programming language.  Java is a system independent. Decryption means converting data back to readable form.Hypertext transfer Protocol. *. which work in agreement with TCP/IP5. is called Tampering. double 0. Java uses protocols like HTTP6 & FTP.  Virus was first developed by Pakistani’s. In 1995. Evesdropping:. WhyJavais suitablefor Internet: Security problems on Internet are eliminated through java. containing personal information for identify the person in encrypted form. Virus:. is called Eves dropping.Reading others data illegally on Internet. Digital signatures are developed in java. Featuresof Java :1. *. Java is designed for use on internet.  In every java program we must create a single class. A method can be inheritedandit canbe overloadedor overridden. A method will returns a void or any valid return type.A methodhas calledexplicitly.  Robust means strong.  Method is a function.  Methods or functions can store only some temporary variables or local variables. Secure: .Java programs are compiled to generate bye code.COREJAVA 4. Q) Whatis the differencebetween. Using pointers harmful programs are written.  In JVM class loader sub system will allot the memory required for program. In java we will write only methods. Robust: . Interpreted:.  Unused memory released or free it by JVM  Garbage Collector will delocate or removes memory for unreferenced or unused objects and variables.exe file contains machine language instructions for the microprocessor.  Functioncanbe writteninside& outsideof the class.  C++ is not purely Object oriented programming  Internet is a distributed technology. Portable: . It is system independent. This byte code can be downloaded and interpreted by the interpreter. Page 6 of 191 . A functioncan be called& executeditself..  Garbage Collector can be called explicitly but there no gurantee that the garbage collector executes or not at that point. Writing a function outside the class is not possible in java. Function represents set of instructions to perform the results. These are lead to complex programs 2. Pointersare eliminatedfromJavadueto: 1. Architecture Neutral: . It is system dependent. A method must be starts with lowercase. 7.class file contains byte instructions for JVM.Java’s byte code is not machine dependent. 8.Mark & Sweep algorithm. Java enables the construction of virus-free. but not permanent variables. Q) Whatis the differencebetweenmethodand function?***** Ans: .Java programs will not crash because of its exception handling and its memory management feature. 6. it is writtenonly insideof a class.classfile? ***** Ans: . It can be run any machine with any processor and any operating system. Class doesn’t exist really becauseit is only an idea but objectsexist really. Portable means yielding same results on different machines. . in java we can write strong programs. Q) Whatalgorithmis usedby garbagecollectorto removevariablesor objectsfrommemory?***** Ans:.Java does not have implement-dependent aspects. So the results will be same on all machines.exe and. 5. but a method is a function. 3.  Garbage memory delocates the memory.  Exception means runtime error  JVM will allot memory to what ever we required memory.  A class will also contain variables & methods.  Java is suitable for distributed technology.e.A method is a function written only inside of a class but functions can be written any where in class i. JVM contain interpreter. inside or outside of the class.  An object will also contain variables & methods. tamper free systems.  A class is a model or idea or plan to create objects or Class is a group of objects. Pointers may crash a program. COREJAVA 9. High performance:- Along with interpreter there will JIT (Just in time compiler) , which enhances the speed of execution. Variable: - An item of data named by identifier. Each variable has a type, such as int or object and a scope. ReferenceVariable:- A data element whose value is in an address. LocalVariable:- A data item known within a block, but inaccessible to the code outside the block. For example, any variable defined within a method is a local variable and can’t be used outside the method.  A local variable life cycle ends when the execution of method completed. A local variable should declared within a method body and it must be initialized when we are declaring in a method, because it doesn’ttakesdefault values. PathVariable:- It is exterenal command file. A pathvariableis usedto specifywherethe executablefiles are. Ex: - javac.exe, java.exe, javap.exe etc. Argument:- A data item specified in a method called an argument. An argument can be a literal value, a variable or an expression (or) an argument is a value that is passed to the method when it is invoked. Parameter:- While defining a method, variables passed in the method called as parameter (or) Parameters are variables defined by method that receives values when a method is called.  Parameters are useful to pass the variables from objects to the constructor.  Method parameters are local variables to receive the data from out side for method.  Parametersare usefulto receivethe valuesfromoutsideto mainmethod.  Whatis the differencebetweenparameterandargument?***** Ans: - While defining method, variables passed in the method called as parameter. While using those methods, values passed to those variables called arguments. Process: A virtual address space containing one or more threads (or) a program under execution is also called as process. Peer: - In networking, any functional unit in the same layer as another entity. Expression:- An expression is a series of variables, operators, and methods calls, (constructed according to the syntax of the language) that evaluates to single value. Howwouldyou detectandminimisememoryleaksin Java:In Java memory leaks are caused by poor program design where object references are long lived and the garbage collector is unable to reclaim those objects. Detectingmemoryleaks: Use tools like JProbe,OptimizeIt etc to detect memory leaks. Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems. Write your own utility class with the help of totalMemory() and freeMemory()methodsin the Java Runtimeclass . Place these calls in your code strategically for pre and post memory recording where you suspect to be causing memory leaks. An even better approach than a utility class is using dynamic proxies or Aspect Oriented Programming(AOP) for pre and post memory recording where you have the control of activating memory measurement only when needed. Minimisingmemoryleaks: In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to objects of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the references to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any issues because the garbage collector is smart enough to deal with the circular references. JVMArchitecture:- JVM 1.4.1 version developed by Hotspot. Page 7 of 191 COREJAVA Class Loader Subsystem Class files Method area Heap Java Stacks runtime data areas PC registers Native method stacks Native method interface Execution Engine Native method libraries Classloadersubsystemdoesthe followingthings:1. It will load .class file into memory (RAM) 2. It will verify byte code of that .class file. 3. It will allot the required memory for the program. This memory is divided into five parts; they are called runtime data areas. 1. Methodarea: - It stores classcode , staticvariables , staticblocks and methodcode . 2. Heaparea: - Objects are created on Heap. JVM creates objects on Heap. 3. Java Stacks:- Java stacks are used to executethe java methods . Java stackswill haveframes . On each frame a separatemethodis executed. 4. PC Registers:- These registers contain the addressof that instructionto be executedby the processor. 5. Native method stacks: - It is a method written in a language other than java. Native method stacks places when native methods are executed. Note: - Native method interface linksheaderfiles to a nativemethodwhile it is being executing.  Execution engine contains interpreter & JIT compiler , which translates byte code into machine language. How JIT compiles converts byte codes. Ex: print a; 2sec For Interpreter print b; 2sec Repeat the loop 10times; JIT Compiler Processor print a; 2 + 2 memory  Hotspot is the block code of given to JIT compiler for execution. 10. Multithread:- Thread means an execution or processing group of statements. Executing different parts of a program simultaneously at a time by using more than one thread is called Multithreading. This is an essential feature of to design server side programs. 11. Dynamic: - It means at runtime, we can develop programs in java, which dynamically change on Internet. (Ex: Applets).  In java entire memory will be dynamic memory. JavaProgramming :• Comments represent description of the features of a program. • The main advantages of comments are readability7 of the program is increased. There are 3 types of comments in Java. They are 7 Readability = Understandability. Page 8 of 191 COREJAVA 1. Singleline comments:- It represents only one line as comment. Single line comments start with //. Ex: //Welcome INet Solv //welcome to Java 2. Multi line Comments:- They represents a group of lines as comment. They starts with /* and end with */ Ex: - /*Welcome to India*/ 3. JavadocumentationComments:- They starts with /** and end with */. Ex: - /**Welcome to BTCE*/  These comments are useful to create .html documents from .java programs. API Document: - API stands for Application programming Interface. It is a .html document that contains description of all the features of a software or a product or a technology. API document does not contain code. Javadoc complier is used for this.  Comments are non executable statements. These 3 types of comments are not executable by java compiler or JVM compiler.  In Java we can define/write any number of classes in a single class. Out of n number of classes we are writing in a single class only one can be defined as public class, because the name of the class should be public class.  If we need all the classes as public we have to decalred/write sepeartely each class as public. ExampleProgram:/*This is our first Java program. To display a message Author: INet Solv team Version8: V 1.0 Project: Proxyz 1.11 */ //Starting a program in Java import java.lang.system; import java.lang.string; or in the place of two steps directly we can write as below import java.lang.*9; class First Java library { 10 main () It contains group of packages { --------------Packages --------------It is a sub directory & it contains --------------group of class/interfaces } Class/Interfaces } It contains group of methods Methods Q) Whatis the differencebetween#includeandimportstatements?***** Ans: - #include makes C/C++ compiler to copy the header file into a C/C++ program. Thus it wastes the memory and processor time. import will makes the JVM to go to a particular class, it executes the code there and then it comeback to the program and substitute the results in the program. JRE:- It stands for Java runtime environment. JRE= JVM+ Javalibrary If java programs have to run we required the JVM and java library. JVM will starts execution of java program from main method only. 8 9 VersionV 1.0: - 1 represents major version and 0 represents minor version. * means all the class/interfaces are java.lang are known available. 10 main() is a called as main method. It is a group of statements. Page 9 of 191 e.COREJAVA  String represents group of characters.methodName().). Page 10 of 191 . Ex: . We canprovidea securityfor a classas below: public static void main(String args[ ]){ 11 12 mainis a method. All the methods in the System class are static methods.  Save the name with in double quotations to avoid the extension of . Ex: .  gc() out: .  Void means no value (i.A System class will have static members. etc.  Properties getProperties() (Property is a class in java. To create on object to the class to which method belongs Classname obj = new12 Classname(). end. Public: .println(): System: . properties of JVM and etc. import java.*.First f = new First(). JVM will not run the public without writing String args[].lang.).It means available outside the object. SystemClass:.main(). monitor etc… and to get and set the properties associated with java runtime system.lang package that provides the access to the system resources like Keyboard. it returns no value). println(): . version.txt. that is a group of statements.  arrayCopy(Object[ ]. Array denotes with [ ]  The values passed to the main method are called command line arguments.System is a predefined final class which is defined in java.out. (∴f = object) 2.out is a static variable defined in a System class of the type PrintStream class.util package and getProperties() method is usefull to set/get the property of a class.  Array represents group of elements. newis an operator. they are as follows below  PrintStream out.println() is a built-in overloaded method in the out object or the PrintStream object supports the print() or println() methods for all data types. Object[ ]. For single character in java we have to write in single quotations like as ‘a’ and for integer don’t write in any quotations. Call the method using object name.f. err  InputStream in. It is a static variable or filed. which provides all of the formatting capabilities we have been using from the system file handler or out is the PrintStream object. System.methodname Obj. st)  exit(int)  loadLibrary(String)  get/setSecurityManager(SecurityManager)  String getProperty(String)  String getProperties(String str) (getProperties() method is usefull to get the JVM name. 14 Out is a variable.Out is a variable of a system class.  Objectsare createddynamically(runtime)by JVM Staticmethod:. JVM could not executes the main method.It is a method that can be called and executed without creating an object. st. class First { main11() { ------------------------------------} } To call methodthereare twosteps:1.out14: . 13 Systemis a class. 13 System . setSecurityManager(new SecurityManager()). //Now find sum int c = a + b. class Sum { public static void main(String args[ ]) { //Variables int a.*.COREJAVA System.  Public is written to make available main method to the JVM.java↵ (This is for program compilation) C:\rnr>java Sum. Ex 2: //To find sum of two numbers import java.  Command line arguments are passed some values to the main method. b = 15. (∴* is a String class) class Sum { ( { ----This is for starting of class) public static void main(String args[ ]) (String args[ ] is a parameter) { //Variables int a. //Store data into variables a = 10. b = 15. } } (∴} ----This is for ending of class) (or) //To find sum of two numbers import java. println method displays the results and then throws the cursor to the next line.lang.lang.java↵ C:\rnr>java First↵ Welcome to java  Class. ------------------------------------------} To Compile:C:\rnr>javac First.*.out. b.  Main method does not return any value.  S. //display the result System. Backslashcodes or escapesequence Page 11 of 191 Meaning . } } Save the above file (withclassnamecompulsory) as “Sum. No.out.println(“Sum = ”. //display the result System.  Functionis writteninside& outsideof the class. b. interface contains methods.println(“Sum = ” + (a+b)). but methodsare writtenonly insideof the class.java” C:\rnr>javac Sum. //Store data into variables a = 10. print method displays the results and keeps the cursor in the same line.+c).java↵ (This is to run the program) Note: 1. 2. Void means no value.  JVM always starts execution of the statements inside of the main method.  Class is model for creating objects.rmi means remote method invocation18.sql: . 4. java.println(). java. Servlets are server side programs. into memory locations). java.java. getChars.This package got primary classes and interfaces essential for java language. strings. employee_Net_Sal etc… 5. java.  Java is case sensitive programming language. LinkedList. Hashtable. The objects.util (util = utility): . 6.sql stands for structure query language.PI.Servlets are server side programs which communicate several clients at a time. The classes in this package have been derived from other package. which travel form one place to another place on internet. java. In case we have to write methods & variables. They can be developed using this package. DataInputStream. This package helps to connect to databases like oracle and utilize them in java. javax. Constant variables should be written using all capital letters. then each word start with a capital letter. This package helps to develop GUI like java. 18 Invocation= Calling Page 12 of 191 .lang: . Ex: age.e. It consists of wrapper classes. javax. Packages names in java are written in all small letters. 9.x stands for extended package. NamingConventionsin Java:1. 3.awt. StringBuffer. which handle clients.applet: .  Data types represent the type data stored into variable (i. MAX_VALUE.servlet: . java.awt (awt = abstract windowtoolkit): . Ex: . 7.This package handles files and input/output related tasks.  Wrapper classes are useful to create objects  String is a class in java  Multithreading means create several threads (processes executing) at a time.Applets are small intelligent programs. 2. Ex: . getNumberInstance() etc… 4. readLine().This package contains useful classes and interfaces like stack.awt.io. java. 15 16 FONTis a class BOLDis a constant 17 Network:. 4.event and java. This package is useful to develop servlets. 3.This package helps to develop GUI (Graphical user interface).swing:. 2. Ex: . java. java. 5. 6. Ex: .BOLD16 Note: . \n \r \t \b \\ \“ \‘ New line Enter key Horizontal tab Backspace key \ “ ‘  In java every statement must end with semi colon (. It uses TCP/IP internally.beans:. empName. Importantpackagesof Java:1. FONT15.net: .awt.String.lang is a package that is by default imported into every java program. Arrays etc. multithreading etc. 8.swing etc… 3. which exist on one computer in the network.Beans are software reusable components.io:. java. Client/Server programming can be done using this package. ActionListener etc… 2. It consists of 2 important sub packages. 7. The other packages must be imported in java program. Method names start with a small letter. 10.Interconnection of computers are called as network.net stands for network17.COREJAVA 1.rmi: .). can be invoked from another computer and can be used.java.image. 5. namely: java. Each word of class names and interface names start with a capital letter. 11. Variables names also follow the above rule.awt. java. 6. long x = 150L. S. 2.7e308 to + 1.It represents a single characters. 1.literal)  Literal means the constant value being directly storing into variable. 3. Datatype (Single precision ) float Double precision Memorysize 4 bytes 8 bytes Min & Maxvalue -3.e.no = 10 (0 .char ch = ‘x’. No.It represents integer numbers i. Double can represents up to 15 digits after decimal point accurately. 2. 7.4e38 to + 3. 8.byte r.A data type represents the type of data stores in memory (variable). L means take that number forcibly as long integer to allot the memory as user defined. 2.4e38 to + 3. Datatype char byte short int long float double boolean MemorySize 2 bytes 1 byte 2 bytes 4 bytes 8 bytes 4 bytes 8 bytes 1 bit Min & Maxvalue 0 to 65535 -128 to 127 -32768 to +32767 -2147483648 to +2147483647 -9223372036854775808 to +9223372036854775807 (or) -9. Datatype byte short int long Memorysize 1 byte 2 bytes 4 bytes 8 bytes Min & Maxvalue -128 to 127 -32768 to +32767 -2147483648 to +2147483647 -9223372036854775808 to +9223372036854775807 (or) -9.2 x 10-18 to 9.142F. Ex: . float data types:. 1. No. Ex: . Such number’s called floating data type. 5. 1. 1. No.) Whatis the differencebetweenfloat anddouble?***** Ans:.float can represents up to 7 digits after decimal point accurately. S.They can handle numbers with decimal points. Integerdata type: . Subtype: S.7e308 Q. 3. ASCII – American standard code for information interchange. No. Subtype:S.  F represents forcing the JVM to take the value as float because JVM defaultly takes any decimal values as double.2 x 10-18 to 9.COREJAVA Data typesandliterals:.7e308 0 or 1 Datatype Char MemorySize 2 bytes Min & Maxvalue 0 to 65535 Keyboard consists 114keys . the numbers without decimal points. Page 13 of 191 . 4. 4.2 x 1018 Ex: .4e38 -1. Keyboard consists up to 200 characters only.2 x 1018 -3.4e38 -1.float PI = 3.7e308 to + 1. Characterdata type: . Completelist of Javakeywords:abstract char double for int private strictfp throws assert Transient:. } } Operator:. If an operator acts upon two operands is called binary operand. if (s instanceof String) { System.String name “Inet solv”.String represents a group of characters. Unicode uses 2 bytes to represent single character. Note: . we mean class or interface-in other words. 4. As these variables values could be changed unexpectedly. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimization on the variable. String str = new String (“A String”). Ex: . ` a+b (∴ a.out. Ex: .An operand is a variable on which operator acts upon.  Transient variables aren’t appropriate for equals()and hashCode() methods. It is called unary operator. If an operator acts on three operands is called ternary operand. it is then vital that reading & writing of the value in the copies and the master variable do not result in any inconsistency. threads might cache the values of member variable for efficiency reason.COREJAVA Q) Whatis Unicode?***** Ans:. + is the operator) Operand:.print("s is a String"). instanceof will still return true if the object being compared is assignment compatible with the type on the right. Stringdata types:. if the object referred to by the variable on the left side of the operator passes the IS-A test for the class or interface type on the rightside. Strings are objects of string class in java. instanceOf: . b are operands. An operator may act upon a single operand.They store either true or false. indicating that its value need not be saved when objects of its classes are put in persistence storage or it prevents fields from ever being serialized.In multithreading environment.A value of an instance variable in a class will not persistent when the object is stored.An operator is a symbol that represents an operation. such an instance variable can be specified as transient variable. Even if the object being tested is not an actual instantiation of the class type on the right side of the operator.That the transient modifier cannotbe specifiedfor static variables as these do not belong to objects. Operatorsin Java:1. It can handle only two values. Transient fields are always skipped when objects are serialized. class A { public static void main (String [] args) { String s = new String("foo"). Booleandata type: . Volatile: . ArithmeticOperators:+ * / % Page 14 of 191 boolean class else goto interface protected super transient Break Const Extends If Long Public Switch Try byte continue final implements native return synchronized void case default finally Import new short this volatile catch do float instanceof package static throw while .The instanceof operator is used for object reference variables only.boolean response = true.Unicode is specification that includes the alphabetic of all international languages into java character set. Since threads can share a variable. and you can use it to check whether an object is of a particular type. By type. name. Writing ++ after a variable name is called post incrementation. UnaryOperators:. 3. 5 System.int x = 1.?: 9.o.out.println(x). 4. BooleanOperators:& | ! 7.o.printlin(-(-(-x))). TernaryOperator(ConditionalOperator):. Ex: .  In pre incrementation.  In post incrementation any other task is done first.printlin(-(-x)). InstanceofOperator:. 1: . (Negation means converting – value into + value vice versa).println(x++).getsal() c) To refer a variablein a class:Employee.println(x).0.COREJAVA 2.println(x). S.printlin(-x). S. -5 System. S. Ex. 5. LogicalOperators:&& || ! 6.o.o.out. System.name 10. -5 IncrementOperator(++): .out.++ -3.To test whether an object belongs to a class.These operators perform basic arithmetic calculations like addition. 2.out.o. Ex: int x = 1. RelationalOperators:< <= > >= == != 5. BitwiseOperator:a) Bitwise Compliment: ~ b) Bitwise and: & c) Bitwise or: | d) Bitwise xor: ^ e) Bitwise left shift << f) Bitwise right shift >> 8.): a) To refer a classin a package:. b = 5 S.6 3 UnaryOperatorsor Unaryminus(-) Operator:.println(x) S. incrementation is done at the end.printlin(x).emp instanceof Employee. emp. -5 System. AssignmentOperators:= += -= *= /= %= 4. Ex: int x = -5.This operator negates the value of a variable.This operator increases the value of a variable by one.println(++x). int x = 1. S. subtraction. ++x 2 x++  3 x=x+14 Writing ++ before a variable name is called pre incrementation. No. Output Output 1 1 2 1 2 2 Page 15 of 191 .util.Date b) To refer a methodin class:math.pow() emp. S. Dot Operator(. Operator + * / % Meaning Addition Subtraction Multiplication Division Modulus operator (Remainder of division) Example a+b a–b a*b a/b a% b Result 18 8 65 2.java. incrementation is done first any other task is done next. Arithmetic Operators: . etc… Ex: a = 13. 1. Ex: .int y = x. a = b++. AssignmentOperator(=): 1..int x = 15.These operators act upon individual bits of a number. b = 2.These operators act upon Boolean variables and they return Boolean value.true BitwiseOperators:.What is the value of the following expression. BooleanOperator:.. It can store the value of an expression into a variable. if(!(x==1))……………………. --x  0 x-. -1 x=x–1-2 Writing – before a variable is called pre decrementation. CompactNotation:a = a + 10  a +=10 b = b – 100  b -=10 j=k*j  j *=k i = i/10.not Ex: if(a>b && b>c)…………….false !b . a=3 a=2 b=3 b=3 Ex 3: .  i/=10 p = p%10  p%=10 Relational Operators: .COREJAVA Ex. It can store the value of variable into another variable.true b|b . They are used to constant conditions. if(a==100||b=50)…………. 2.false a & a .. if a = 7? ++a*a++.. Convert45 into binary:.. if(a==100)…….false !a .and || = or ! . It is used to store a value into a variable. [ b ] a) 49 b) 64 c) 56 d) 72 e) None of these DecrementOperator(--): .. 3.a = 1. & Boolean and | Boolean or boolean a = true.These operators are useful to compare two quantities. writing after a variable is called post decrementation. int x = 1. if(x!=y)………. Combining more than one condition called Compound condition... a & b . Logical Operators:.. Note: .Divide the number successively by 2 and table remainders from bottom to top.These operators are useful to combine more than one condition. && ..At the left hand side of assignment we should use only one variable. Ex: . 45 0 0 1 0 1 1 0 1 22 – 1 11 – 0 5–1 Page 16 of 191 . > < >= <= == != Ex: if(a>b)………. boolean b = false.This operator decreases the value of a variable by one. a = 1.int z = x + y – 10. b = 2. Ex: .. 2: . a = ++b. This operator performs exclusively oring operations on individual bits a b a|b 0 0 0 0 1 1 1 0 1 1 1 0 XOR gate Ex: .x = 10. x = 10 x >>2 x >> 2 x = 10 0 0 0 0 1 0 1 0 Page 17 of 191 .COREJAVA 2–1 1–0 0–1 Converting00101101into decimal:. x | y =? x = 0 0 0 0 1 0 1 0 y = 0 0 0 0 1 0 1 1 x | y= 0 0 0 0 1 0 1 1 = 11 Bitwise Xor (^): . -3 ~x = -11.x = 10 y = 11.^ is called as Circum flex or Cap or caret.This operator performs or-ing operations on individual bits a b a|b 0 0 0 0 1 1 1 0 1 1 1 1 OR gate Ex: . Ex: int x = 10.This operator performs anding operations on individual bits -4 a b a & b This table is called truth table. x & y =? x = 0 0 y = 0 x&y = 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 1 0 3 2 1 = 10 Bitwiseor (|): . Ex: . 0 0 1 0 1 1 0 1 x x x x x x x x 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 0 + 0 + 32 + 0 + 8 + 0 + 0 + 1 = 45 -1 -2 BitwiseCompliment(~): .Multiply the bits by the powers of 2 & take the sum of those products.x = 10 y = 11.This operator shifts the bits towards left a specified number of times. it shows 0 0 0 0 input and output bits 0 1 1 1 0 0 1 1 1 AND gate Ex: .x = 10 y = 11. x << 2 =? x = 10 0 0 0 0 1 0 1 0 x<< 2 0 0 1 0 1 0 0 0 = 40 Bitwiseright shift (>>): . x = 10.This operator performs shifting of bit towards right a specified number of times.This operator gives complement from of a number. It means. Bitwiseand(&): . x ^ y =? x = 0 0 0 0 1 0 1 0 y = 0 0 0 0 1 0 1 1 x^y = 0 0 0 0 0 0 0 1 =1 Bitwiseleft shift (<<): . name 3.COREJAVA x >> 2 0 0 0 0 0 0 1 0 =2 Bitwisezero fill right shift (>>>): Q) Whatis the difference>> and>>>?***** Ans:. This gives better control for the programmer on the flow of execution.println(“x ^ y” = +(x^y)). For this reason it is called zero fill right shift.out.sqrt() br. x = 10.out emp. } } TernaryOperator:. In Random execution the programmer can executive any statement directly or repeatedly.out.method() or objectname.read instanceOfoperator: .out. System. Ex: //Bitwise operators class Bits{ public static void main (String args[ ]){ byte x. packagename.out.This operator acts on three variables i.println(“~x = ” +(~x)). Syntax:var = exp1?exp2:exp. y = 11. It always fills the sign bit with 0. max = (a>b)?a : b. >>> also shifts the bits towards right but does not preserve the sign bit. classname. Random execution is possible by using control statements. System.y. Page 18 of 191 . System. System. classname.var (to refer variable) System.out. This operator works like a conditional if-else statement.classname (to refer classname) java.io.BufferedReader 2. it will takes three variables.>> shifts the bits towards right and also preserves the sign bit (0 for positive and 1 for negative sign). (or) if(a>b) max = a.It is denoted as instanceof.method() (to refer method)] Math.out. System. Executing the statements one by one by JVM is called sequential execution. else max = b.e.e Boolean values.) operator:1. So this operator is called as conditional operator.println(“x >> y” = +(x>>y)).var or objectname. System.objectname instanceof classname Ex: br instanceof BufferedReader This operator returns true of false i. Syntax:. It is used to test whether the object belongs to that class or not.println(“x & y” = +(x&y)). dot (.println(“x << y” = +(x<<y)). In sequential execution programmers does not have better control on the flow of execution.println(“x | y” = +(x|y)). Ex: //To display numbers from 1 to 10 Class Demo { public static void main(Static args[ ]) { int n = 1.java↵ C:\rnr\java Demo↵ Output:-15 is negative. do….This statement performs a task (one or more statement) depending upon whether a condition is true or not.println(“x+” “is positive”). do{ System.java↵ Page 19 of 191 . break statement  A loop can be executed repeatedly.COREJAVA Control Statements : . else statement3. while loop 6.println(“x+” “is negative”). }while(condition). else System. return statement 3.Control statements modify the flow of execution and give better control for the programmer on the flow of execution. continue statement 2.This loop repeatedly executes a group of statements as long as a given condition is true. Syntax1:if(condition) statement1. Syntax:.while loop 5.out. If…else statement: . if…else statement 4. else statement2.  Storing starting value into the variable is called initialization.out. Syntax2: if(condition1) if(condition2) if(condition3) statement1.] Ex: //Test if a given number is +ve or –ve class Demo { public static void main (String args[ ]) { int x. }while(n<=10). [else statement2. Without control statements programmers can not able to write better programs. x = -15.out. n++. for loop 7. 1.do { statements. Do…whileloop: .println(“It is zero”).println(n+ “ ”). switch statement 8.out. else statement4. A statement can be executed once only. else if(x>0) System. if(x==0) System. } } C:\rnr\javac Demo. } } C:\rnr\javac Demo. println(i). exp2.This loop repeatedly executes a group of statements as long as a condition is true.COREJAVA C:\rnr\java Demo↵ Output:1 2 3 4 5 6 7 8 9 10 Whileloop:.This loop repeatedly executes a group of statements as long as a condition is true. Ex: //Demo of for loop class Demo { public static void main(String args[ ]) Page 20 of 191 . exp3 is modifying the value of variable. exp2 is checking condition expression as long as the condition is true. i = i + 2. [ i += is called compact notation] } } } (or) //To display even numbers up to 10 class Demo { public static void main(String args[ ]) { int i = 2. i<=10. } exp1 is initialization expression. exp3) { statements.println(i +=2).out. for loop: .We can write for loop without exp1 or exp2 or exp3 or any two expressions or all three expressions. } } }  Q) Do…whileandwhile loops.out. or i +=2. Right from beginning of the execution it provides control to the programmers.whichloopis efficient?***** Ans:.out. while(i<=10) { System. while(i<=10) { System. Syntax:while(condition) { (statements).While loop is efficient. } Note: .println(i). i++) { System. Syntax:for(exp1. Ex: for(int i = 1. } Ex: //To display even numbers up to 10 class Demo { public static void main(String args[ ]) { int i = 2. j++) { statements.This statement is useful to selectively execute a task from a group of available tasks. } } Note: . i++) { for(int j = 1. case ‘w’: System. } Infinite loop[for( .We can write a for loop inside another for loop. for( .out. )]: .] } Ex: //Using Switch class Demo { public static void main(String args[ ]) { char color = ‘g’.println(“Blue”). case value2: statement2. ----------------------case valuen: statementn. case value3: statement3. } } } (or) int i = 1. i<=4.println(i). break. break.println(“White”).COREJAVA { for(int i = 1. . } } SwitchStatement:.Infinite loop is a loop. case ‘b’: System. It is a bad programming. This type for loop is called Nested for loop. i<=3. . ) { System. Page 21 of 191 . . These are drawback of programs. i<=10.out.println(“Green”).println(“Red”). i++. { statement. for( . break.out.out. statements. switch(color) { case ‘r’: System. if(i>10)break.out. case ‘g’: System.out.println(i). Syntax:switch(var) { case value1: statement1. break. Ex: for(int i = 1. [default: default statement. }while(true). ) do{ while(true) { statements. i++) { System. which executes forever. } System. Break is used to goto end of a block19. } } } 19 20 Block:.out. } Systen.1. Page 22 of 191 .This statement continues the next repetition of a loop and sub sequent statements are not executed. i--) { if(i>5)continue.out. Break is useful to the come out of the switch statement. } } }  Switchstatementmoresuitablefor menudrivenprograms.println(“No Color”). } System.Block represents a group of statements written in left and right braces. which is useful to come out from the loop. bl1: { bl2: { bl3: { System. goto statements make documentation20 of program very difficult.println(“Block 3”). Ex: //break as goto class Demo { public static void main(String args[ ]) { boolean x = true. i<=1.continue.out. goto statements form infinite loops.Break is a statement. } } Continue: . Syntax:. 3. Break:. To come out of a loop. Documentation:.COREJAVA default: System. Syntax:. 2. goto statements are decreases the readability of a program.out. goto is not part of structured programming.println(i).Documentation is preserving a copy of a program for future use. Algorithm consists step by step to solve a program.out.  Factorial representation of all the steps of an algorithm is a flow chart. Q) gotostatementsare not availablein java why?***** Ans:.println(“Out of all). It is used in three ways. 2. Ex: //Continue class Demo { public static void main(String args[ ]) { for(int i = 10. 4. It is used to come out of a switch block.println(“Block 1”).break blockname. if(x==true) break bl2.out. System. 3.println(“Block 2). 1. i--) { if(i<5)continue. It is used to come out of a method to the calling method. } } } C:\rnr\javac Demo.out.return. i<=1. System. System.exit(1)?***** Ans:. Syntax:return x.]   Whatis the differencebetweenSystem. System is a class name and exit is a method. return (x+y). } } [ Where in System. 2.println(“Before return”).COREJAVA C:\rnr\javac Demo. System. System.exit(0) is represents normal termination. Ex: //return statement in main() class Demo { public static void main(String args[ ]). Homeworkprograms:Page 23 of 191 .println(i).java↵ C:\rnr\java Demo↵ Output:10 9 8 7 6 5 returnstatement:1. return statement can return a value to the calling method. in the place of above statement return.println(“After return”). Syntax:.System.exit(0)and System. if(x==1)return.out.exit(1) is represents termination with errors.java↵ C:\rnr\java Demo↵ Output:5 4 3 2 1 Ex: . return y.ot.exit(0). // or we can use as here System.//Continue class Demo { public static void main(String args[ ]) { for(int i = 10.exit(0). { int x = 1. To move data we need stream.  Keyboard is represented by System.It represents flow of data from one place to another place .io.in [ System is a class] System. It accepts the data form InputStreamReader.It receives or reads data. BufferedReader BufferedReader: . Attach the keyboard to InputStreamReader.io.err()?***** Ans:.package.’s upto 100? 2. import java.? 6.in InputStreamReader obj = new InputStreamReader(System. To print odd no.It is one type of InputStreamReader.InputStreamReader reads the data from keyboard. Page 24 of 191 .err  PrintStream obj Monitor  Q) Whatis the differencebetweenSystem. To create an object InputStreamReader Class obj = new Class() System.out.read().println(“Enter a single char: ”). is even or odd? 3.  Streams are represented by classes in java.println(“Error message).  Streams are represented by input/output devices. 3. Thus we are achieving system independent.System. 1.It sends or writes data to some other place. There are two types of streams are available.println(“A normal message”). Test whether a no.  By using streams we can handle hardware components even though Input/output are channel we need not to change the stream in java program.out. //read data from BufferedReader System.in). 2. Display the stars in this below form? * * * * * * * * * * Acceptinginput fromKeyboard:Stream: . Test whether a no. 21 Exception:. is prime or not? 4. Attach the InputStreamReader to BufferedReader BufferedReader br = new BufferedReader(obj). Input Stream:.System. InputStreamReader:. System. Ex: .out()andSystem. 2.*.in  InputStream obj Keyboard System. Read data from BufferedReader using read() or readLine() methods. //Attach the InputStreamReader to the BufferedReader BufferedReader br = new BufferedReader(object). Ex: .out  PrintStream obj Monitor System.It means runtime error.out is used to display normal messages and results. 1. Calculate factorial of given no. Ex: //Accepting a single char from Keyboard.in). OutputStream:.err is used to display error messages. Char ch = (char)br. class Input { public static void main(String args[ ]) throws IOException21 { //Attach the keyboard to InputStreamReader InputStreamReader obj = new InputStreamReader(System.err. It is connected to InputStreamReader. Display a multiplication table? 5.COREJAVA 1.System.  When we are using read() method in rare conditions we will get runtime errors.parseInt(str).io. We have to write float n = Float.io. Acceptinga String:String ch = br. readLine takes 255 characters.print(“Sex :”+sex). System.parseFloat(br.parseFloat(str). (or) float n = Float.out.parseInt(br.out. } }  br. System.in)).read() to give in char value [ Char ch = (char)br.read() returns int values so we have to use (char) before the br.println(“ID :”+id).print(“Employee sex: ”). so to eliminate this error we have to use throws IOException.out.COREJAVA System.readLine()).readLine(). int n = Integer. int id = Integer. System.]  Converting one data type to another data type is called typecasting or casting .print(“Enter int No.out. System.  read() method cannot read more than one character. Char sex = (char)br. Ex: //Accepting int value import java. ( ) is called as casting operator. //parseInt(str) is a static method in Integer class System. String str = br. String Name = br. ”).println(“Number =”+n).*. }  Page 25 of 191 . class Input { public static void main(String args[ ])throws IOException { //create BufferedReader object to accept data from keyboard BufferedReader br=new BufferedReader(new InputStreamReader(System.*.parseDouble(br.print(“Employee ID: ”). //Display Employee Data System. } } parseInt(str) is a Static method in a integer class Acceptinga float Numberfromkeyboard:Same as above but in the place of int n = Integer. br. System.readLine().in)). Ex: //Accept & display Employee Details import java. Acceptinga doublefloat Number:Same as above double n= Double. //Accept Employee Data System.read().println(“You Entered: ”+ ch).out.println(“Employee Data: ”).read().readLine(). System.readLine()).out.skip(2).out.out. class Input { public static void main(String args[ ]) throws IOException { // To accept data from keyboard BufferedReader br=new BufferedReader(new InputStreamReader(System.readLine)).out.out.print(“Employee Name: ”).parseInt(str).print(“Employee Name :”+Name). parseInt[br. 4D. ‘c’} .readLine().skip(2) is used to eliminate the enter key = \r. Index represents the position of an element in the array. Memory allocated by JVM is 55 57 68 70 69 [0] [1] [2] [3] [4] Marks 55 = marks[0] or Marks[ i ] where i is an integer number that indicates position of the element in the array. char ch[ ] = {‘a’. 13.3f}. i<n. marks[2] = 80.8.….of. i++).5. One dimensional array consists only one index.. 5D. We can create 1D array by declaring & initializing it directly. 17.13.34. Ex: int marks[ ] = new int[10]. Double sal[ ] = new Double[100]. Ex: int marks[ ] = {55.A One dimensional array represents a single row or a single column of elements.21.There are 2 ways 1. Page 26 of 191 . //Create array with size n int marks[ ] = new int[n]. division.…) 4) Print prime no series (2. 11.1. 2) Print even no’s between m & n 3) Print Fibonacci series (0. Programs: 1) Accept 2 numbers from keyboard & find the result of their addition.*.. multiplication. ‘b’.in)). i is also called as index.readLine() it will get.read () & br. String name[ ] = {“raj”.. String s[ ] = new String[50].arrayname. marks[0] = 50. Because when we are using br.print(Enter marks: ”).out. { System.5f. float x[ ] = {1. 7.println(“How many subjects? ”). System.56}. 5. } //Find Total int tot = 0.) ARRAY:An Array represents a group of elements of same data type.3.23. Two dimensional array (2D) 3) Multidimensional array (3D. One dimensional array (1D) 2.1. class Arr1 { public static void main(String args[ ]) throws IOException { //To accept data from keyboard BufferedReader br = new BufferedReader(InputStreamReader(System. 2. “kamal”. NOTE:.) Onedimensionalarray: . //Store marks into array for(int i=0. 3.COREJAVA  } br. int n = Integer. 2) WeScan create a 1D array by using “new” operator and later we can store the elements in that array. There are 3 types of arrays 1.out. We can represent several elements in a single array.Marks obtained by a student in 5 subjects are: 55 64 66 74 24 CreatingOnedimensionalarray:. marks[1] = 60. “sita”}.readLine()).lengthgivessize of array .parseInt(br.io. Ex: // Find total & percentage of marks import java. marks[ i ] = Integer. subtraction.87.2. Ex: . 5f}. i<3. 2. 51. 1.out.4f. r1 r2 r3 C0 C1 C2 C4 1D array is a combinations of several 1D array marks[ i ] [ j ] In this i and j are indexes. 64}. We create 2D array using new operator and we can store elements in to it. but in java every thing is created on dynamic memory  Only one for is enough to handle One dimensional array. } } Page 27 of 191 . 64 Student3 – 70. 72. 73. 2. j<4.out. 3.4f.println(marks[ i ]).3f. 3.5f}}. 2D array consists 2 indexes. i++) { for(int j = 0. 1. i represents as row position and j represents as column position. 1. 74}}.println(“Total marks = ”+ tot). 2. tot = tot + marks[ i } //Display the total marks System.1f. 1.out. 61. 2. i++) { System.4f.2f. {60. {3.out.5f}. j++) { System. 2.1f.4f.1f.1f.3f. int marks [ ] = new int[3] [5].1f.5f}}.out.4f. 54}. 52. Student1 – 50. 53. } }  By default arrays are created in C.println(“The array elements are: ”). 63. //Calculate percentage float percent = (float) tot/n.2f.1f.5f}.4f. 3. char ch[ ] = new char[100] [100]. 72. 3. 1. 1. } System.3f. 2. 54 Student2 – 60. 62. Ex: // To display a 2D array in a matrix Class Arr1 { public static void main(String args[ ]) { float marks[ ] [ ] = {{ 1. {70. 62.2f.println(“Percentage = ”+ percent). 51. 3.printl(“In matrix form: ”). 52. 53. for(int i = 0. System. 73. 2. 1.2f. {2. {2. 2. 71. We can declare and initialize directly. //(float) is a cast operator System.3f. 61.3f. 71.COREJAVA System. 2.println().C++ on static memory. TwoDimensionalArray(2D Array):. Ex: int marks[ ] [ ] = {{ 50.2f.out. i<n. 3. 1. 3. 74 Creating2D array:1. JVM allot memory for the above array like below.3f. 63.out.println(x[ i ] [ j ] + “\t”).5f}.2D array represents several rows & columns of elements.2f. Ex: float marks[ ] [ ] = {{ 1. for(int i = 0. 3. {3.A class students are obtained marks in 5 subjects. Ex: . To integrate your newer. j++) { tot = tot + [ i ] + [ j ]. 14. Vector can always grow in size if we start adding more elements to it then its size will grow. of args = “ +n). Page 28 of 191 . Array is not synchronized. Vector is synchronized. It can store only object references. Whatare differencesbetweenArrayandVector:Array 1. of args. } } 13. An array is denoted as [ ] 2. args[1]. i++) { for(int j = 0. To pass an array to a method that is not overloaded to accept a collection. 2. j<4. int n = args. Array can store primitive data types like int. i<n.println([args[ i ]). Whydo youwantto converta collectioninto an Array:1. The size of the array needs to be declared in an advance. 4. 3. for this matrix to find total of matrix same as above and then add below program float tot = 0. //Displays args for(int i = 0. Also display the total of their elements. collection based code with legacy code that doesn’t understand collection. 2. We may give its size or you may not.out. System. i<3. Once declared array can’t grow in size. No need to declare the size of vector. Vector 1. float. Storing the primitive data types is not possible in case of Vector.) C:\>java prog 10 11 12 Command line 10 args[0] 10 Command line argument 11 args[1] 12 arg[s2] Command line arguments are stored in args[0]. To obtain faster processing time for certain operation. double …. 4. 3. 3. Add two matrices (or 2D arrays) and display their sum of matrix.length. args[2]. } ( Parameter is useful to receive values from outside to the main method.out. Command line arguments are the values passed to the main method at the time of running a program. Ex: //Program finds args length class Args { public static void main(String args[ ]) { //find no.println(“No. char.COREJAVA }  The outer most for loop represents row of matrix and inner most for loop represents column of matrix. Find the transpose of given matrix. for(int i = 0. i++) System. int n = s1. 3. 3.A string represents a group of characters. o = 109. s1. compareTo(s2).lang package. String class is created in java. Stringstr = newString(“Hello”). Comparing Strings. String x = s1. ‘e’. Stringstr = newString(arr). in dictionary order. Creating and initializing String. 3. i. We can create a string from a character array char arr[ ] = {‘H’. Where as String is a class name str is object name (referring the memory) 2. Note: . Ex: String s1 = “Boy”. 1. Stringclassprovidesthe followingfunctionalityfor handlingStrings:1. All will be displayed writing string like above. Here ASCII value of B = 66. y = 119 s1 = Boy = 66 109 119 s2 = Box = 66 109 118 0 0 1 HereOutputis 1 int n = s1. but a string doesn’t means character array. int length:.lang. Reading individual characters in a String. A string means character array in C-Language.In String class methods available as below. String s2 = “bad”. 4. A string represents an object of string class. 2.+ will also do the same String s1 = “Hydera”. Concatenating String. String: . Extracting sub strings 8. Stringclasscan not extendanotherclass . When s1< s2 it will gives negative s1> s2 it will gives positive s1= s2 it will gives 0 It compare with dictionary form. java. String str = new String(arr.It receives the integer number and returns the character at the specified. int compare To(String str): . 6.returns a negative value if the string comes before str.charAt(2) 4. We can create a string by directly storing a string into string class object. 2. x = 118.length(). ‘l’. of characters. Stringconcat(Stringstr): Concatenates22 the calling string with str. ‘o’}.contact(s2). 1. Stringstr = “Hello ”. Changing the case of characters in a string (toUpperCase/toLowerCase) 5. ‘+’ is called as concatenation operator. Here 1 represents the 1st character 3 represents No.returns the length of a string. or 0 if the strings are equal. Searching for characters and sub Strings 7. 22 Concatenation:. Page 29 of 191 .It means joining. String s2 = “Box”.COREJAVA String: . which strings comes first & next. A positive value if the string comes after str. CreatingStringclassobject:1.e. 3). We can create a string object using new operator. Conversion of objects to Strings. Stringclassis declaredas final class . char charAt(int index):. ‘l’. 24. 23. ------. Capital Alphabates A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ASCII Code 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 Small Alphabates a b c d e f g h i j k l m n o p q r s t u v w x y z ASCII Code 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 Numeric Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ASCII Code 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 5. Page 30 of 191 . It ignores the uppercase or lowercase.startsWith(“This”). 14. 4. 18.returns a negative value if the string comes before str.compareTo() method returns the int data type. ------.Above two methods use case sensitive comparison.return the first occurrence of str in the string. 25.returns true if the string starts with suffix. 9. 3. 16. S. 22.true str. 20. or 0 if the strings are equal. booleanstarts With(Stringprefix): . 7. 6. int index Of(Stringstr): . 8. 13. 17. 5.COREJAVA  Whatis the differencebetweencompareTo()methodandequals()method?***** Ans:.returns true if the string starts with prefix. int compareToIgnoreCase(Stringstr): .returns true if the string equals str. This case insensitive comparison.endsWith(“book”). in dictionary order. 6. It is a case sensitive comparison. where are equals() method returns the booleandata type. A positive value if the string comes after str.returns true if the string equals str. 10. str. booleanends With(Stringsuffix): . 19. 11. 12. 15. 21. Note: . 8. 2. No. 26. booleanequals( Stringstr): . boolean equals Ignore Case(String str): . 7. 9.true 10. 1. println(“Uppercase s1 = ”+ s1.substring(0. String replace(char oldChar.out. char arr[ ] = {‘I’.returns a new string consisting of all characters from beginIndex until endIndex (exclusive). StringtoLower Case(): .returns a new string that is obtained by replacing all characters oldChar in the string with newChar. ‘e’. ‘t’. ‘ ’. ‘v’}.A string that is created using the shorthand notation is known as a canonical string. toCharArray():. 19.out.Returns character array (char[ ]).println(“s3 = ”+ s3). The spaces found before the string are called leading spaces and the spaces are found after the string are called trailing space. It returns solv str. //Attach s1 and s2 System. ‘S’.toUpperCase).println(“s1 = ”+ s1).println(“s1 joined with s2 = ”+ s1.Both the above methodsreturn negativevalues.COREJAVA String str. //Find no.out. System.substring(0). ‘l’. = “This is book”.Converts all characters into uppercase.println(“s1 does not starts with This”). //Check if s1 starts with This or not boolean x = s1.4).returns the last occurrence of str in the string.Eliminates all leading and trailing spaces. ’o’.out.println(“Length of s1 = ”+ s1.println(p+q). 16. String substring(int begin Index): . String trim(): . String s3 = new String(arr). if str not found in the calling string. Note: . It returns INet 14.out. ‘N’. Count starts from 0. int endIndex): . Page 31 of 191 .out. 18.6). String s2 = new String(“I like it”). else System. You can use the String’s intern method to return a canonical string. //Join 3 strings using + (concatenation operator) System. which is the same string that is created using the shorthand notation. str. int lastIndex Of(Stringstr): .Converts all characters into lowercase. if(x==true) System. System.concat(s2)).out. char new Char): . String substring(int begin Index. 17.length()). Stringintern(): . 15. int n = str.out. Ex: //Understanding Strings class Str { public static void main(String args[ ]) { //Create 3 different strings String s1 = “This is java”. String q = s3. 11. 12. int n = str. //Convert the case of s1 System.returns a new string consisting of all characters from beginIndex until the end of the string.startsWith(“This”). StringtoUpperCase(): .substring(4).substring(0.println(s1+ “at ”+ s3). System.indexOf(“is”).out. //Extraxt sub string from s2 and s3 String p = s2.println(“s2 = ”+ s2).out. of chars in s1 System. Ex: String str = “INetSolv”. 13. //Displays the string System.println(“s1 starts with This”).lastIndexOf(“is”). String s2=new String("anand"). } } Output:.toLowerCase).println(“Hashcode of s2 = ”+“ ”+s2.COREJAVA System.println(“Both are not same”). if(s1==s2) System. if(s1==s2){ System.out.println(“Both are same”).println(1).out. System.out. else System. System.out. } if(s1. } } //Comparing the Strings class Compare { public static void main(String args[ ]) { String s1 = “Hello”. } } } Output:Hashcodeof s1 = 92955274 Hashcodeof s2 = 92955274 Ex: Page 32 of 191 . String s2 = new String(“Hello”).println(3).out.println(2).equals(s2)) System. } else{ System.out.out.out. if(s1.println(4).hashCode()).equals(s2)){ System. } } s1.println(“Hashcode of s1 = ”+“ ”+s1. String s2 = new String(“Hello”).hashCode()).out. Ex: public class TwoStrings { public static void main(String[] args) { String s1="anand". } else{ System.out. To compare contents of objects we have to use as below statement if(s1.println(“Both are same”). s2 are reference variables but it is not content of objects.equals(s2)) We can use the above statement in the place of if(s1==s2) in the above program Usingequals()://Comparing the Strings class Compare { public static void main(String args[ ]) { String s1 = “Hello”.println(“Uppercase s1 = ”+ s1.out.Both are same. else System.println(“Both are not same”). out.i>=0.out.println(s1). } return returnString.reverseString(s1)).length()<=1){ return s.out.println(s).--i){ returnString+=s.charAt(i). s3="babu".reverseString(s1)).println("Reversed String = "+r.out.charAt(0). s1=new String("babu"). System. s2=new String("babu"). System. String s3=new String("anand"). } } } class StringReverse{ public static void main(String args[]){ Reverse r=new Reverse(). return reverseString(s. } } class StringReverse { public static void main(String args[]){ Reverse r=new Reverse(). } else{ char c=s.COREJAVA 2 3 public class StringTest1 { public static void main(String[] args) { String s="anand". System. String s2=new String("anand").println("Reversed String = "+r. System.println(s2). s="babu". String s1="anand".out.length()-1. System.out.println(s3). String s1="anand".substring(1))+c. String s1="anand". } } babu babu babu babu //StringReverse class Reverse{ public String reverseString(String s){ if(s. for(int i=s. } } (or) //StringReverse class Reverse{ public String reverseString(String s){ String returnString=" ". System. Page 33 of 191 Ex: - Output:- Ex: - Ex: - . import java.equals(s2). s1==s2. i--.out.in)).readLine(). whose contents of objects can be modified. } } } Q) Whatis the (Hash)#code?***** Ans:.length(). Mutable objects. So we should use equals method for comparing two strings. BufferedReader br=new BufferedReader(new InputStreamReader(System.Here a is false and b is true. String s2 = “aaa”. String class objects are immutable.IOException. true (or) false b. Q) Whatis the differencebetween== and equals()methodin comparingtwo string?***** Ans:.InputStreamReader. for(int i=n-1. String s=br. true (or) false Ans:. String s2 = new String(“aaa”). s1.io. Q) Whatis the result for the followingprogram? String s1 = “aaa”. int n=s. i>=0.COREJAVA } } (or) import java. Page 34 of 191 . String s1 = “aaa”. j++){ System. Immutable objects.io. StringBuffer class objects are mutable.BufferedReader. Typeof Objects:1. Ex: //String class objects are immutable**** s1 Hello class Test { Hai public static void main(String args[ ]) s2 { String s1 = “Hello”.print(ch[i]). their hashcodes must be equal as well.out. ImmutableObjects:.println("Enter String value here = "). 2. Hai s1= s1+s2.a and b both are true. char ch[ ]=s. System. a.  If the two objects are equal. public class ReverseString1 { public static void main(String[ ] args) throws IOException{ System. } }  When ever you want string modified here JVM will create another object and store “Hello Hai” and assigns s1 to that s1 is disconnect with “Hello”. Hello String s2 = new String(“Hai”).println(s1). number allotted to an object by JVM is called (hash) #code.D. whose contents of objects can’t be modified. import java.out. Garbage collector comes & delete (“Hello”) unreferenced objects.toCharArray(). a.out. System. All the data manipulation methods are available in StringBuffer class only.The unique I.println(n). so it gives unreliable results.== compares the references. MutableObjects:.It is an object.It is an object. s1==s2.equals(s2). j=0.io. s1. true (or) false b. true (or) false Ans:. equals() method compares the contents of string class objects. StringBufferclassprovidesthe followingfunctionalityfor handlingStrings:1.  Both String and StringBuffer classes are defined in java. All the data manipulation methods are available in StringBuffer class only. x): . //Empty StringBuffer java. 3. 2. It will be inserted into the StringBuffer at offset (at the middle it will insert). 3. int length():.Reverses the character sequence in the StringBuffer. but objects can change without an explicit assignment in the statement.  StringBuffer class implements dynamic character String. 5. 4. 4. Q) Canyou extendthe Stringclass& StringBuffer class?***** Page 35 of 191 . it doesn’t compares values.  StringBuffer can change without creating a new object. StringBuffer objects are mutable. 6. StringBuffer append(x): .returns the length of the StringBuffer. It provides room for exact number of characters 5. i. deleting and reading characters in StringBuffer.lang. 4. String or StringBuffer.Removes the characters sequence in the StringBuffer. char. String class objects are immutable.x may be int. Changing.  StringBuffer class objects are mutable. double. Appending. All the data manipulation methods are available in this class.  StringBuffer equals() method is not overridden.lang. StringBuffer 1. 2. StringBuffer Methods:1. Controlling StringBuffer Capacity. CreatingStringBuffer: 1. 2. JVM will take less time to create new string class object so string objects are always immutable.Appending means adding at the end of StringBuffer. StringBuffer insert(int offset. 4. StringBuffer class doesn’t overrides equals() and hashCode() methods of object class. String class overrides equals() and hashcode() methods of object class.Converts string buffer into a String and return the string object. It will be appended to the calling StringBuffer.String class objects are immutable. 2. (or) String 1. 5. StringBuffer class objects are mutable. StringBuffer delete(intstart. Q) Whatis the differencebetweenString& StringBuffer?***** Ans:.e. It provides room for 16 more characters 5. StringBuffer sb = new StringBuffer(50). String class can be used as key in the HashMap or Hashtable. It will be inserted into the StringBuffer at offset (at the middle it will insert). There are no data manipulation methods in the class. StringBuffer class can not be used as key in the HashMap or Hashtable. float. StringtoString(): . StringBuffer reverse():. double. So StringBuffer class also cannot extend another class. StringBuffer sb = new StringBuffer(“Hello”). Thus they are available to all programs automatically. x may be int. String or StringBuffer. 3. Q) Whystringobjectsare immutable?***** Ans:JVM will takes more time to reallocate memory for the same object than creating new object. Constructing StringBuffers. StringBuffer class is also a final class. 3. inserting and deleting in StringBuffer. float. int end): . char. 2.COREJAVA  StringBuffer methods act on the nvoking object. JVM will takes more time to modify contents of objects in strings. Construction Strings from StringBuffer. reverse()). we can not extend both classes because both classes are predefined final classes.readLine(). In procedural approach the programmers concentration will be on the problem and its solution. It is a document consisting of Input/Output screens. So we need another approach to develop bigger and complex projects and still the programmer will loose his control. We will write function or procedures in these languages  C++. System. We need another approach where the entire system is studied and then only software is developed. String sur = br.out. Page 36 of 191 . Ex: //Full name of a person Import java. last to sb sb.println(“Enter last Name: ”). String last = br. Project Leader will prepare SRS. pseudo codes.*.println(“Enter Middle Name: ”). //Append sur. Java languages are called Object Oriented languages.append(sur). which means that neither of these classes may be subclassed. 1. System. Sort a given group of strings into alphabetical order? 14. FORTRON.out.in)). sb.append(last).insert(n. Q) Whatis SDS?***** Ans:SDS means Software Design Specification.readLine().out. Both String and StringBuffer implement the CharSequence interface.println(“In reverse = ”+ sb. System. such types of languages are called procedural languages. mid). //Insert mid after sur int n = sur. class Full { public static void main(String args[ ]) throws IOException { //To accept data from keyboard BufferedReader br=new BufferedReader(new InputStreamReader(System.COREJAVA Ans: .  Module is a part of developing software. //Create StringBuffer StringBuffer sb = new StringBuffer().length(). sb. 2. String mid = br. Q) Whatis SRS?***** Ans:Software requirement specification is a document that contains requirements of the client and strategies to fulfill these requirements.println(sb). Test whether a given string in palindrome or not? Palindrome is a string = reverse string. dataflow diagrams. System. } } StringsHomeWork:13. software and hardware requirements and databases etc… used to develop the products.out. Pascal.  Procedural languages can not handle bigger projects. COBOL.io.out. when program size exceeds 10000 lines of code and before reading 100000 lines of code the programmers suddenly loosing control on the code. In procedural approach.println(“Full Name = ”+ sb). //Display the Full Name System.readLine().out.No. System.println(“Enter Surname: ”). Ex: rnr = rnr  C. MutableObjects: . Q) Whatis OOPS?***** Ans:An Object Oriented Programming organizes a program around its data. Instance variables are loaded in the objects.Whose contents of objects can be modified. OOPS concept has been developed on human beings life. hashCode() and toString() methods are public.An object is any thing that exists in the world. Procedural approach doesn’t reflect human beings life. Because of the above reasons. Object: . An object is super class for all the classes.  The critical methods in class Object are equals().Instance means object.. but objects are dynamically created by JVM on the heap area of class loader subsystem. int nanoseconds)  equals(). Returns the hash code associated with the invoking object. Resumes execution of all threads waiting on the invoking object. ImmutableObjects:.  We can not override getClass(). Page 37 of 191 Purpose Creates a new object that is the same as the object being cloned. We another approach. notify(). 2.COREJAVA 3. objects and a set of well defined interfaces to that data.reflect  Field[ ] getFields()  Method[ ] getDeclaredMethods()  Constuctor[ ] getDeclaredConstructors()  Field[ ] getDeclaredFields()  Object newInstance() Q) Whatwill storein oblectsandwhatwill storein the stacks?***** Ans:.lang. Variables and methods are available in object. Waits on another thread of execution . The methods in the object class are as follows: Method object clone() boolean equals(Object object) void finalize() final Class getClass() int hashCode() String toString() final void notify() final void notifyAll() final void wait() final void wait(long milliseconds) final void wait(long milliseconds. where programming reflects human beings life. notifyAll() and wait() methods because they are declared as final. OOPS is a methodology that uses objects & classes in writing programs. but we can override remaining methods in the object class. Obtains the class of an object at run time. An object-oriented program can be characterized as data controlling access to code. finalize(). An object will have properties and actions.e. a new approach object oriented programming system (OOPS) has been developed. hashCode() and toString() methods. i. Called before an unused object is recycled. Returns a string that describes the object. Featuresof OOPS:1. Examplesof getClass(): String getName()  Class getSuperClass()  Class[ ] getInterfaces()  Method[ ] getMethods()  Constuctor[ ] getConstuctors() java. Resumes execution of a thread waiting on the invoking object. Objects are two types 1.  finalize() method is protected.Whose contents of objects can not be modified. Determines whether one object is equal to another.  Classes can also be modified with final. but there will be only one Heap space. (If there are 10 threads in JVM. Class will not exit physically. The reusability is the main advantage of Inheritance.  But a class can exist without objects.  Without a class we cannot create objects. The newly produced class will have all the qualities of the existing class plus it can have its own qualities. Java Page 38 of 191 . } } (or) Ex: class TestAcc { static int i. System. public static void main(String[ ] args) { System. If something exists in different form it is called Polymorphism. private.i).  There are four access levels: public. 5. still there will not be any problem. Encapsulation:.println(i). (The above 6 features) Q) Whatis the differencebetweenobjectorientedlanguages& objectbasedlanguages?***** Ans:. } public static void main(String[ ] args) { TestAcc a=new TestAcc().This word is comes out from the two words of Greek Words.me(). Polymorphism: . Q) Whyjava is objectorientedlanguage?***** Ans:. then there will be 10 different stack spaces. Abstraction:. Polymorphism means many forms.Showing necessary data and hiding unnecessary data from the user is called abstraction. If same method performs various tasks it is called as polymorphism. Ex: . Class is an example for encapsulation.out.  There are three class access modifiers: public.println(a. The main advantage of encapsulation is programmers can use same names in the two different classes.  Class also will have variables (data) and methods (code). void me() { System. protected. 6.e a final class cannot extends the other class. default.out. 2. The JVM is responsible for allocating some amount of memory space called as stack space for every thread.Object oriented languages follow all the features of OOPS.COREJAVA The Stack space will used to store parameters of the methods and local variables of a method.  A final class prevents inheritance i.Producing new classes from an existing class is called inheritance.Java obeys all the features of OOPS. 4. Messagepassing:. 3. Inheritance: . abstract or strictfp. } } Class:.A class is a model to creating an object.Calling a method is called as message passing.println(i).out.  A class cannot be both final and abstract.Bundling up of data & methods as a single unit is called Encapsulation. a.C++. private. Ex: class TestAcc { int i. Poly means many and morphism means forms. protected.  The unique code or ID of every objects which is allotted by JVM.println(“My age is” +age).  HCGA– Hash code generation Algorithm memory address → HCGA → hash code  Hash code is produced or generated from memory address. No.  Method codes are stored in method area. name = “Subba Rao”.0 A space Null Null (Anyclassnull meansemptyobjects) Initializingthe instancevariables:1.  The variables which are stored in objects are called instance variables.Smalltalk. { Person p1 = new Person().COREJAVA Object based programming languages contain all the features of oops except inheritance.hashcode()).out.0 0. Page 39 of 191 . Simula67 etc…  Object is an instance of a class. Ex: . } class Demo { public static void main(String args[ ]).  When the instance variables are not initialized java compiler uses some default values to initialize them. p1. 4. } }  new operator (new person()) will create the object.  A class is called user defined datatype. 1.out. It gives initial values on the data type. S. System. Ex: //A class and object class Person { //Properties – vars String name.println(“Hello I am ” +name). Hash code & memory address are not same. objects are created JVM on dynamic memory.println(p1. 5. int age. 6. 3. Datatype Int Float Double Char String Any class DefaultValue 0 0. //Actions – methods void talk() { System.age = 22. Hash code is the reference of the object. System. p1.talk(). another class { p1. 2.out. We can initialize the instance variables of a class in another class.  Super class default constructor is also available to sub class.  Parameters. AccessSpecifier: .  A constructor will not return any value. This offers full security. method or variable accessible from any other class.A protected members are available outside the class. Interface is not part of an object’s inheritance tree. Private: . not even void. Default members are available outside the class.  Super class parameterized constructor is not available to sub class. To give security for instance variables we give there instance is private.  Abstract classes can have constructors that are called when concrete sub class is instantiated.An access specifier is a keyword that represents. A constant is a variable which will have a fixed value. return st.  Only static variables and methods can be accessed of the call to super() or this().  The main purpose of constructor is to set the initial state of an object when the object is creating using “new” operator. 4.  this() and super() methods cannot be in the same constructor. SingleTonClassCode: class SingleTon { private static SingleTon st=null. There are two types of constructors. } public static SingleTon stfactory() { if(st==null) st=new SingleTon().  Constructor can use any access modifier even private also.14159 3. We can have one or the other. Protected:.A public members of a class are accessible any where outside the class or makes a class.A private member of a class is not available any where outside the class or makes a method or a variable accessible only from within its own class. This private is also call as access specifier.  Constructors cannot be overridden. If a constructor is declared Constructor as private in a class then it will creates only one object to its class. Ex: . Page 40 of 191 .  Constructors can be overloaded.println(“\nIn constructor”). There are four types of access specifiers. It is like as public members or makes a method or a variable accessible only to classes in the same package or subclasses of the class.  Interfaces do not have constructors. but never both.final Double pi = 3. Public: . Constructor: . private SingleTon() { System.  This way of initialization is suitable for constant.  A constructor will have same name of that of its class. writing two or more constructors with same name but with difference in the parameters is called as constructor overloading. To initialize the instance variable we can use the constructor.COREJAVA } } There is no security of data will be across by other class. 2. 3.  This way of initialization will store same data in all the objects.  When you create an object to sub class the super class constructor is also available to sub class.If no specifier is used java compiler uses a default specifier. which passes the variables from objects to the constructor. 1.A constructor is similar to a method. We can initialize the instance variables by directly storing values at the time of their declaration.out.  The default return value of constructor is class. which is used to initialize the variables or objects.  A constructor can be directly invoked by another constructor (using a call to super() or this()). that type of classes are called as Singleton classes. because constructors are not inherited into classes. Default Specifier: . 1. The instance variables may not available if they are declared as private. 2. how to access (read) the members of a class. age = 30. Method can be inherited. it represents group of statements to perform tasks. . Ex: //default constructor person() { name = “Vishnu”. private OnlyOne(){… } //Private constructor. and so on all the way up to the Object constructor. Constructors cannot specify exception in the header. begin with lower case. int a) { name = s. 5. static and final etc. and so on back down to the completion of the constructor of the actual instance being created. Page 41 of 191 Method 1. public static OnlyOne getInstance() { return one. 4. This class cannot be instantiated from outside. which calls its superclass constructor. 5. 6. OnlyOne myOne = OnlyOne.getInstance(). Constructor doesn’t return any type. We can over load but we cannot overridden. 8. Method has called explicitly.It is a constructor without parameters. “This” refers to another constructor in the present/same class. Modifiers other than the accessibility are not permitted (Ex: . 3. “This” refers to instance of class. Note: .abstract. DifferencebetweenConstructorand Method: Constructor 1.  The object constructor executes and then returns to the calling constructor.). ParameterizedConstructor:. 7. (or) this.name = name. 7. 2. Method can return void or valid return type. Restrictions:1. Constructor will automatically invoke when an instance of class is created. Execute an overridden method in the super class.This will have one or more parameters. Typesof Constructors:1. which runs to completion and then returns to its calling constructor. 4. Default constructor:. 2. not even void also. 6. We can over load and overridden. A method is a function.A constructor is called and executed only once at the time of creating an object to the class. Constructorexecutionoccursas follows: The constructor calls its superclass constructor. Constructor is a special kind of method used to instance of a class. 8. } } To use it: //No matter how many times you call. 2. 2. } //action-methods //parameterized constructor person(String s. you get the same instance of the object.. Constructor will have the same name of that its class.COREJAVA } } (or) public class OnlyOne { private static OnlyOne one = new OnlyOne(). Constructor prevents the inheritance. As a name except the class method name. 3. “Super” refers to invoke the super class constructor. Parameterized constructor is used to initialize each object with different data. } //action-methods public void talk(). ( i it is a local variable) } } class Demo { public static void main(String args[ ]) { //Create an object to Sample class Sample s = new Sample(). Note1:. i.println(“Hello I am” +name). } Sample(int i) { this.Default constructor is used to initialize every object with same data.  Q) Whatis the functionaldifferencebetweendefault constructorandparameterizedconstructor?* Ans:. Parameterized constructor is used to initialize each object with different data. when the programmer did not provide any type of constructor in a class. constructors. Java compiler creates a default constructor.out. Super Class parametrized constructor is not available to its subclass. //Constructors class Sample { int i Sample() { this().  “this” is a keyword. 4.age = age. 2. 3.Writing two or more constructors with the same name but with difference in the parameters is called as constructor overloading. Default constructor is used to initialize every object with same data. ParametrizedConstructor 1.display(). //Here default constructor is called & executed. (or) this. Java compiler did not provide the paramerized constructor to the class.e. The programmer has to provide the parametrized constructor in a class. 2. System. A Constructor with one or more parameters is called parametrized constructor. (or) Default Constructor 1.i = i. methods.println(“i = ”+i). methods and constructors. Note2: .COREJAVA age = a. Super Class default constructor is available to its subclass. then the java compiler provides default constructor. 3.//this refers to present class variables. Ex1: . //refers to instance variable } void this. 4.Java compiler creates a default constructor or with default values when no constructor is provided by the programmer.display(). A constructor without any parameters is called as default constructor. “this” can refer present class instance variables. present class constructors and present class methods. //calls para constructror) ( this() left & right simple braces will call present class default constructor) this. Where String s & int a are local variables to receive data from outside.out.   Page 42 of 191 . s.display(int i) ( (int i) local variable) { System. that refers to present class object.  “this” represents present class object that means it refers the instance variables. ( i it is a instance variable) } } class Demo { public static void main(String args[ ]) { //Create an object to Sample class Sample s = new Sample(200). } Sample() { this. t.show(). ( x is instance variable) Two t. s.out.out. } }  To get instance variable use this.println(“x = ”+x).display(). //Here parameter constructor is called & executed. Ex2: .i  This always refers to present class object.//Where class One { int x. t = new Two(). } void show() { x 10 System.display(int i) ( (int i) local variable) { System.println(“i = ”+i).out.println(“This is Two”). //calls para constructror) this. o   Hash Code } } class Two { void show()/Two()/show() { System.display(). //refers to instance variable } void this.i = i.COREJAVA } } (or) //Constructors class Sample { int i Sample() { this(). ( Two is class and t is instance variable) One() { x = 10. } } class Demo { t Class One object class Two object Object graph Page 43 of 191 . return x. d2. Ex: //Understanding methods class Sample { double d1. Methods:. } Note: . In between these curlew braces we have to write statements. It starts with begin “{” and ends with “}”.y.out.A method consists of a set of statements to perform a task.d2 = d2. Ex: void sum(double d1. sample(double d1.This part contains method name. { One o = new One(). 15. Methodbody: . parameters and method return type. double d2) double sqrt(double x) long fact(int n) double power(double x. int n) 2. Q) Whatis objectgraph?***** Ans:. return obj. returntype methodname(parameter1. double d2) //parameterized constructor //double d1. return x+y. } } class Demo1 { public static void main(String args[ ]) { Sample s = new Sample(10. Method can return only variable/objects/value. } }  this() can call present class parameterized constructor. Ex: { statements.  We can establish a relationship between objects by using three methods they are reference variables/inner classes/inheritance. } void sum() { System. Page 44 of 191 . parameter2.d1 = d1. A method will have two parts. this.5). Ex: return 1. Method header (or) Method Prototype: . ……) method parameters are local variables to receive the data from outside for the method. o. { this.COREJAVA public static void main(String args[ ]).  It is not possible.println(“Sum = ”+(d1+d2)).The graph showing the relationship between different objects is called Object graph.  this() can refer present class method. return x. double d2 are local variables.It contains statements representing the logic to solve the problem.show(). 1.A method can return some value only if return statement is used in the method body.  this() can call present class instance variable. double x = Sample.out. double d2) //parameterized constructor //double d1. } Sample s = new Sample(). 15. double x = s.  Q) Whatis differencebetweenstatic variableand instancevariable?***** Ans:A static variable is a variable whose single copy in memory is shared by all the objects of class. 2. double d2) { return d1+d2.println(“Result = ”+x). To call instance methods we have to use objname. A static method is called using objectname. System. 7. A static method should be declared as static. 5.d1 = d1.sum(10. A static method is a method that can be called and executed without creating an object. Static variable is also known/called as “Class Variable”.out. System. Ex: static double(double d1. 8.COREJAVA s. A static method is called class. //Understanding methods class Sample { double d1.5).methodname(). 15. A static method is also called directly using classname. d1.sum().A static method is a method that does not act upon instance variables of a class.sum(). But it can be redefined in a subclass. sample(double d1. d2.5). 3.methodname().5). } static void sum(double d1. Any modification of one object will affect other objects. { this. // d1.methodname(). Static methods are overloaded. 1.methodname(). 6. Static methods are declared with static keyword. this. A static method is a method it cannot act on instance variables. double d2) { return d1+d2. Static method: .println(“Result = ”+x). Static method cannot access instance variable but they can access static variables. d2 are instance variables. 15. } }  Java compiler will construct default constructor when there is not any constructor.It is a method that acts upon instance variables. double d2 are local variables. d2 are local variable } } class Demo1 { public static void main(String args[ ]) { Sample s = new Sample(10. Static methods are loaded on the Method area of the Class loader sub system in the JVM architecture. Instancemethod:. Static methods can’t be overridden. double x = s. Page 45 of 191 .sum(10.d2 = d2. double d2 are local variables. 4. }   (or) } double d1. Static blocks and static methods are stored on method area of JVM. An instance variable will have a separate copy available in each object.  Static blocks are executed before any method is executed. 3. so ultimately instance variables are loaded on the heap area of class loader sub system. Only instance variables and methods can be accessed after super constructor runs. Instance means objects. Instance variables are executed at runtime. Factory methods. System. 3. If any modification of one object will affect other objects. 2. 5.COREJAVA An instance variable will have a separate copy available in each object. } Page 46 of 191 . Typesof methodsin Java:1.  Static variables.  A static method does not act on instance variables. Objects are in the memory of heap. 3. 2.println(“Inside main”). Any modification of one object will not affect other objects. So instance variable are stored in heap. 4. } } Staticblocks:.out. Instance methods a) Accessor method b) Mutator methods. 2. 4.out. } public static void main(String args[ ]) { System. (or) StaticVariable 1.exit(0).println(“This is inside static”). Instance variables are loaded in the objects. If any modification of one object will not affect other objects. Ex: //A Static block class Sample { static{ System.Static blocks are group of statements written inside a block declared as static.  Static blocks are stored on the method area of Class loader sub system. InstanceVariable 1.println(“This is inside static block”). 5.  Static variable must be declared with static keyword. Static methods. A static variable is a variable whose single copy in memory is shared by all the objects of class. Objects are dynamically created by JVM on the heap area of class loader sub system in the JVM architecture.out. Only static variables and methods can be accessed of the call to super() or this().  It means static blocks are executed at the time of compilation only.  Instance variable can be decalred any where in the class and no need of initializing it. Static variables are loaded on the method area of class loader sub system in the JVM architecture.  block is a group of statements with () Ex: .  Instance variables are created in objects.//A Static block class Sample { static{ System. It will takes default values. Static variables are executed at compilation time. COREJAVA }  In general without main method we can not run the java program.out. this. char sex). this.age = age.display().name = name. { name = n. age = a. System.println(“Sex = ”+sex).  Only instance variables and methods can acess after super constructor runs. int age. } } class Demo { public static void main(String args[ ]) { Person p1 = new Person(“Srinivas”.Constructor will be executed finally  When instance variable & local variable names are same then only we have to use “this”. An object contains instance variables.  Instance methods can be overloaded or overridden. Instance variables are created in object in the heap memory. Ex: //Accessor and mutator methods class Person { String name.methodname. ‘M’). { this. Ex: //Accessor and mutator methods class Person { String name. Instance method: . Instance methods these are methods. char sex). Person(String name. int age.  An instance method is called using objectname. } } In a class: Static blocks These are executed initially Static variables Instance Variables Then these are executed secondly Instance method Constructor ---.out. which act upon instance variables of a class. int age.println(“Age = ”+age). p1. Person(String name.These methods not only read the instance variables but also modify them.  Class variables means static variables. Page 47 of 191 . 20. void display ()//this is an accessor method { System.println(“Name = ”+name).  A class is also called user defined data type. b) Mutator method: . int age. sex = s. 2.These methods access or read instance variables.out. Mutator methods modify the contents of the objects.sex = sex. This means instance methods acts upon class objects. char sex. System. a) Accessormethod:.  An instance method can access instance variables.Instance means objects. char sex.  methods also receives arrays as parameters and returns array as result. class Arr Page 48 of 191 .println(“Name = ”+n). System. int. obj.  JVM/JVM compiler is developed in C-Language. float and double) and the keyword void are also represented as class objects.  Any thing passed to method by value. 30. p1. ( obj is Person class object) }  } class Demo { public static void main(String args[ ]) { Person p1 = new Person(“Srinivas”. ‘M’)).out.modify(new Person(“Vankat”. } Person modify (Person obj) //Mutator method { obj.  Objects are passed to the methods byvalue. System. p2. char.  There is no concept pass byvalue & pass byreference.name = “Laxmi”.sex = ‘F’. Person p2 = p1.modify(p1). p1.*.println(“Age = ”+a).COREJAVA void display ()//this is an accessor method { System. short. Ex: /*Finding sum of given two matrices using methods to accept and return arrays*/ import java.println(“Sex = ”+s).  Pass by reference means passed the address of variable to methods.display(). 20.  The primitive java types (boolean.out. --obj. ‘M’).display().age. (Now it will displays Laxmi’s details) } } reference variable p1 Copy of another obj reference We are storing as Object Srinivas 20 M Lakxmi 19 F reference variable p1 Object Srinivas 20 M Object Venkat 30 M Laxmi obj p2 p2 30 M  Referenced variables are passed to methods by value.out.display().io. byte. return obj. long. but pointers are not used by the programmers.  Pointers are used internally by JVM. (or) Person p2 = p1. then pointers receives the address of variable then we can do modification. j++) { System. j<c.println().getArray(). Arr obj1 = new Arr(3. i++) for(int j = 0. c. i<r.println(“Enter elements of second array: ”). int c) { this. } //To accept elements of an array and return int [ ] [ ]getArray() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System. arr = new int[r][c]. i<r. arr[ i ][ j ] = Integer. } } //method to display the array after receiving it void putArray(int res[ ] [ ]) { for(int i = 0. System.putArray(y). } System. System.putArray(x). obj1.out. Arr obj2 = new Arr(3.3). j<c.r = r. } } //To accept two arrays and find sum array and return it { int[ ][ ] findSum(int a[ ][ ].parseInt(br. j++) { System. return temp.out.print(res[ i ][ j ] + “\t”).readLine()).getArray(). Page 49 of 191 .out. obj2. y = obj2. for(int i = 0. for(int i = 0. } } class ArraySum { public static void main(String args[ ]) throws IOException { //Vars int x[ ][ ]. i++) for(int j = 0. i<r.out.COREJAVA { int arr[ ][ ]. this. Arr(int r. y[ ][ ].3).out.c = c. int r. j<c.println(“Enter elements of first array: ”).print(“Enter element: ”).in)). int b[ ]) { int temp[ ] [ ] = new int [ r ][ c ]. j++) temp[ i ][ j ] = a[ i ][ j ] + b[ i ][ j ]. z[ ][ ]. i++) { for(int j = 0. x = obj1. //A non-static method. which creates an instance of a class (i.forName(“Employee”). Ex: class MyClass { public static void main(String args[]){ Car c = newCar().getPercentInstance() are factory methods. creates an object). //myClassName should be read from a properties file or Constants interface.getNumberInstance(). Let us look at how to load classes dynamically. Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. NumberFormat obj1= NumberFormat.com. 4) Using Cloning: . All factory methods are static methods. String myClassName = "au.getCurrencyInstance(). class.y). static loading) but the runtime system cannot find the referenced class.getPercentInstance(). The above static method returns the class object associated with the class name.e. 3) Using newInstance() method: Ex: .Employee obj = new Employee(). Page 50 of 191 . //static method which returns a Class.e.clone(). Obj1. Usingnewoperator:1. the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions.In 4 ways we can create an object: 1) Using new operator: Ex: .findSum(x.getNumberInstance(). In some classes we cannot use new operator to create an object. NumberFormat obj1= NumberFormat. Ex: . getNumberInstance(). Whatis the differencebetweenusingnewoperatorandclass. It’s just like creating a class object with no arguments. } } Factory methods: .forName(myClassName).newInstance(). Ex: NumberFormat obj = NumberFormat.COREJAVA z = obj1.setFuelCapacity(50).Employee e2 = e1. System. } } 2.Jeep". Objectsare constructed:  We cannot create a new object without invoking a constructor.out. The string className can be supplied dynamically at run time.newInstance (). In that situation this factory methods are used.Cloning means creating another copy same as like original copy. Class vehicleClass = Class.Class c = Class. Employee obj = c.forName()to createan object. Unlike the static loading.forName():1.  Each superclass in an object’s inheritance tree will have a constructor called. UsingClass.A factory method is a method that returns object of the class to which it belongs. myJeep.getCurrencyInstance(). 2) Using factory method Ex: .NumberFormat obj = NumberFormat.println(“The sum array: ”). Once the class is dynamically loaded the following method returns an instance of the loaded class. A NoClassDefFoundException is thrown if a class is referenced with Java’s “ new” operator (i. //stay away from hard coding values in your program. Classes are statically loaded with Java’s “new” operator. Q) In howmanyyoucan createan objectusingnewoperator?***** Ans:. myJeep = (Jeep) vehicleClass.newInstance ().forName (String className). Jeep myJeep = null.putArray[z]. Class. In general we should avoid using inner classes. Page 51 of 191 .setMaximumIntegerDigit(2). Comparators etc which are used in the context of an outer class. double r = 15. System.println(“Area = ”+area). This leaves a security hole.COREJAVA 2. // final double PI = (double)22/7..getNumberInstance().) method in class . So in such a case we must have a default consturctor for a class.ClassLoader. } } (or) //Area of a circle import java.  The findSystemClass(.Class.*. Whereshouldwe use inner classes: Code without inner classes is more maintainable and readable. } } 15.  The loadClass(.      You can use public access specifier before a class. String s = obj.5.*.ClassLoader. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it.14159. System. Otherwise we get an error.14159. String. the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. obj.text.println(“Formatted area = ” +s). // final double PI = (double)22/7. class Circle { public static void main(String args[ ]) { final double PI = 3. A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:  The forName(. Inner classes are used primarily to implement helper classes like Iterators. class Circle { public static void main(String args[ ]) { final double PI = 3.format(area). Ex: //Area of a circle import java. When you access private data members of the outer class.out.setMinimumIntegerDigit(6). double area = PI * r * r . Create a class with student details and create 2 objects to it and display the details using methods? Inner Class:.out..5. obj.  When we call a newInstance() method.. //Format the are value NumberFormat obj = NumberFormat. it always calls for the default constructor. You cannot use private access specifier before a class.) method in class . Only inner classes can be declared as the private. double r = 15. We can create objects to the outer classes.println(“Area = ”+area).) method in class .text.A class within another class is called inner class.out. double area = PI * r * r . Directly you cannot create objects to the inner class. COREJAVA  Inner class objects can be created only its outer class. bal += interest. Obj. } private class Interset { private double rate. System. // bal = bal + interest.5 } } (or) //Inner class class BankAcct { private double bal. } } } class InnerDemo { public static void main(String args[ ]) { BankAcct obj = new BankAcct(10000). in . in . //Rate of interest = 4.  Outer class is acting as a firewall. Interest(double r) Page 52 of 191 Another Class . } void start(double r) { //Create an object to inner class Interest in = new Interest(r). calculateInterest().start(4. BankAcct(double b) { bal = b.out. Interest(double r) { rate = r. Ex: //Inner class class BankAcct Outer Class { Inner class private double bal.5). calculateInterest(). } valid calculateInterset() { double interest = bal * rate/100.println(“Interest = ”+interest). } private class Interset { private double rate.out.println(“Balance = ” +bal). } void start(double r) { One Person class //Create an object to inner class Interest in = new Interest(r). BankAcct(double b) { bal = b. System. 3.Anonymous classes combine the process of definition and instantiation into a single step. 9.bal/100.println(“Interest = ”+interest). // bal = bal + interest.5). Anonymous classes can be defined and instantiated in contexts. 5.bal). Anonymous classes are typically used for creating objects on the fly contexts such as return value of a method. Inner class is a safety mechanism. } valid calculateInterset() { double interest = BankAcct.5 } } Summaryof Inner Class:1. These are defined at a location where they are instantiated. Inner class features are accessible through outer class only. Method.bal*this.this.e. Outer class members are available to inner class. Anonymous class cannot have constructors. 10. Inner class & outer class are separated by ‘$’ symbol. 4. Instance initializer can be used to achieve the same effect as a constructor. } } } class InnerDemo { public static void main(String args[ ]) { BankAcct obj = new BankAcct(10000).this. System. in initialization of variables. 8. An inner class is a class within another class 2.this.out. } class Shape implements IDrawable{ void draw(){ } Page 53 of 191 Interest bal this&0 . as an argument in a method call.member. Inner class object contains an invisible field “this$0” that stores outer class reference. 7. Typesof Inner Classes: 1. as expression that executes to a reference denoting an object. Only inner classes can be declared as ‘private’. obj. Non-Static Inner Classes 4. An object to inner class cannot be created in other classes. 11. Annonymous Classes 2.local Inner Classes Anonymousclass: . BankAcct. Ex: interface IDrawable{ void draw().println(“Balance = ” + BankAcct. //Rate of interest = 4. 12. System.COREJAVA { rate = r.out. where a reference can be used i.this. Outer class members can be referred as: outerclass. 6.start(4.bal += interest. An object to inner class can be created only in bal outer class. Inner class is hidden from other classes in its outer BankAcct class. Outer class object and inner class objects are created separately in memory. Static Inner Classes 3. //We writing semicolon here at the end of annonymous class void m1() { obj. Declaration and instantiation combined in the same process. { //Anonymous class starts here without name void show() { System.out. It can implement a single interface. } } } } To define and instantiate an anonymous class that extends an existing class can be specified by new SuperClassName(optional arguments){class declaration} A reference to an anonymous class cannot be declared the functionality of the class is only available through super class reference implementing an interface. 1: //Exampleof AnonymousClass class Hai { void show() { System. Cannot declare a reference and constructor. The anonymous class implicitly extends the object class. } }. } } class Hello { Hai obj = new Hai() //Don’t put semicolon in above because here we are creating anonymous class. protected void finalize() throws Throwable{ } Ex. It is not a method of Hai class } } //end of Hello class class Test { public static void main(String args[ ]) { Page 54 of 191 .println(“ ”). } void disp() { System.println(“I am display”).out.out. 4.No implementation clause is used in the constructor.println(“I am show”). We cannot use either extends or implement keywords with anonymous classes. No arguments are passed.out. Anonymous class provides a single interface implementation and no arguments are passed.COREJAVA } class Pointer{ public Shape createShape(){ return new shape(){ public void draw(){ System.disp(). 2. Note: . 5. 3. Anonymousclass 1.show().println(“I am show”). //obj. println("I am in Disp"). Obj2. void disp().m1(). //end of Annonymous class void m1() { obj. obj1.println(“I am new show”).show(). } } class Test { public static void main(String args[ ]) { Hello obj2 = new Hello().COREJAVA Hai obj1=new Hai().println(“I am disp”).out.out. } } Ex 3: class MethodInner { void disp(){ System.show(). m.println("I am in Show").out.disp(). h. } }. obj.disp(). class Hai{ void show(){ System. } } class MethodLocalInner{ public static void main(String a[]){ MethodInner m=new MethodInner().m1(). obj2. //To access annonymous class overriding show in m1() method } } Ex. Hello obj2-new Hello().out. 2: //Exampleof AnnonymousClass interface Hai { void show(). } } Hai h=new Hai(). } class Hello { Hai obj = new Hai() { public void show() { System. } public void disp() { System. } } Page 55 of 191 .show(). address= address. yy). String bal. } void setAddress(String address) { this. } int getAddress() { return address. float sal. Project Lead } PL int getName() { return name.id = id. void setId(int id) //mutator() method { this. } void setSal(float sal) { this. Display the different number of days in their dates of birth? Ex: //Teacher class class Teacher { int id. } int getId() //accessor() method { return id. Now create two objects and store two student’s details.id = id.sal= sal. name. } int getId() Programmer 1 P1 Programmer 2 P2 Project Database Page 56 of 191 .COREJAVA Inner classExercise: 16. rno. } float getSal() { return sal. int marks. String bal. Create a student class with student details like. } Ex: } //Student class class Student { int id.name = name. String address. } void setName(String name) { this. String address. void setId(int id) { this. mm. In this class create an inner class DOB that contains date of birth of student (dd. getMarks()). //Store data into s s. s.setId(10). } int getAddress() { return address.marks = marks. } int getName() { return name. } void setName(String name) { this.out.setMarks(77).setAddress(“MIG-44. void setMarks(int marks) { this. System. Hyderabad).out.getAddress()). S1 s.out. } } //use Student class class Use { public static void main(String args[ ]) { //Create an object to student class Student s = new Stuent().println(“Address = ”+s. //retrieve data from s and display System.println(“Id = ”+s.COREJAVA { return id. s.println(“Name = ”+s.name = name.println(“Marks = ”+s. } void setAddress(String address) { this.out.setName(“Vijay”). } int getMarks() { return marks.marks = marks. System. KPHB Colony.getId()). } int getMarks() Page 57 of 191 ID Name Address Marks . } } //Student class extends Teacher class] class Student extends Teacher { int marks. System. } void setMarks(int marks) { this.address= address.getName()). println(“Super class method = ” +i).Producing new classes from an existing class is called as inheritance.  Super class default constructor is also available to sub class.out. int y) { Page 58 of 191 . Because in Sub class it contains all the methods & objects of class are available to sub class.i = i.out.COREJAVA { return marks.  Extends is the keyword use in inheritance.  In inheritance. } }  When you create an object to sub class to super class constructor is also available to sub class. Two(int x.  Sub class contains a copy of super class object. One(int i) { this. we create object to only sub class. Syntax:class Subclass extends Super class  Reusability is the main advantage of inheritance. The original class is called Super class.  The newly produced class is called sub class.  Super class parameterized constructor is not available to sub class. } } class Two extends One { int i.println(“Two”). } } class Two { Two() { System.out.  Because of reusability developing of software/program becomes easy. } void show() { System. Case2: //If Super class has parameterized constructor class One { int i.println(“One”). } } class Const { public static void main(String args[ ]) { Two t = new Two(). } Inheritance:. Case1: //If Super class has a default constructor class One { One() { System. add(10.20. int c) { int d = a+b+c. t.  We have to initialize first super class constructor.println(“Sum of two = ” +(a+b)). Method consists two parts 1.out. i = y. Static Polymorphism 2.out. it is called Polymorphism. Polymorphism:.200). } }  Super keyword refers to super class from sub class. If the same method performs many tasks it is called Polymorphism. Dynamic Polymorphism DynamicPolymorphism:.println(“Sub class method = ” +i). Method header – It doesn’t change 2. It shows super class method. super(x). methods also. super. int b) { System. //super() means calling super class default constructor } void show() { System. System.This is the Polymorphism exhibited at runtime. Ex: //Method Overloading class Sample { void add(int a. s.20). Method body – But body will change/different In Dynamic Polymorphism a method called is linked with method code at runtime.Polymorphism came from two Greek words.println(super.show().  super. If something exists in many forms.println(“Sum of three = ” +d).add(10. } } Ex: class Shape{ Page 59 of 191 . Class Poly { public static void main(String args[ ]) { Sample s = new Sample(). So it is also called late binding. System. This is also known as runtime polymorphism (or) late binding. Dynamic means runtime.  Using super key word we can refers to super class instance variables constructors.30).i). int b. s. } void add(int a. 1.COREJAVA super(x).show().show() in sub class. } } class Const { public static void main(String args[ ]) { Two t = new Two(100.out. There are two types of Polymorphisms.out. Poly means many and morphs means forms. It is invalid Box b1=(Box)new Shape().i).p).println("It is shape").java:31) Ex: class Shape{ int i. It is invalid /*From above we can say that Superclass cannot access the members of subclass.COREJAVA int i.out. b.i). } } class Box extends Shape{ int p. Shape s1=new Box(). s.out.out.println(s. //s1.println(b1.out.vara.println("It is box").println(s1.println("It is shape").m1().out. b1. It is invalid //System. b. /*From above we can say that Subclass can refer the Superclass reference and Subclass canaccessall the membersof Superclass. but Superclasscan accessonly overriddenmethods*/ Box b=new Box().m2(). } } Output:0 It is shape 0 0 It is shape It is box 0 It is shape Exception in thread "main" java.Shape at com.out. s1. void m2(){ System.marlabs.println(b1.m2().println(s1. //s. It is invalid //System.println(b.m1(). } } class Box extends Shape{ int p. void m1(){ System. } } public class TestSuper { public static void main(String[] args) { Shape s=new Shape(). System.p).i).main(TestSuper.m2(). System. b1.out. System.m1().println(s.marlabs.p). System. Page 60 of 191 .out.println(b. //If we run the wholecodenowruntimeexceptionoccurs System.TestSuper.p).ClassCastException: com.vara.lang.out.m1(). System.i).out.m2().out. void m1(){ System. It is invalid Box b1=(Box)s1. It is invalid //System.out. System.m1().m2().i). It is invalid //System.println(s. int b) Any one of the above differences will make method signature to be different.m2(). Shape s1=new Box(). b. then JVM can recognized that method differently.out. double b) 3. b1. It is invalid Box b=new Box(). System.out.p).A method signature represents method name and its parameter.println(b1. int b. There is a difference in the sequence of parameters (or) order of parameters Ex: int swap(char a.println(s.out.out.i).i). This part is called method signature. JVM identifies a method separately when any one of the following differences is found.p). There is a difference in the data types of parameters (or) number of parameters Ex: void add(float a. s.println(b. 1. } } Output:0 It is shape 0 0 It is shape It is box 0 It is shape 0 0 It is shape It is box Method Signature: .out. //s1.out.out. System.m1(). int b) void add(double a.println(b. Page 61 of 191 .m1().COREJAVA void m2(){ System.m2().println(s1.m2(). int c) 2. It is useful to uniquely identify method from signature. b.println("It is box"). Ex: void add(int a.println(b1. char b) 4. b1. //s. System. } } public class TestSuper { public static void main(String[] args) { Shape s=new Shape().println(s1. s1.i). System.m1().p). There must be difference in return type Ex: int add(int a.p). System. There may be different number of parameters in the both methods. int b) int add(int a. int b) void add(int a. int b) int add(int a.out. calculate(16).println(“Result = ”+res). } } class Poly { public static void main(String args[ ]) { Two t = new Two().sqrt(x).4 Ex: //Method Overriding class One { double calculate(double x) { return x * x. If you write same methods and same parameters in one class it is called as duplicate method. double calculate  Methods can be overridden and overloaded. (double x)  Methods from a superclass can be overloaded in a subclass.out.  May have different return types.  Reference type determines which overloaded double calculate method will be used at compile time. System. There must be some difference in the method in one class. Method overloading is an example for Dynamic Polymorphism.  May have different access modifiers. t  Polymorphism is not applied to overloading. } } O/P: .  Overlaoded methods can change return type. but with different arguments.  May throw different exceptions. } } class Two extends One { double calculate(double x) { Page 62 of 191 . double res = t. (double x)  Constructors are overloaded but not overridden.  Methods can be overloaded in the same class or in a subclass. but compiler doesn’t execute this type of method.  Overloading means reusing the same method name.Writing two or more methods with the same name but with different method signatures is called method over loading. } } class Two extends One { double calculate(double x) { return Math. Ex: //Example for Overriding class One { double calculate(double x) { return x * x.COREJAVA Overloading method: . Overloadedmethods:  Must have different argument lists. as long as the argument lists are also different. marlabs.println("---Result---"+res3). System.calculate(4). System. double res=t.0 ---Result---2.println("---Result---"+res).out.256 Ex: class Test{ double calculate(double x){ return x*x. //This above code calls Subclass method Test t1=new B().println("---Result---"+res2).calculate(4). double res1=b. //This above code calls Subclass overridden method B b2=(B)t1.lang.calculate(16).out. double res = t. //In the above line if we keep t reference also it throws ClassCastException double res3=b2.sqrt(x).ClassCastException: com. System. //This above code calls Superclass method B b =new B().calculate(4). } } public class MethodOverride { public static void main(String[] args) { Test t=new Test().COREJAVA return Math.0 Exception in thread "main" java. double res2=t1. System.sqrt(x).0 ---Result---2. System.out.out.0 ---Result---2.Test Page 63 of 191 .calculate(4). } } class B extends Test{ double calculate(double x){ return Math. //This above code calls Subclass Overriden method B b1=(B)new Test(). System.calculate(4). double res4=b1.println("---Result---"+res1).println("---Result---"+res4).out.out.println(“Result = ”+res). } } O/P: .vara. //The above code throws ClassCastException } } Output:---Result---16. } } class Poly { public static void main(String args[ ]) { One t = new One().  Object type determines which overridden method is used at runtime.println(b.  When we are overriding the methods superclass methods must throws superclass exception and in subclass method should throws subclass exception.  Polymorphism applies to overriding. A1 a1=new B1(). } public class TestSuperInt { public static void main(String[] args){ A1 a=new A1(). Q) Whatis the functionaldifferencebetweenmethodoverloadingandmethodoverriding?***** Ans:A programmer uses method overloading when he wants to extend an already available feature. } } 50 60 50 60 Methodoverriding:.println(b1. System.i). System. This means only sub class method is executed.  The argument list must exactly match that of the overridden method. this is the rule for overriding a method.println(a.  The overriding method must not throw new broader checked exceptions than those declared by the overridden method.  When a method is declared certain exceptions and you want to override that method you can cut of all your runtime exceptions while overriding and any general level exceptions like the parent exceptions can be replaced with its subclass exceptions list.java:31) class A1{ int i=50.marlabs.  The access level must not be more restrictive than that of the overridden method. B1 b1=(B1)a1. System.out.main(MethodOverride.  Writing body for method is called implementation.  If superclass method is throws superclass exception and the subclass method can be without throwing an exception (or) subclass method can throws runtime exceptions.  The return type must exactly match that of the overridden method.Writing two or more methods in super and sub classes with the same name and same signature is called method overriding.i). A method overloading is code refinement. not to overloading.COREJAVA Ex: at com. System.i).i).MethodOverride.  If a method can’t be inherited we cannot override it.out. } class B1 extends A1{ int i=60.println(a1.out. Overlaoding lets you define the same operation in different ways for different data.out. In method overriding JVM executes a method depending upon the type of the reference used to call the method.  The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type.vara. Method overriding is an example for Dynamic Polymorphism. If superclass method is throws superclass exception and it should be hanlded by try & catch block. (or) you can specify the same set of the exceptions or you can leave out of all of the exceptions. Page 64 of 191 Output:- . The sub class method overrides the super class method. B1 b=new B1().  Only overrided methods are accessible by Superclass from the Subclass. double.This is the Polymorphism exhibited at compile time.These data types represent groups of values.Converting a lower data type into a higher type is called widening. Here the compiler knows which method is called and the method call is linked with method code at compile time. 2.COREJAVA A programmer uses method overriding when he wants to provide different implementation for the same feature. float. There are two types of data types. A programmer uses method overloading when he wants to extend an already available feature. Referenced data types represent groups of values.Any array. A method overriding depends on return type of a method. Lower data type means occupies lower memory and contains less numbers of data and higher data type means occupies higher memory and consists higher numbers of data. Method overriding is code replacement. long. A method overloading is code refinement. Advanced data types (or) Referenced data types: .final methods are the methods in final class. For this purpose wrapper classes are available. Data type: . 3. 3. This is also called Early binding. Using casting we can convert a referenced data type into another referenced data type. int. Overriding lets you define the same operation in different ways for different object types. Widening:. A method overriding depends on return type of a method and exception. It is also use for declare the values Ex: final class A class B extends A (Invalid) 2. Overlaoding lets you define the same operation in different ways for different data. Method overriding is code replacement. Q) Whatis the differencebetweenprimitivedatatypesand referencetypes?***** Ans:Primitive data types represent single value methods are not available to directly handle Primitive data types. Methods are available to handle them. Using casting we can covert a primitive data type into another primitive data type. String any class. Ex: .Converting one data type into another (data) type is called casting. 4. 2. this is also called Compile time Polymorphism . Ex: . Primitive data types: . A class declared as final is called final class. final methods:. Note: 1.It represents the type of data stored into a variable is called Data type. Ex: . 4. final keyword before a class name prevents the inheritance and overriding. boolean.char. A programmer uses method overriding when he wants to provide different implementation for the same feature. Primitive data types will store only single value. Overriding lets you define the same operation in different ways for different object types. We cannot use casting to covert a primitive type into a referenced type and vice versa. (or) Whatare the functionaldifferencebetweenmethodoverloadingand methodoverriding:MethodOverloading 1. A method overloading doesn’t depends on return type of a method and exception. Page 65 of 191 . CastingPrimitivedata type: 1. Ex: final class A Note: 1. MethodOverriding 1.These data types represent a single value methods are not available to directly handle Primitive data types. Static Polymorphism: .  In C++ method over loading is example for Static Polymorphism and method over riding is an example for Dynamic Polymorphism. So. 3. 1.  Primitive data types will store only single value. Methods are available to handle them. byte. Casting:. 2. 2.Achieving Polymorphism using private methods or static methods or final methods is Static Polymorphism. o = new One().COREJAVA char. In narrowing we may loose some digits or precessions. o. There must be some relationship between classes to casting. regardless of whether the overridden method declares the exception.  The overriding method can throw any unchecked (runtime) exception.  The access level can't be more restrictive than the overridden method's. Here o is reference variable.If the classes don’t have any relationship then we cannot convert from one class to another class. double Lower --------------------------------------------------- higher Ex: char ch = ‘B’. class One { void show1() { System. Casting referenceddata types: . the return type declared in the original overridden method in the superclass. float. 2.println(“One”). The rulesfor overridinga methodare as follows:  The argument list must exactly match that of the overridden method. Ex: double d = 12. int.Converting a higher data type a lower data type is called narrowing. Narrowing: . byte. If they don't match. short. } } class Two extends One { void show2() //overriding – void show1() { System. We can cast one class type into another class type only if there is a relation between those classes by the way of inheritance. A subclass in a different package can override only those nonfinal methods marked public or protected (since protected methods are inherited by the subclass).  A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. int n = (int)d. Ex: float f = (float)n. o.out.123.println(“Two”).  The return type must be the same as. Page 66 of 191 .We can convert char into int type only. } } class Cast { public static void main(String args[ ]) { //Super class reference to refer super class object One o. int n = (int) ch. or a subtype of. } }  Reference variable always use to refer to an object One o. Ex: int n = 65. long.  The access level can be less restrictive than that of the overridden method. //Here (int) is cast operator.show2(). char ch = (char)n. Ex: //Casting referenced data types. Note: .  Instance methods can be overridden only if they are inherited by the subclass. Here it is temporary conversion of n only.out.show1(). you can end up with an overloaded method you didn't intend. println(“One”).  You cannot override a method marked static. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks.  You cannot override a method marked final. Exception. 2nd Combination:Ex: //Casting referenced data types. class One { void show1() { System.println(“One”). We'll look at an example in a few pages when we discuss static methods in more detail.  The overriding method can throw narrower or fewer exceptions.out. t = new Two(). } }  Here subclass can access to superclass (inheritance). } } class Two extends One { void show2() Page 67 of 191 .COREJAVA  The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. } } class Two extends One { void show2() { System.We can use Superclass reference to refer to superclass object.show1(). For example. a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException. Remember that overriding implies that you're reimplementing a method you inherited! Note: . regardless of what the overridden method declares. Subclass reference to refer to subclass object. you cannot override it. t.println(“Two”). class One { void show1() { System.  If a method can't be inherited. } } class Cast { public static void main(String args[ ]) { //Subclass reference to refer superclass object Two t.  Inheritance we create an object to subclass not to superclass.out.  When we create an object to the subclass then it contains a copy of superclass.out. 3rd Combination:Ex: //Casting referenced data types. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw. t. or any other non-runtime exception unless it's a subclass of FileNotFoundException.show2(). Here we can refers to all superclass members.  Abstract means a method without a body.println(“Two”).Coming down from super class to sub class is called specialization or downcasting or narrowing.out. } } Ex: Citrous Fruits class Non-Citrous Lemon Orange Apple Banana Q) Whatis generalization?***** Ans:In inheritance hierarchy moving up from sub class to super class is called generalization or upcasting or widening. o. the super class members/methods are accessible.  In widening sub class members are not available. unless they over ride super class method. -- It is not required for overriding. Ex: //Casting referenced data types. class One { void show1() { System. } } class Cast { public static void main(String args[ ]) Page 68 of 191 .COREJAVA { System.show1().println(“One”). o. o = new One().println(“Two”).out.  In widening.show2().out. abstract class One { abstract void show(). } } class Cast { public static void main(String args[ ]) { //Super class reference to refer to sub class object One o.It contains abstract methods then that class is called as abstract class. } } class Two extends One { void show2() { System. Q) Whatis specialization?***** Ans:. } Abstractclass:. Methodbody:. Two t = Two(o).Abstract method is a method without a body. In narrowing we can refer to super class methods as well as sub class methods also.out. Abstractmethod:.COREJAVA { One o. Methodheader/prototype:void calculate(double sal) 2. Page 69 of 191 .println(“One”). o = (One)new Two(). 4th Combination:Ex: //Casting referenced data types. t.See above all.We can not use sub class reference to refer to super class object. In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Ex: // abstract class Car { //every car will have a regno int regno. } } Note: . } } class Cast { public static void main(String args[ ]) { Two t. Note: .When the same method has different implementations (different bodies) the programmer cannot write any body for the method in the super class.out.show2(). Q) Whatis wideningand narrowing?***** Ans:. } } class Two extends One { void show2() { System. } } Here we created an object to sub class.show2().show1(). t = (Two)new One(). class One { void show1() { System.It represents how to implement the body features. t. Two t = Two(o).println(“Two”). t. Abstract classes are excellent candidates inside of application frameworks. A class with abstract methods is called abstract class both the abstract method and abstract class must be declared with abstract. A method will have two parts 1. Abstract classes let you define some default behaviour and force subclasses to provide any specific behaviour. } } Save it & compile it. System.out. } /*every car will have steering. } Save it & compile it. System.out. } Save it and compile it.println(“Apply brakes to stop the car”).println(“Please drive the car”).out.println(“Take the key and fill the tank”).println(“Santro uses gas brakes”). /*every car will have brakes. } void steering(int direction) { System. The mechanism to fill the tank is same for all cars*/ void filltank() { System. But different cars will have different steering mechanism*/ abstract void steering(int direction).out.out.println(“Santro uses power steering”).out.println(“Maruti uses hydraulic brakes”).COREJAVA //to store a regno value Car(int r) { regno = r. //This is a concrete sub class of car class class Santro extends Car { Santro(int regno) { super(regno). //Let us use a car class UseCar { public static void main(String args[ ]) { Page 70 of 191 .out. } void braking(int force) { System.println(“Apply brakes to stop the car”).out. } /*every car will have a fuel tank.println(“Maruti uses manual steering”). System.out. //This is a concrete sub class of car class class Maruti extends Car { Maruti(int regno) { super(regno). But different cars will have different breaking mechanism*/ abstract void braking(int force). System.println(“Start the car”). } void steering(int direction) { System. } void braking(int force) { System.  In interface here all the abstract methods. The reference of abstract super class can be used to refer to objects its sub class. Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. Page 71 of 191 .methods hierarchy.  In interface we have the abstract methods. Santro s = new Santro(1111). An interface ------can also declare constants. 2. Interface will solve all the ambiguities caused by this ‘diamond problem’.An Interface defines a protocol of behavior that can Abstract be implemented by any class anywhere in the class ------. Java does not support multiple inheritances. We cannot create an object to abstract class. 7. An abstract class must be subclassed. An abstract class can have variables/vars. 11. All the abstract methods of the abstract class should be implemented (body) in its sub class. //Create a reference to Car class Car ref. 8. 3.steering(2). (or) ref = s. complete methods and abstract methods. If abstract method is not implemented then that sub class should be declared “abstract”.  We can provide several classes for the same interface.  We can create reference to the interface.4 implement them.braking(450). 6. you should prefer using Implementation class interface to abstract.java then compile and run it. If you need to change your design frequently. But we can create a reference variable to abstract class. }  } Save this above code as UseCar. Prototypes will be in the interface. // ref – reference variable to Car class //Use Maruti ref = m. An abstract class cannot be both abstract and final. Interface:. where the 4 4 client wants to only deal with a type and does not care about the actual implementation use interfaces. An interface is a specification of method proto types. An abstract class will have constructors. 4.filTank(). The reference of abstract super class cannot refer to the individual methods of the sub class. Java only supports multiple interface inheritance. 10.  We can provide n number of implement to interface. AbstractClass:1. //Now use it ref. For polymorphic interface inheritance.  All the methods are incomplete only. An interface defines a set of methods but doesn’t ------. 5. Another justification for using interfaces is that they solve the ‘ diamond problem ’ of traditional multiple inheritance as shown in the figure.COREJAVA //take new Maruti an Santro cars Maruti m = new Maruti(6666). ref. An abstract class is a class with 0 or more abstract methods. abstract final class A (invalid). Implementation class is a class. All the methods of the interface are abstract. 9. An interface is a named collection of method definitions (without implementations). ref.  We can’t create an object to interface. and those constructors are always called when a concrete sub class is intantiated. So must implement all methods in a class (this can also contain or within body to that methods) this class is called implemented class. where all the methods in a class. C.  API document is a . } connect() } mi method class MysqlDB implements MyInter { c references that object public void connect() { System. To manage and to store the data.println(“Connecting to Oracle database…”). Implementation Databases class (I.  Driver is an implementation class.  By default all the methods of interface are public & abstract. Ex: //Interface example interface MyInter { void connect(). Mysql  void method() this support all or any database in the world.out. } } class SybaseDB implements MyInter { public void connect() c OracleDB { System.println(“Connecting to Mysql database…”).out.) Oracle * Sybase * I. * I. Data is stored in the form of tables.  All the methods in interface are abstract. void connect() { ---------------------------------------------------------} main method API doc.out. that contains description of all the features of a software or a product or a technology.C.  Interface is more powerful than class. } } c OracleDB class Database { public static void main(String args[ ]) connect() throws Exception mi method Page 72 of 191 c references that object .html file. //public abstract } class OracleDB implements MyInter { public void connect() { System.println(“Connecting to Sybase database…”).  The database & to retrieve the data. database is needed. Boy for the method remove it & use interface.COREJAVA  Interface contains only names.  Database is repository of data. where the methods are implemented. C. MyInter mi = (MyInter)c.java MysqlDB↵ Interface:1.connect(). Interface methods must not be static. 2. interfaces can declare only constants. Interface reference can be used to refer to the objects of implementation classes. 5. 11. (or) AbstractClass 1. All the methods in the interface are incomplete only. We cannot create an object to an interface. 2. //Call connect() method using mi mi. A programmer writes an interface.. 3. it should be declared as “abstract”.newInstance(). 6. A class can implement multiple interfaces. A programmer writes an interface. All the methods of the interface are public and abstract by default. and those constructors are always called when a concrete sub class is intantiated. 15. If any method is not implemented in an implementation class. An interface defines a set of methods but doesn’t implement them. 9. 2. An interface contains o or more abstract methods. 4.java↵ C:\rnr>java Database. Interfaces are not part of an object’s inheritance tree. An interface is a specification of method prototypes. when all features are implemented differently for different objects. Page 73 of 191 . 12. 7.java C:\rnr>javac Database. Once an interface is written. In another words. Because interface methods are abstract. All the abstract methods of the interface should be implemented in its implementation class. they cannot be marked final. All the methods of the interface are public and abstract by default. Interface dos not have constructors. which are public static and final by default. Q) Whatis the functionaldifferencebetweenan abstractclassandan interface?***** Ans:. 3. 5. But we can create a reference of interface type.A programmer uses abstract class when some common features are shared by all the objects. //Create an object to the class whose name is in c. Absract class will have complete methods. 13. An interface cannot implement another interface. Interfaces are not part of an object’s inheritance tree.java OracleDB↵ C:\rnr>java Database. Interface does not have constructors. any third party vendor can implement it. All the methods of the abstract class are not public and abstract by default.java SybaseDB↵ C:\rnr>java Database. Interface 1. or native. 10. when all features are implemented differently for different objects. A programmer uses abstract class when some common features are shared by all the objects. not instance variables. An abstract class will have constructors. An interface can extend another interface. 8. 5. 4. We can write a class inside an interface. 4. 17. strictfp. } } Save it Database.COREJAVA { //Accept the database name and store it in object c. An Interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. 14. An interface may have variables. 16. An abstract class is a class with 0 or more abstract methods. 3. All the methods are incomplete only. Class c = Class forName(args[0]). COREJAVA 6. An abstract class will have instance variables in its concrete sub class. . 7. An abstract class can extend only one another class. 8. An abstract class methods can be declared as static in its sub class. 6. An interface may have variables, which are public static and final by default. In another words, interfaces can declare only constants, not instance variables. 7. An interface can extends multiple interfaces (or) a class can implements multiple interfaces. 8. Interface methods must not be static. Because interface methods are abstract, they cannot be marked final, strictfp, or native.  Howmuchmemoryis occupiedby classtwoobjects?***** Ans:- class One class Object { { int x; object } } class Two extends One class One extends Object { { int y; int x; } } class Two extends One { int y; } object – It will occupies some memory. We can not say exact memory. Howmuchmemoryis occupiedby classTwoobjects [ c ] a) 4 bytes b) 8 bytes c) >8 bytes d) None of the above Typesof inheritance:1. Singleinheritance:- Producing sub classes from a single super class is called single inheritance. A B B class B extends A A C class B extends A class c extends A 2. Multipleinheritance:- Producing sub classes from multiple super classes is called multiple inheritance. A B class A A B class A class B C class B C D class C extends A, B in valid in Java class D extends A, B in valid in Java class C extends A, B in valid in Java  Multiple inheritance does not support in java. Q) Whymultipleinheritanceis not availablein java?***** Ans:Multiple inheritance leads to confusion for programmer. This is against to the aim of java to be a simple programming language. Java = C++ - Complexity Page 74 of 191 COREJAVA  There is no operator loading in java. There is no destructor. Destructor work is done by garbage collector. Q) Howcanyoucall garbagecollector?***** Ans:By calling System.gc();. It will runs the garbage collector. Runtime and system classes of java.lang package System.gc(); is available. Q) Canyou createobjectto the systemclass?***** Ans:- No, It is not possible. System class cannot be initiated because it contains static methods. finalize() method belongs to class of java.lang package. finalized method destroy the memory. If you call the finalize() method it may crash the program, so it is better to avoid calling finalize() method. finalize() method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release nonmemory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method. Garbage collector will works automatically; we should not required to call it. 3. Multiple inheritance can be achieved by programmers by using interfaces. class Z extends A, B (Invalid) class Z implements A, B (Valid) – It is indirect way achieving multiple inheritance. (Refer the point of interfaces summary) A class can implement more than one interfaces. 4. Multiple inheritance can be achieved by repeated use of single inheritance. (1) (2) (3) Multiple level inheritance Hierarchical Hybrid inheritance From figure (3) above the line is multiple inheritance and below the line is single inheritance. So it is the combinations of single & multiple inheritances. Ex: //Multiple Interface example interface Father { int PROP1 = 500000; //public static final, final means fixed values float HT1 = 6.2f; } interface Mother { int PROP1 = 800000; float HT1 = 5.0f; } class Child implements Father, Mother { void property() { System.out.println(“Child’s Property = ”+(PROP1 + PROP2)); } class Multi { public static void main(String args[ ]) { Page 75 of 191 COREJAVA Child ch = new Child(); ch.property(); ch.height(); } } Child’s property = 13, 00, 000 Child’s height = 5.6 O/P: - Packages:- A package represents a sub directory that contains a group of classes and interfaces. import java.awt.*; From the above statement * represents classes and interfaces of that package only but not available in packages. import java.awt.event.*; From the above statement event is package which does not available to import java.awt.*;, so if you want to use classes and interfaces of event package we must use import java.awt.event.*; Advantages:1. Packages hide classes and interfaces in a directory, accidental deletion is not possible. 2. The classes and interfaces of one package are isolated from the classes and interfaces of another package. Ex: java.util.Date dd mm hh mi.ss (1sec = 1000 milli seconds) java.sql.Date dd mm hh mi.ss 3. Packages provide reusability.  Java is objective oriented language because it obeys all the object oriented methods.  Java increases the productivity by using reusability. Packaging a Web Application: - The standard packaging format for a web application is a web archive file (WAR). A WAR file is simply a JAR file with extension .war as opposed to .jar. You can create a WAR file by using jar, java’s archiving tool. C:\BTCE\>jar cvf anand.war↵ C:\BTCE\>jar xvf anand.war↵ 4. Packages can be extended a new packages can be created. Disadvantageof Java: Disadvantage of java is, java programs execution is slower than C/C++ programs, because of .exe file will be created after compiling the C or C++ program. Where as in java .class will be created first after that this .class will converted into machine language by JVM after that processor execute this machine language. Page 76 of 191 0. but rather.class. double b) { return(a – b).  Java does not support multiple inheritance.  Java does not have the delete operator.println(“Sum = ”+(d1+d2)).d1 = d1.java and Use. Addition. Page 77 of 191 . } } Save it as Subtraction. It is not available in JDK 1.  All the code in a Java program is encapsulated within one or more classes.Addition(10.” means current directory. So we have to keep . this.pack infront of Addition. double d2) { this. } }  BufferReader is available from JK 1. Java does not support destructors.6).class file of (previous program) Addition. In the above code if you don’t declare public you can not able to create object for addition for out side package to available. add the finalize() function. In the above statement pack contains .COREJAVA  Java does not support pointers. } } Save it as Adition.class are available in rnr directory. public Addition(double d1. //Using the package after creating: pack class Use { public static void main(String args[ ]) { pack.  Java does not support operator overloading.java file will stored in the rnr root directory. Pointers are inherently insecure and troublesome. Therefore.  The << and >> are not overloaded for I/O operations Ex: //Creating our own package: pack package pack.class file will stored in pack sub directory and Addition. (iii) Java does not perform any automatic type conversions that result in a loss of precision. //Adding another class to package: pack public class Subtraction { public static void sub(double a.  From API document we will understand now many values to pass in parameterized constructor and sum() method does not return anything. public class Adition { double d1.1.Adition obj = new pack. pack. After compiling the above code now it will creates pack sub directory to the rnr and Addition.java↵ In the above “-d” means to create a directory or a package and “.out. Use.Adition obj = new pack.d2 = d2.Adition(). 15. obj = sum(). Java does not have global variables or global functions.java C:\rnr>javac –d .java  Static method means this method does not acts upon instance variable. Since pointers do not exist in Java. 2. } void sum() { System. import pack.MyInter.%CLASSPATH%↵ In the above CLASSPATH keep old class path without disturbing.util. Java compiler searches for the package in the current directory and sub directories (after cutting those Addition.java files and paste in another new folder (pool – to available others).java↵ (GMT means Green witch mean time) (1) //Using the interface Page 78 of 191 .java↵ //this is implementation class for MyInter package pack.//public abstract //In the above showData() will be default public abstract C:\rnr>javac –d . double x = pack.out.Date. Java compiler searches for the package in the current class path. } } To avoid pack. Java compiler takes the current directory as package and searches for .*.println(d).java and Subtraction. import java. MyInter.java↵ //Using the package after creating: pack class Use { public static void main(String args[ ]) { pack.out. 15.Addition as below.Substraction in creating objects we have to import pack.5). 15. } } C:\rnr>javac –d . MyDateImpl. System.Substraction. import pack.Subtraction sub(10.Addition.class files in the current directory. System. 4. public class MyDateImpl implements MyInter { public void showDate() { Date d = new Date().\Addition.Addition and pack. class Use (or) //Using the package after creating: pack import pack. 3.println(“Result = ”+x).jar format in C:\j2sdk1.COREJAVA C:\rnr>javac –d .4. Class path is a system variable (it is provide by operating system) that stores active directory path. //Using the package after creating: pack import pack.*. Java compiler searches for a package in .Adition(10.java 1. public interface MyInter public class Adition { void showDate().1_01\jre\lib\ext 2.Adition obj = new pack.5). C:\rnr>echo %classppath%↵ %classpath% Howto set CLASSPATH:C:\rnr>set CLASSPATH = d:\. Subtraction.. obj = sum(). Ex: //An interface in a package: pack package pack. class Use badclassfile: . import pack. } } From the above 2nd is efficient. Private members of class are not accessible on other classes of the same package or another package.out. } } C:\rnr>javac –d . public 2. Set classpath = C:\rnr\inner. class Use { public static void main(String args[ ]) { Sample s = new Sample(). public class Sample { public void display() { System.Sample.If the package in other sub directory (not in current) you will set class path. default 1.java↵ //Using the sub package import inet. mi.solv. Page 79 of 191 . . private 3. } } (2) //Using the interface import pack. There are four access specifiers in java. s.showDate().MyDateImpl.showDate(). 1.println(“Hello Students”). } } Note: . Public members of a class available in the other classes of the same package or another package scope of public members is global scope or makes a class. In (1) we are calling only MyDateImpl methods but in (2) we are calling MyDateImpl methods on well as class use methods.display(). class Use extends MyDateImpl { public static void main(String args[ ]) { Use u = new Use(). Sample. Ex: //An interface in a package: pack package pack. protect 4. The scope of private members is with in the class or class scope or (or) makes a method or a variable accessible only from within its own class. 2. %classpath%↵ Access specifier is a keyword that represents how to access or retrieve the members of class. u. class Use { public static void main(String args[ ]) { MyDateImpl mi = new MyDateImpl().COREJAVA import pack. .MyDateImpl. method or variable accessible from any other class. Default members are available in other classes of same package but not in another package default members scope is package scope. } Class E { a1. a1. } package p2.d. protected double d. class A{ int i. } package p1. } package p1. but not in another package or makes a method or a variable accessible only to classes in the same package or subclasses of the class.Protected members always available in sub class in the same package or another package. Default members are available in other classes of same package but not in another package default members scope is package scope. class C { F. d.i. class B extends A{ F. public float F. 4. a1. d. Protected members are an accessible in the sub classes of same package. Q) Differencebetweenprotectedanddefault?***** Ans:. private char ch. } package same. void disp( ){ i. Visibility From the same class From any class in the same package From any non-subclass class outside the package From a subclass in the same package From a subclass outside the same package Ex: package p1. d. class D extends A{ F. F. Public Yes Yes Yes Yes Yes Protected Yes Yes No Yes Yes Default Yes Yes No Yes No Private Yes No No No No Ex: - Page 80 of 191 .COREJAVA B ×    A private public protected default × × C × same another 3. ch.F. println(obj.println(obj. 2. Import this package into a main program and display the values.A method. which is not approved to used programs that are deprecated method. Page 81 of 191 . Create a figure class with 2 instance variables x. Convert the comments into java documentation comments. public class C { public static void main(String args[ ]) { A obj = new A().W. } package same.A.html files will be created with index . import same.println(obj.ot.b). System. Create a package with 3 classes to calculate square root value.A. double value = math.pow(x. System. import same.sqrt(x).java↵ We compile some . System.COREJAVA public class A { private int a = 1.ot. y).c).ot. 21.ot.ot.html is very important this is our files. System. protected int c =3. int d = 4. System.println(obj. CreatingAPI document:1.c). Similarly derive triangle class and circle classes and display their areas. } } Note: . System. power value and factorial values.a). System. double value = math.b).a).d). } } package another.Static variables another name is class variables. Copy all source code files into a directory.println(obj. y in a package called gco path. these variables only display on the API document not any other variable.println(obj. public class B { public static void main(String args[ ]) { A obj = new A().ot.ot. private int b = 2.ot. } } If C will extend public class C extends A { public static void main(String args[ ]) { C obj = new C(). This index .println(obj. C:\rnr>javadoc *.println(obj. 20.html file. Note: .d). Then import that package into rectangle class and the area of the rectangle (your rectangle class extends figure). System. H. out.  Removing the errors is called debugging . So the programmer should handle to exception by performing the following tasks. 3. } System.println(“n = ”+n).  Every exception is a sub class to Exception class. 11. No. int a = 45/n. Error Exception } catch (Arithmetic ac) { System.out.length.out. the program is terminated abnormally in the middle. Throwable System. 9.An exception is an error that can be handled. Q) Whatare checkedexceptions?***** Ans:.out.An exception is runtime error. Ex: //An Exception example class Ex { java.  Logical errors are the errors commited in the logic. } } When there is an exception. 2. List of classesandExceptionclassesin java.COREJAVA Exception:.These are the exceptions. This may spoil the user data. 7. 5. These errors canot be detected by compiler or JVM. If it occurs.println(ac). abnormal termination will happen. Boolean Byte Character Class ClassLoader Double Float Integer Long Math Object Classes Throwable Exception ArithematicException ArrayIndexOutOfBoundsException ClassCastException ClassNotFoundException CloneNotSupportedException IllegalAccesException IllegalArgumentException IllegalStateException IllegalThreadStateException Page 82 of 191 ExceptionClasses .println(“Class all”). Q) Whatis differencebetweenexceptionand error?***** Ans:. 4. 10. These errors can be detected by comparing the programme output with manually calculated results.All runtimeexeptionsare called as unchecked exceptions which are dectedby JVM. 8. An error cannot be handled it.println(“a = ”+a).langpackage: S.  DeskCheckingis the solution for compiletimeerrors . 1. Q) Whatare uncheckedexceptions?***** Ans:. 6.  Exception is an abnormal event in the program. System.  An Error in a program or software is called bug .lang public static void main(String args[ ]) { Object try{ int n = avgs.  Exceptions are represented by classes in java. which are detected by the compiler at the time of compilation. COREJAVA 12. Error AbstractMethodError AssertionError ClassFormatError IllegalAccessError InstantiationError NoClassDefFoundError NoSuchFieldError NoSuchMethodError OutOfMemoryError StackOverFlowError Error Classes 1. if there is an exception. 2.langpackage:S. 8. It will store exception details in stack. Runtime Short String StringBuffer System Thread ThreadGroup IndexOutOfBoundsException InstantiationException InterputtedException NegativeArraySizeException NosuchFieldException NoSuchMethodException NullPointerException NumberFormatException RunTimeException StringIndexOutOfBoundsException List interfacesin java. 20. 11. 15. 19. 16. 1. 17. The programmer should write all the statements. No. 14. Cloneable Runnable Comparable Interfaces List Error classesin java. It will jump into catch block. try { statements. 3. 3. 10. 1. Page 83 of 191 . } JVM examines the statements inside try blocks for any exceptions. 4. 9. No. 7. 13. 2. After storing exception details in a stack. try { statements.langpackage:S. 18. Exception Stack } catch(Exception class obj) { statements. } The JVM will jump before catch block. 5. 6. 21. which may cause exceptions inside try block. If any code in the try block is executed. }  A try block and catch block can be written either in a method or in a loop.catchblockis executedonly if thereis an exception .  finally block is optional. Otherwise it throws UnreachableException.  When we are handling the multiple exceptions using try & catch blocks in first catch block we have to catch/write the subclass exception and in the second catch block we have to write superclass exception. finally bock will not executed if we put System. So that the data in the files and database is not lost. we can write try & catch blocks within a catch block and we can write try & catch blocks within a finally block also. then finally block is guaranteed to be executed regardless of whether any catch block is executed. try{ statements. } catch(Exception class obj){ statements. } finally{ statements. } catch(Exception class obj){ statements. } }catch(Exception class obj){ statements. finally Block: . Ex: try{ statements. finally block must use when we write break or return statements in try or catch blocks. in the try block.  We can write try & catch blocks anywhere it means we can write try & catch blocks within a try & catch blocks. Note: . } finally{ Page 84 of 191 . The programmer should close all the files and databases by using finally block.  A try block must have atleast catch block or finally blcok. } catch(Exception e){ statements. Note: . 3. Ex: try{ try{ statements.exit(0). In otherwords we write nested try & catch blocks. }  Performing the above three steps is called exception handling.finally statement or block is executed always whether there is an exception or not.COREJAVA 2. finally block can be used to specify any clean up code. The programmer should write any messages to the user and also he should display exception details to the user in catch block.  In the try block or in the catch block we can providebreak or return statements. } catch(FileNotFoundException fofe) //FileNotFoundEception is a subclass of IOException{ statements. } catch(IOException ioe){ statements. } finally{ statements. } catch(Exception class obj2){ statements. System.println(“n = ”+n).printStackTrace().COREJAVA close the resources. } finally{ System.println(“Class all”). catch(ArrayIndexOutOfBoundsException aie) { aie. } } By handling exception that programs are called Robust programs.println(“Please enter the values: ”). } finally{ statements.printStateTrace() Page 85 of 191 . } DisplayError Message: try{ open_the_file } catch(<exceptionType obj>){ //appropriate exception handler obj. } catch(Exception class obj1){ statements. } } catch (ArithmeticException ae){ System. System.out. try{ statements.println(ae).println(“a = ”+a). }  A try block can haveany numberof catchblocks .getMessage()). the line where was the error occurred and the exception type at the console. try{ statements. }  But a try block can have only one finally block .  getMessage() returns the error message alone. }  Using the capatured exception type object you can findout where the error is occured and what is the error messages.out. } catch(Exception class obj){ statements.  printStackTrace() will display the error message.println(obj. Ex: class Ex{ public static void main(String args[ ]){ try{ System.out.out. It doesn’t tell us where the error was occurred and what type of exexption it is. int a = 45/n.out. statements. System.out. io. System.length()). } } class Demo { public static void main(String args[ ]) { Sample s = new Sample().out.accept(). But we can write a try block without a catch block. So throw is the example of an annonymous class.in)).*.  Using throws clause you can specified multiple exceptions. 2.out.println(“Array index is not within the range”).  throws cluase is used to propagate an exception.out. Note: . void accept() throws IOException  throws clause is always specified against a method. Throw: .io. Ex: //throw import java.println(“Hello”+name). public static void main(String[] args) { System. System.This is used to create an exception object and throw it out of a try block. We can write a try block followed by multiple catch blocks.println(“Enter your name: ”). class Demo { static void Demo() { try { Page 86 of 191 . if we are directly throwing the exception of the created object.  If we are not storing the instance of any exception into an object variable of that exception type. Throw is used in try block. the caller of the method must handle that particular exception by writing try & catch blocks. } 1.It will throw NullPointerException Throwsclause:. s. We can’t write a catch block without a try block.readLine(). String name = br. } } O/P: .This is used to throw out an exception without handling it.out.println(s. } } Ex: //NullPointerException public class NPE { static String s. when we don't associated any instance with the object variable of itself it is called as Annonymous object or Annonymous instance .COREJAVA System.  Whenever throws clause is used against a method.*. class Sample { void accept() { BufferedReader br = new BufferedReader(new InputStreamReader(System.throws exception represents any type of exception because exception is the superclass of all exceptions. Ex: //Not handles the exception import java. Ex: ArithmeticException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException IOException RuntimeException Any type of Runtime Exception FileNotFoundException NoSuchMethodException ClassNotFoundException NumberFormatException InterruptedException NullPointerException CheckedExceptions FileNotFoundException ClassNotFoundException CloneNotSupportedException NoSuchMethodException NoSuchFieldException IllegalAccessException InstantiationException InteruptedException IOException SQLException SocketException EndOfFileException UncheckedExceptions IndexOutOfBoundsException StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException ArrayStoreException ArithmeticException ClassCastException UnsupportedOperationException NegativeArraySizeException NullPointerException NumberFormatException ObjectNotFoundException IllegalArgumentException IllegalStateException IllegalThreadStateException IllegalMonitorStateException SecurityException TypeNotPresentException (Addedby J2se5.These are the exceptions available in java.  Unchecked exceptions are run timeexceptionssubclasses are java. 2. Throw clause is used to forcibly to create an exception and handle it using throw. Page 87 of 191 . 1.lang.)  Checked exceptions are compiletime exceptionssubclasses java.println(ne). This is used to create user-defined exceptions and throw them out. } } Q) Whatis the differencebetweenthrowsand throw?***** Ans:Throws clause is used not to handle an exception .COREJAVA System.out.Exception. Throw clause is used in between testing.RuntimeExcetion. } } } public static void main(String args[ ]) { Demo() //Demo is static method. a) Inbuilt Exceptions:.println(“Inside Demo”).out. throw new NullPointerException(“My Data”) } catch(NullPointerException ne) { System.lang. RuntimeException(Simply the super class of corresponding type). 3.77. Write your own Exception class that extends Exception class. CreatingUser definedException:1. throw me. i<5. } public String toString(){ return "Credit Card Number " +ccn +" is invalid. Write a default constructor in your own Exception class. } MyException(String str) { super(str). 12000.class InvalidCCExcep extends Exception{ String ccn="". public InvalidCCExcep(){ } public InvalidCCExcep(String cc){ this. 1002.out. try{ m1(ccn).COREJAVA b) User definedExceptions:. 1990. private static double bal[ ] = {5000.out. Ex: class MyException extends Exception { private static int accno[ ] = {1001.75}.99. 2. MyException() { state. }catch(InvalidCCExcep e){ System.out.println(“Account”+”\t” + “Name”+”\t” + “Balance”+”\t”). i++) { System. Write a parameterized constructor with a String as a parameter.ccn=cc.println(e). } } catch (MyException me) { me. private static String name[ ] = {“Raju”. for(int i = 0.These are exceptions create by user. 50. “Rani”.printStateTrace(). } } Page 88 of 191 . } } } Ex 2: .7007. Try Again". 1200. } } public class UserDefineExcep{ public static void main(String as[]){ String ccn=as[0]. “Sita”. 4. When ever needed create an object to your Exception class and throw it and clause. //If bal<2000 then paid No Exception MyException me = new MyException().Throwable. 1003}. “Vinay”}.println(accno[ i ] + “\t” + name[ i ] + “\t” + bal[ i ]). } public static void main(String args[ ]) { try { System. } else{ throw new InvalidCCExcep(ccn). static char toLowerCase(char ch) Page 89 of 191 . Primitivedata type char byte int float double long Wrapperclass Charcter Byte Integer Float Double Long Characterclass:Constructor:1. 6. //If we are not storing the instance of InvalidCCException into an object variable of that InvalidCCException type. 2. 2. 4. 1. Methods:1. 3.length()==16){ System. Character obj = new Character(ch).. To convert primitive data type in to objects we need wrapper class. 8. Different applications on internet send or receive data in the form of objects. S. it cannot extends other classes. char charvalue() returns the char value of the invoking (calling) object. static boolean isDigit(char ch) returns true if ch is a digit (0 to 9) otherwise returns false.  A wrapper class is a final class that prevents the inheritance i.COREJAVA public static void m1(String ccn) throws InvalidCCExcep{ if(ccn.langpackage. static char toUpperCase(char ch) converts ch into uppercase 9. ENTER. when we don't associatedany instancewiththe objectvariableof itself it is calledas Annonymousobjector Annonymousinstance. static boolean isLowerCase(char ch) returns true if ch is a lowercase letter (a to z) 6. } } } WrapperClasses:We should convert primitive data types into objects because of the following reasons.charValue().OK"). if we are directly throwing the InvalidCCException of the created object. Character.e. 7. static boolean isLetter(char ch) returns true if ch is a letter (A to Z or a to z) 4. static boolean isUpperCase(char ch) returns true if ch is an uppercase letter (A to Z) 5. BACKSPACE.isDigit(ch).out. 1. 5. char ch = ‘1’. 2. static boolean isWhiteSpace(char ch) returns true if ch is coming from TAB.  Wrappingmeanscontainingor storing.  Wrapper classes overridden the equals() and hashCode() of object class. char ch = obj. All the classesin java.println("OK. A wrapper class is a class. 3.util packageact upononly objects. Character (char ch) char ch = ‘A’.  All wrapper classes are defined in java. whose object wraps or contains primitive data type. static boolean isSpaceChar(char ch) returns true if ch is coming from “SPACEBAR”. No. (2) byte n = 120. Char ch = (char)br. static byte parseByte(String str) throws NumberFormatException returns the byte equivalent of the number contained in the string specified by ‘str’. Ex: //Creating and comparing Byte objects import java.out. Returns 0 if the values are equal. System.out. class CharTest { public static void main(String args[ ]) throws IOException { //to accept a char from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System. 1. Methods:1.*. else if(Character. //test ch if(Character.COREJAVA Ex: converts ch into lowercase //Testing a char import java. } } Byte class:Constructor:.println(“Enter a char: ”). class Byte { Page 90 of 191 .println(“It is whitespace letter”).isLowerCase(ch)) System.Byte is the wrapper class of primitive byte.io.*.println(“It is from Spacebar”).isSpaceChar(ch)) System. Returns a negative value if the invoking object has a lower value.println(“Sorry.out.isWhiteSpace(ch)) System.in)). Byte(String str) -----------------. int n = b1. if b1 == b2 n =0 if b1 > b2 n>0 if b1 < b2 n<0 3. 4. int compareTo(Byte b) Compares the numerical value of invoking object with that of ‘b’. I don’t know that char”). from (1) Byte b1 = new Byte(). static Byte valueOf(String str) throws NumberFormatException returns a byte object that contains the value specified by the string ‘str’. Returns a positive value if the invoking object has a greater value. byte byteValue() returns the value of invoking object as a byte. else if(Character.io. else System.compareTo(b2). 2.println(“It is lowercase letter”). from(2) String s = “120”.read().isDigit(ch)) System.out.out. Byte(byte num) -----------------.isUpperCase(ch)) System.println(“It is a digit”). Byte b1 = new Byte(s).out.out. else if(Character. else if(Character. 5.println(“It is uppercase letter”). String toString() returns a string that contains the decimal equivalent of the invoking object.(1) 2. out. if(n == 0) System. int compareTo(Integer obj) Compares the numerical value of invoking object with that of ‘obj’.in)). str = br.println(“”b1+” is lesser).readLine(). } } Integerclass:Constructor:. static Integer valueOf(String str) throws NumberFormatException returns a Integer object that contains the value shown by the string ‘str’. Byte b1 = new Byte(str). static String toOctalString(int i) returns a String representation of the integer argument in base 8. 4. static String toBinaryString(int i) returns a String representation of the integer argument in base 2.out. 2. Byte b2 = new Byte(str). 3. 8. 7. class Convert { public static void main(String args[ ]) throws IOException Page 91 of 191 . 5. Integer(String str) -----------------.COREJAVA public static void main(String args[ ]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System. Returns 0.out. else System. System. 6. 1. Integer(int num) -----------------.It is wrapper class for int data type. else if(n > 0) System. int intValue() returns the value of the invoking object as a int.(2) Q) Which of the wrapper classes have only one constructor (or) which of the wrapper classes does not have a constructorwith stringparameter?***** Ans:. -ve value or +ve value.out.println(“Enter another byte no: ”). static String toHexString(int i) returns a String representation of the integer argument in base 16. //Compare b1 and b2 objects int n = b1. System.readLine().Character.*.out.println(“Enter a byte no: ”).io. String str = br. Ex: //Converting int into other systems import java. Methods:1.println(“b1+”is bigger). String toString() returns a string form of the invoking object.println(“Both are same”).(1) 2. static int parseInt(String str) throws NumberFormatException returns the int equivalent of the number contained in the string specified by ‘str’.compareTo(b2). //Convert n into other systems str = Integer.It is wrapper class for float data type. Float(String str) -----------------. System.toOctalString(n). 6.(1) 2.println(“In Octal = ”+str).out. //Converting str into int. Returns 0. 2.out. String str = br. double doubleValue() returns the value of the invoking object as a double. Float(float num) -----------------. float floatValue() returns the value of the invoking object as a float. double doubleValue() returns the value of the invoking object as a double. 1. float floatValue() returns the value of the invoking object as a float. String toString() returns a string form of the invoking object. static float parseFloat(String str) throws NumberFormatException returns the float equivalent of the string contained in the string specified by ‘str’. 2. negative or positive value.println(“In decimal = ”+n). Page 92 of 191 .out.println(“In binary = ”+str). System. 5. 1. System. static Integer valueOf(String str) throws NumberFormatException returns a Float object that contains the value shown by the string ‘str’. String toString() returns a string form of the invoking object. Doubleclass:Constructor:. Double(String str) -----------------.toBinaryString(n). Double(double num) -----------------. 5. 4.out.println(“In Hexadecimal = ”+str). static Double valueOf(String str) throws NumberFormatException returns a Double object that contains the value shown by the string ‘str’. 6.(1) 2.toHexString(n). System. 3. str = Integer. int n = Integer.It is wrapper class for double data type.(2) Methods:1. } } Float class:Constructor:. negative or positive value. System. 4. static float parseFloat(String str) throws NumberFormatException returns the float equivalent of the string contained in the string specified by ‘str’.println(“Enter int value: ”).COREJAVA { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)). int compareTo(Float f) Compares the numerical value of the invoking object with that of ‘f’. int compareTo(Double d) Compares the numerical value of the invoking object with that of ‘d’. str = Integer.parseInt(str).readLine().out. Returns 0. 3.(2) Methods:1. round(4.println(i). arg2) returns the maximum of arg1 and arg2. static double min(arg1. 15. arg2) returns the minimum of arg1 and arg2. System. static double toRadius(double angle) converts angle in degrees into radius. static double random() returns the random number between 0 to 1.ceil(4. square root value and Page 93 of 191 . arg is in radians. static long round(arg) returns the rounded value of arg. static double floor(double arg) returns the greatest integer which is lower or equal to arg. int i = (int)d. static double sin(double arg) returns the sine value of the arg.random().readLine(). 8. } } } H.COREJAVA Math class:. static double ceil(double arg) returns the smallest integer which is greater or equal to arg. 7.6) is 5 13. static double sqrt(double arg) returns the square root value of the arg.5) is 4.0 10. static double cos(double arg) returns the cosine value of the arg.0 9. 3. 14. if(i ==0) System. Thread. Ex: Math. static double toDegrees(double angle) converts angle in radians into degrees.exit(“0”). Ex: //Creating ranom number between 0 to 10 class Rand { public static void main(String args[ ]) throws Exception { while(true) { double d = 10 * Math. 2. 12. arg is in radians. static double pow(double arg) returns x to the power n value.ceil(4. 11. Methods:1. String str = br.W. Ex: Math. static double max(arg1. 6.The class Math contains methods for performing basic numeric operations. 5.out.sleep(3000). Ex: Math. arg is in radians. static double abs(double arg) returns the absolute value of the arg. static double log(double arg) returns the natural logarithm value of the arg. Create a class calculate with static methods to find: factorial value. 4.5) is 5. power value. 23. static double tan(double arg) returns the tangent value of the arg. Page 94 of 191 . Collection classes or Container the classes whose Objects can handle a group of other objects. To createa stack: Stack st = new Stack(). int a) { st.util. 5 4 Ex: 3 1: . 2. } public static void main(String args[ ]) throws IOException.out.*. To knowwhethera stackis emptyor not. If the stack is empty it returns true. class StackDemo { static void stpush(Stack st. i – represents the position of element in the stack from the top. System. Stack: . 2 Elements 2.A stack represents arrangement of elements in LIFO order. int choice = 0. } static void stsearch(Stack st. 6 Removing elements from the stack is called pop operations. EmptyStackException { //vars Stack st = new Stack(). Insertion and deletion of elements will take place only from outside called stack of the top. 3. Shunting of coaches to railway engine is an example for stack. To pushan elementfroma stack: st.search(). To insert elements (Elements means objects). 4. int element.push(new Integer(a)). A Container object stores references of other objects.pop(). } static void stpop(Stack st) { Integer a = (Integer)st. import java.println(‘Popped = ”+a). 5. if the stack is not empty it returns the false. if the element is not found. use empty(): Boolean b = st. Collectionsclasses(or) Containerclass: A Collections class or Container class whose object can store a group of other objects. Inserting elements into the stack is called push stack.io.push(element). To searchfor an elementin the stack: int i = st. 1 Creationof Stack:1.*.in)).COREJAVA sine value. Ex: //Stack operations import java. To popan elementfroma stack: object element =st.pop().search(new Integer(a)). return i.A pile pf plates in a cafeteria is an example for stack. BufferedReader br = new BufferedReader(new InputStreamReader(System.empty(). This method returns -1. int a) { int i = st. pos. out. 1. element). Enumeration. ListIterator 3.println(“4 Exit”). element.out.out. stpush(st. Each node contains two fields data and link to the next node. element). else System. 1.println(“Stack =” +st). System.out. Retrieving nodes one by one done use links.out. braek. System. case 2: stpop(st).out. } } } To retrieve elements we have to use the interfaces.println(“3 search for element”).readLine()). braek.removeFirst(element).println(“Enter your Choice: ”).add(element). element).parseInt(br. case 3: System.println(“2 Pop element”).parseInt(br.Integer.out. node data link Linked list is more flexible way of arranged elements than the stack. LinkedList:. System. To removefirst elementfromthe linkedlist ll.readLine()).println(“Enter element: ”).out.readLine()). swith(choice) case 1: System. if(pos == -1) System.println(“1 Push element”).println(“Element is not found”). 3. To remove last element from the linked list Page 95 of 191 . pos = stsearch(st.println(“STACK OPERATIONS”).A linked list is a set of nodes. To createa Linked List: LinkedList ll = new LinkedList(). } System. To add element in 2nd position ll.out. To addelements(objects)to a linkedlist ll. 2.add(2.parseInt(br. default: return.println(“Enter element: ”).out. System. choice = Integer. Iterator 2. element.println(“Element found at position: ”+pos).COREJAVA //menu while(choice<4) { System. System.Integer. braek.out. ll.out.readLine()).readLine()). int pos.element).out. To remove 2nd element from the linked list ll.removeLast(element).io. braek. System.println(“Linked List = ”+ll).println(“Enter your Choice: ”).println(“Enter element: ”).readLine()).*.println(“Enter position: ”). pos = Integer.out. ll. Newelement).println(“4 Exit”).add(“India”). pos = Integer. String element. ll.println(“Enter new element: ”).parseInt(br.util. choice = Integer. System.add(“America”).out. braek.out. pos = Integer.set(2. import java. To changethe 2nd elementwith a newelement ll.out.out. class LLDemo { public static void main(String args[ ]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System. System.println(“1 Insert element”). //menu while(choice<4) { System. Ex: //Linked list with strings import java.println(“LinkedList =” +ll). swith(choice) case 1: System.out.println(“3 Change element”).println(“Enter position: ”).parseInt(br. System.println(“Enter position: ”).out. case 3: System.remove(2). ll. ll. System.COREJAVA ll.*. case 2: System. choice = 0.parseInt(br. System. ll.readLine()).add(“China”). ll.readLine(). element = br. element = br. LinkedList ll = new LinkedList(). } System. default: return.out.remove(pos).parseInt(br.println(“LINKED LIST OPERATIONS”).add(“Japan”).out.out.element). System. 4.in)).set(pos.println(“2 Remove element”).add(pos.out. } } Page 96 of 191 . braek.readLine(). System. it returns a negative value. Ex: //Sorting and searching in an array import java.println(“Element found at position: ”+(pos+1)). To compare two arrays. start. System. Accept a string from the keyboard and find its position in the array. to know if they are same or not. Create a stack with a group of strings.println(“Enter element to search: ”).io.out.equal(arr1.binarySearch(arr.binary Search()methodwill act only on a sortedarray. int pos = Array. //Search for an element System.parseInt(br. Create an array with string. //Create in array with size n int arr[ ] = new int[ n ]. 2.W. i<arr. display(arr). Arrays.println(arr[ i ]). if(pos<0) System. class Arr1 { public static void main(String args[ ]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.length. } //Sort the array in ascending order Array.parseInt(br.println(“How many elements? ”).readLine()).binarySearch(arr.Arrays is class.out.util. Note: .println(“Element not found”).sort(arr.sort(arr). element). which contain methods to handle array 1.parseInt(br. To sort only a rangeof elementsof the array Array.readLine()). 26. } static void display(int arr[ ]) for(int i = 0.COREJAVA } Arrays:.out. x). if arr1 and arr2 are same else if returns false. int x = Integer. import java. } } H. 4.in)). This sorts the elements of ‘arr’ starting from ‘start’ till ‘end’ -1 element. Build a linked list of double values. i++) System. To search for element n array Arrays. end). 3. 25. This returns true. arr2).out. Page 97 of 191 .*. else System. This search for ‘element’ in the array ‘arr’ and returns its position.out.println(“The sorted array: ”). int n = Integer. for(int i = 0.println(“Enter Element: ”).out. System.sort(arr). Arr[ i ] = Integer. i<n. To sort the elementsof an arrayinto ascendingorder Arrays.readLine()). i++) { System. 24.*.out. If the ‘element’ is not found. Employee(int i. } void display() { System.In this type of cloning any modifications to the original object will also modify the cloned object. Cloningin java: . String name.display(). name = s.println(“name = ”+name). } Page 98 of 191 . 2. This cloning technology is available now. String s) { id = i.Obtaining bitwise exact copy of an existing object is called as cloning.out. } void display() { System.out. } Employee myClone() throws CloneNotSupportedException { return (Employee)super. } } (or) Ex: //Cloning class Employee implements Cloneable { int id. //Create another obj by cloning Employee e2 = e1. name = s. Deep cloning or copy can be achieved through serialization. a bird. DeepCloning:. System. Employee(int i.println(“id = ” +id).COREJAVA Cloning:. “Sagar”).In this type of modification to original objects will not affect the cloned object.myClone().Cloning is a technology to obtain exact copy of a plant.display().println(“id = ” +id). Shallow Cloning: . This may be fast to code but will have performance implications.out. E2. System.println(“name = ”+name). String name.an animal or a human being. } } class CloneDemo { public static void main(String args[ ]) throws CloneNotSupportedException { //Create an obj naturally Employee e1 = new Employee(10. e1. String s) { id = i. There are two types of cloning 1.out.clone(). Ex: //Cloning class Employee implements Cloneable { int id.  A group of objects are also handled with array.display(). Objects are passed in RMI (Remote Method Invocation) across network using serialization.clone(). A common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database. e2. Collections  A group of elements are handled by representing with an array.  An interface without any methods is called marking interface or tagging interface. e1.COREJAVA public object clone() throws CloneNotSupportedException { return super. for(int i = 0. Object is super class.Object class.util Package Collections class Collections obj Page 99 of 191 .  clone() method is object class.lang. } } Q) Whichmethodis usedin cloning?***** Ans:. Ex: . It specifies or indicates a special purpose for the class objects.By using clone() method of java.Serializable. Do not use serialization if you do not have to.  The interfaces with no defined methods act like markers. “Sagar”). //Create another obj by cloning Employee e2 = (Employee)e1. i<100. i++) { arr[ i ] = new Employee(……).cloneable. The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to achieve scalability.  By writing implements Cloneable the programmer is indicating that class’s objects are cloneable. To store objects in Array Employee arr[ ] = new Employee[100]. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.  Interface Cloneable will not have any methods. } Java. } } class CloneDemo { public static void main(String args[ ]) throws CloneNotSupportedException { //Create an obj naturally Employee e1 = new Employee(10.display().clone(). 9. Collection frame work is defined in java. List is also similar to set.COREJAVA Collectionsobject(or) ContainerObject:. Maps:. 3.Sets of the collection class will not allow the duplicate values. 2.A map stores elements in the form of the keys and value pairs.ArrayList. It will also store elements or objects. Vector. 1. All collection classes have defined in java.  Sorted means iterating through a collection in a natural sorted order.util package. Q) Whatis the differencebetweencollectionand Collections?***** Ans:.It is an object that stores a group other objects. Collections objects stores references of other objects. Ex: . Collections objects will not act upon primitive datatypes.It is a class whose object can store other objects. 7. Sets: . No.Hashmap. 8. Sets will not allow the duplicate values but Lists will duplicate values.util package(or) Collectionframework: S. Q) Whatis collectionsframework?***** Ans:Collections frame work is a class library to handle groups of objects. Set will not stores the object in ordered/sorted order.HashSet.util package. Set List Map SortedSet SortedMap Iterator ListIterator Enumeration Interfaces ArrayList Vector LinedList HashSet TreeSet Collections LinkedHashSet HashMap TreeMap HashTable CollectionClasses Page 100 of 191 . 3. etc… 2. List will stores the object in ordered/sorted order. LinkedHashSet. LinkedList etc… Collection objects Q) Whichof the collectionclasswill not allowduplicatevalues?***** Ans:. Ex: . Collectionsclass(or) Containerclass:. 10.Collection is an interface. Hashtable etc… List of interfacesandclassesin java. 6. This is the difference between Lists and Sets. Ex: . TreeSet. Lists: . Frame work means group of classes. All collection classes are defined into 3 types. (or) collections objects will not store primitive datatypes.A list represents the group of elements or objects.A set represents a group of objects is called as Set. 4. 1. 5. Collections is a class. Lists of the collection class will allow the duplicate values. To covert ArrayList into an array use toArray() method. 2.println(“Array list = ” +arl).remove(2).  Object is the super class of other classes including user defined classes also. class ArrayListDemo { public static void main(String args[ ]) { //Create an ArrayList ArrayList arl = new ArrayList().hasNext()) System.add(2.remove(“Apple”). “Apple”). 5. arl.add(“Apple”). To remove objects use remove() method.iterator(). arl.out. ArrayList arl = new ArrayList(100).println(“Array list = ” +arl).util.COREJAVA 11. To create an ArrayList ArrayList arl = new ArrayList().add(“Grapes”).  When we are retreiveing the elements from ArrayList. //Add elements to arl arl.out. //Remove elements arl. int n = arl. ListIterator 3. Iterator 2. which are useful to retrieve the objects or elements one by one from array list. arl. it will maintains and gives the same order what we have added the elements to the ArrayList. 4. To know number of objects use size() method. arl.sort(al). Banana …are objects arl. It is not synchronized 23.*. Grapes.size()).next()).toArray(). arl.  ArrayList supports sort method by using the below code Collections.out.println(“Size of Array list = ” +arl. They are 1. object x[ ] = arl. while(it. 3.size(). 1. arl.It is dynamically growing array that stores objects. // Apple.add(“Banana”).remove(“Apple”).println(it. LinkedHashMap ArrayList:. Enumeration 23 Synchronized:.add(“Mango”). arl. //al is ArrayList Class object reference. arl. //Display the content of ArrayList (or) in arl System.out. Ex: //ArrayList creation with string objects import java.It means only one process will allow to act on one object. To add objects use add() method. //Use Terator to retrieve elements Iterator it = arl. Guava. Page 101 of 191 . //Find number of elements in arl System.remove(2). //Display the content of ArrayList (or) in arl System.add(“Guava”).  ArrayList doesn’t supports the null values.add(“Apple”). } }  There are three types of interfaces are available. add(2.COREJAVA Whatare the differencebetweenIteratorandListIterator:Iterator 1. Page 102 of 191 . v. previousIndex() and remove() methods. 6. To search for last occurrence of an element use indexOf() method int n = v . 2. To know the current capacity. But it is synchronized. hasNext(). Enumeration doesn’t supports a remove() method. 1. but by using some methods we can synchronized the ArrayList. 2. Access the collections in the forward direction only. if necessary. Iterator supports ArrayList. 3. To retrieve elements use get() method v. to ensure that it can hold at least the number of components specified by the minimum capacity argument. nextElement(). int n = v.Vector. 8. void ensureCapacity(int minCapacity). ListIterator is the sub interface of Iterator super interface.  When we are retreiveing the elements from Vector.add(obj). Enumeration doesn’t ArrayList. Vectors are suitable objects. lastIndexOf(obj).remove(2). LinkedList. 3. 4. 3. Iterator supports only hasNext(). previous(). To create a vector Vector v = new Vector(). next(). It is not synchronized. 4. HashMap. To add elements use add() method. set().clear(). 2.  List myList = Collections. it maintains and gives the same order what we have added the elements to the Vector. 2. Access the collections in forward and backward directions. use size() method. It is synchronized.  ArrayList is not synchronized by default. To remove all elements v.capacity().LinkedList. Enumeration 1. supports like as Vector:. Whatare the differencebetweenIteratorandEnumeration:Iterator 1. 3. Iterator is a super interface ListIterator 1.It is a dynamically growing array that stores objects. To remove elements use remove() method v. HashTable. 5. To search for last occurrence of an element use lastIndexOf() method int n = v . HashMap. It doesn’t supports legacy methods. 7. use capacity() method int n = v. Iterator supports a remove() method. 2.  Vector doesn’t supports the null values. Vector v = new Vector (100). It supports legacy methods hasMoreElements().synchronizedList(myList). v. intdexOf(obj). obj). 4. When the object is synchronized then we will get reliable results or values. 3.  Vector is synchronized default. Increases the capacity of this vector.get(2). nextIndex(). Iterator supports add(). To know the size of Vector. 9. next() and remove() methods. hasPrevious().size(). size(). int n = ht.add(new Integer(x[ i ])).out. 22.println(v. 5.put(“Sachin”.println (“\n In reverse direction: ”). 5. HashTable:. while(lit.out.COREJAVA Ex: //A Vector of int values import java. it is slower than ArrayList due to its synchronized methods. 4.println(“In forward direction: ” ). To remove the key (and its corresponding value) ht. i< v. //In the above statement ListIterator is an Interface. //Retrieve and display the elements for(int i = 0. class VectorDemo { public static void main(String args[ ]) { //Create an empty Vector Vector v = new Vector (). 2. 3. i< x. ArrayList doesn’t supports the legacy methods.lenght(). Vector supports the capacity(). 3.out. It is synchronized.out. nextElement().Hashtable stores object in the form of keys and value pairs. 5. It is efficient than Vector. 100}. 1. load factor = 0. To store key-Value pair the HashTable ht. ArrayList doesn’t supports the capacity(). To know the number of keys in the HashTable.previous() + “\t”).out. System. It is not synchronized. listIterator().get(“Sachin”). Keys must be unique and keys cannot allow duplicate values.size(). Page 103 of 191 . //Initial Capacity = 11. “Cricket Player”). To get the value when is given ht.hasNext()) System. To create a HashTable HashTable ht = new HashTable().next() +“\t”). It is not efficient than ArrayList. 3.previous()) System. 2.get(i)). ArrayList supports only Iterator interface. //Take (an one dimensional) int type array int x [ ] = {10.remove(“Sachin”). Whatare differencesbetweenArrayListandVector:- Maps: . Its default capacity is 10. Vector supports the legacy methods like hasMoreElements().print(lit. 33. Vector supports Iterator and enumeration interfaces. //Retrieve elements using ListIterator ListIterator lit = v.75 HashTable ht = new HashTable(100). 44.print (lit. i++) System. Vector is dynamically growing array that stores objects. 4. 60. due to ArrayList is fast iterartion and fast random access.util. 4. 2. 6.A map represents storage of elements in the form of the key and value pairs.*. listIterator() is a method System. i++) v. while(lit. An ArrayList is dynamically growing array that stores objects. The default capacity of vector is 10. //Read int values from x and store into v for(int i = 0. 6. Vector 1. } } ArrayList 1. It is synchronized. out.println(“Player Name: ”). new Integer(50)).out.println(Name+”Scored runs = ”+runs). ht. new Integer(125)). "Mogili").intValue(). "@Marlabs"). new Integer(86)). System.Load factor determines the point at which the capacity of HashTable or HashMap will be automatically doubled.in)). becomes 22 (11 x 2).readLine().println(“Player not found”).  Page 104 of 191 .e.*. } } Ex 2: import java.println(ht. //Retrieve all keys Enumeration e = ht.e.out. ht. Ex: . Q) Whatis loadfactor?***** Ans:.put("0".clear().get(name). ht. "Babu"). ht. //Find number of runs of this player Integer score = (Integer) ht.get("1")).put(“Ganguly”. After storing 8th pair the capacity of the HashTable will be doubled i. ht. ht. if(score!=null) { int runs = score. While(e.put(“Amarnadh”.println(e. ht. System.out.hasMoreElements()) System.put(“Kapil”. String name = br.in) represents Keyboard System.io. Score // Here Player Name is Key and Score is a Value ht.*.println(“Enter Player Name: ”). System. To clear all the keys. Ex: //HashTable with Cricket Scores import java. ht. } else System.put(“Dhoni”. System.println("---Retreiveing the elements--.out.75) = 8 i.put("1". // In the above statement (System. "Anand"). ht.out.For HashTable initial capacity (11) X load factor (0. new Integer(175)).= "+ht).put("3". public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable().out. import java.*. new Integer(150)).util. //Ask for Player Name from Keyboard BufferedReader br = new BufferedReader(InputStreamReader(System.put(“Sachin”. Initial capacity = 11.keys().COREJAVA 6.nextElement()). this value depends on the version.put("2". class HashtableDemo { public static void main(String args[ ]) throws IOException { //Create an empty hash table HashTable ht = new HashTable().util. //Store Player Name. Hashtable.get("2")).println(ht.util. "Anand"). System.NullPointerException at java. "@Marlabs").out.println(ht. while(e. ht.out. System.keys(). Enumeration e=ht.lang.println("---Retreving the elements using enumeration from HashTable = "+e.main(DemoHashTable. System.get("0")).put(null.out.get("3")).= "+ht).nextElement()).put(Unknown Source) at com.hasMoreElements()){ System. System.get("2")).out. while(e1.DemoHashTable. while(e.COREJAVA System. System.println("---Retreving the keys using enumeration from HashTable = "+e1.*.util. "Mogili"). Enumeration e=ht.nextElement()). ht.vara.out.nextElement()).elements(). public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable().java:7 Page 105 of 191 .put("1".put("3".get("3")).get("1")). System.nextElement()). } Enumeration e1=ht.println(ht.hasMoreElements()){ System.marlabs. 1=Babu.println(ht.out.println("---Retreiveing the elements--.out.hasMoreElements()){ System. System. 2=Anand.out. "Babu"). } } } O/P: ---Retreiveing the elements--. (or) ht. } } } O/P: Exception in thread "main" java. } Enumeration e1=ht.out. null).println("---Retreving the keys using enumeration from HashTable = "+e1. ht.out. 0=@Marlabs} Babu Anand Mogili @Marlabs ---Retreving the elements using enumeration from HashTable = Mogili ---Retreving the elements using enumeration from HashTable = Anand ---Retreving the elements using enumeration from HashTable = Babu ---Retreving the elements using enumeration from HashTable = @Marlabs ---Retreving the keys using enumeration from HashTable = 3 ---Retreving the keys using enumeration from HashTable = 2 ---Retreving the keys using enumeration from HashTable = 1 ---Retreving the keys using enumeration from HashTable = 0 Ex 3: import java.hasMoreElements()){ System.println("---Retreving the elements using enumeration from HashTable = "+e.get("0")). ht.out. while(e1.elements().put(“2”.= {3=Mogili.println(ht.out.put("0".keys().println(ht.println(ht. int n = Integer. IO stands for input/output. System.println(“3 Exit”).remove(“Sachin”). To store key-Value pair the HashMap hm. 1.util. 2. To create a HashMap HashMap hm = new HashMap().readLine().clear(). To get the value when is given hm. ”).out. perform a task switch(n) { case 1: System. To know the number of key-value pairs in the HashMap.*.println(“1 Enter entries into Phone Book”). not even the same order that we have added keys and elements. 3. hm. load factor = 0.out. “Cricket Player”). import java. System.io. //Menu while(true) //It is an infinite loop { System.readLine()). BufferedReader br = new BufferedReader(InputStreamReader(System. //Convert str into Long obj phno = new Long(str). 4. str = br.size(). It is not synchronized.in)).  In HashMap duplicate keys are not allowed but duplicate values are allowed. 6. int n = hm.  Map myMap = Collections. Long phno. 5.75 HashMap hm = new HashMap(101). To clear all the keys.  In HashTable duplicate keys are not allowed but duplicate values are allowed. HashMap:. str.put(“Sachin”.  IOException may caused by readLine() method. class Tele { public static void main(String args[ ]) throws IOException { //Vars HashMap hm = new HashMap().out.HashMap stores objects in the form of keys and value pairs.parseInt(br.readLine(). //Depending on n value. Name = br.println(“2 Lookup for a Phone Number”). String name.synchronizedMap(myMap).print(“Enter Phone No. To remove the key (and its corresponding value) hm. Page 106 of 191 . Ex: //Telephone entry book import java. //Initial Capacity = 16.print(“Enter Person Name: ”).  Playernames are all keys and scores are all values.*.out.out.  When we retreving the elements or keys using HashTable it will gives the elements or keys in revrse order only. System.  HashMap is similar to HashTable but the difference between these two is HashTable is synchronized but HashMap is not synchronized  When we retreving the elements or keys using HashMap it will gives the elements or keys irregular order.COREJAVA  Enumeration will not maintain objects in the same order.get(“Sachin”). next()).put(null.out. phno = (Long)hm. case 2: System.println("---HasMap size---"+hm. name = br. System.println("---HasMap initial size---"+hm. System. Page 107 of 191 .keySet(). 4=bujji. public class DemoHashmap { public static void main(String args[]){ HashMap hm=new HashMap().get("1")). 2=anji. System.put("4". "anand").get(name). default: return.println(“Phone No: ”+phno).util.hasNext()) System. phone in hm break.print(“Enter Person Name”).get("4")). hm. null). break.out.out. "bujji"). "anji").out. hm. System. System. public class DemoHashmap { public static void main(String args[]){ HashMap hm=new HashMap(). hm. Iterator it=s. hm.out.*.println(hm. "Vara").size()).*.size()).util.get("2")). System.put("1". System. hm. } } O/P: ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{3=anand.println(hm. "Vara").println(hm. while(it.out.println("---Retrieving the elements HasMap---"+hm).println("Retreiveing the Keys = "+it.put("2". hm.out.COREJAVA //Store name. System.put("1".out.put("3".println("---HasMap initial size---"+hm. 1=Vara} bujji Vara anand anji Retreiveing the Keys = 3 Retreiveing the Keys = 2 Retreiveing the Keys = 4 Retreiveing the Keys = 1 Ex 2: import java.out.println(hm.put("3". hm.out.out.iterator().get("3")).size()).readLine(). Set s=hm. System. null). //Pass name to hm and get the Phone No. } } } } Ex 1: import java. 7.COREJAVA hm.next()). (or) StringTokenizer st = new StringTokenizer(str.out.put("4". 6. To know how many number of pieces are there.The StringTokenizer class is useful to break a string into small pieces. HashTable initial capacity is 11 and the capacity of HashTable depends on version of Java. Here . It stores the objects in the form of key and value pairs.out. HashTable 1. } } O/P: ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{null=null.println("---Retrieving the elements HasMap---"+hm). System. It is not efficient than HashMap due to its synchronized methods. HashTable maintained the orderd of elements in reverse.println("---HasMap size---"+hm.out. "bujji"). 3=null.keySet(). 3.size()).hasMoreTokens(). To know if more pieces are remaining.println("Retreiveing the Keys = "+it.out. 3. 1. System. 1=Vara} bujji Vara null null Retreiveing the Keys = null Retreiveing the Keys = 3 Retreiveing the Keys = 4 Retreiveing the Keys = 1 Whatare differencesbetweenHashMapand HashTable:HashMap 1. 8. “. HashMap initial capacity is 16 and the capacity of HashMap depends on version of Java.hasNext()) System. 8.out.println(hm. 4. HashTable doesn’t takes null keys and null values. HapMap takes only one null key and many null values. 5. It stores the objects in the form of key and value pairs. 2. nextElement(). 4=bujji. To find the next piece in the string. System. 5. 3.  Page 108 of 191 . StringTokenizer:. System. called tokens.out. “delimiter”). 7. while(it. Set s=hm.get("1")). (or) StringTokenizer st = new StringTokenizer(str. It supports legacy methods hasMoreElement(). 2. HashTable supports Iterator and enumeration interfaces. It supports only Iterator interface.get("3")).iterator().println(hm. 4. It will makes fastest updates (key/value pairs) so it is efficient than HashTable. 4. :”). It is not synchronized. Iterator it=s. int no = st.”). not even the keys and the elements added to it.get("4")). booleab x = st. System.countTokens().out. like 6. To create an object to StringTokenizer StringTokenizer st = new StringTokenizer(str.get("2")).println(hm. It doesn’t supports legacy methods. System.println(hm. String piece = st.nextToken(). HashMap doesn’t maintained the orderd of elements. : are called as delimiters 2. “. It is synchronized. class STDemo { public static void main(String args[ ]) { //Take a string String str = “It is our capital city called New Delhi”. 2. Ex: //Cutting the string into pieces import java.println(“The token are: ”).out.This class is useful to handle. is our: capital city. } } } Form Name Address Server Section Name Ok Calendar:.util. while(st. “ ”).hasMoreTokens()) { String s1 = st. //brake the string into species StringTokenizer st = new StringTokenizer(str.nextToken(). //brake the string into species StringTokenizer st = new StringTokenizer(str. Page 109 of 191 .out. : ”).get(constant).hasMoreTokens()) { String s1 = st. date & time. } } } (or) //Cutting the string into pieces import java. while(st. System.COREJAVA  Token means piece of string.out. This method returns an integer. cl.*. “. //retrieve the pieces and display System.out. class STDemo { public static void main(String args[ ]) { //Take a string String str = “It.util. To create an object to calendar class: Calendar cl = Calendar.nextToken().getInstance().println(“The token are: ”). called New: Delhi”. Use get() method to retrieve date or time from calendar object. System. //retrieve the pieces and display System.println(s1).println(s1).*. 1. out.getDateInstance(formatconst. ++mm. This method returns a string.*. } } Date Class:.hasMoreTokens(). formatconst region).get(Calendar.30 DateFormat.get(Calendar.LONG 03/09/04 7. //retrieve time details int h = cl.DateFormat fmt = DateFormat. To create an object to Date class. 2.Medium.println(“dd+ “/” +mm+ “/” +yy).getDateInstance(formatconst. System.SHORT.MINUTE). Ex: .getInstance(). //retrieve date details int dd = cl.MEDIUM 03-Sep-04 19:43:14 DateFormat.YEAR Calendar.get(Calendar. Note: ---------------------------------------------------------------------------------------------------------------formatconst Example(region= LocaleUK) ---------------------------------------------------------------------------------------------------------------DateFormat. Ex: //System date and time import java.out. Format the date and times using getDateInstance() or getDateTimeInstance() methods of DateFormat class.get(Calendar. int mm = cl.MONTH Calendar.out.YEAR).println(“System time: ”).US).println(“System date: ”).MINUTE Calendar.Medium.SECOND).10).toString(). class Cal { public static void main(String args[ ]) { //Create an obj to calendar class Calendar cl = Calendar.MONTH. Locale.DATE Calendar. Gregorian calendar is another type class like as calendar class.LONG 03 September 2004 19:43:14 GMT + 5. System.println(h+ “:” +m+ “:” +s)). System. Ex:-DateFormat fmt=DateFormat.COREJAVA Note: Constants:Calendar.set(calendar. System.HOUR Calendar.UK). cl. Syntax:. //Default counting of January month starts with 0 booleab x = st.FULL 03 September 2004 19:43:14 oclock GMT + 5. Date d = new Date(). region).get(Calendar. 1.util. Locale. Syntax:. int yy = cl.getDateInstance(DateFormat.HOUR). To convert a date into string.out. Use set() to get the date or time in the calendar object.43 pm ---------------------------------------------------------------------------------------------------------------Page 110 of 191 .MONTH).getDateInstance(DateFormat. cl. int s = cl. int m = cl.DateFormat fmt = DateFormat.30 DateFormat.txt package.DATE). DateFormat.Date class is class useful to handle date and time. 4. This is in java. use toString(). Here region is the place/the country.get(Calendar.DateFormat fmt = DateFormat.SECOND 3. out.e. It will have more methods than Observer interface. display his name and address. Object arg). France=>Paris” Now display the token as given below. class MyDate { public static void main(String args[ ]) { //Create an obj to Date class Date d = new Date().It receives or reads the data to output stream. Input Streams:.println(“System date and time: ”+s). Create an Employee class with an employee’s id. Display them in reverse order also? 3. DateFormat. OutputStream:. When the bytes passing then it is called as byte stream and when the characters are passing then it is called as character stream. } } Here d represents the system date & time already consists after creating an object. An Observer is an interface. Locale. and arg is the value passed by notifyObservers(). or characters traveling from source to a destination. America=>Washington.format(d).util. Create HashTable with some students hall tickets no.getDateTimeInstance(DateFormat.A stream is a sequence of bytes. To handle data in the form of ‘bytes’. import java. The update() method is called when a change in the observed object take place. When an employee’s ID is given. Here observOb is the object being observed. String str = fmtt.SHORT. Streams (java. Observing classes must implement the Observer interface. 1. Stream: .W. Cut the string into pairs of pieces: “India=>Delhi. Britain=>London.*. 1. Observing classes are notified. H. Create a vector with a group of strings. and address store objects of this class in an ArrayList.UK). //Store the format in DateFormat obj DateFormat fmt = DateFormat.  Streams are represented by classes in java. Ex: //To display system date and time import java. InputStream | Page 111 of 191  . and must implement the observer interface. City Capital Delhi India Washington America London Britain Paris France Q) Whatis the differencebetweenObservableandObserver?***** Ans:. Applying format to Date object is done by format () method.*.text.io package. name.MEDIUM. This interface will defines only one method i.A stream represents flow of data from one place to another place. void update(Observable observOb. which is useful to observe an observable object. 2. the abstract class: InputStream and OutputStream are used. When an object of such a subclass undergoes a change.Observable is a class is used to create subclasses that other parts of our program can observe.It sends or writes the data to some other place. //Display the formatted date and time System. 2.COREJAVA 3. Sort them and display them in a ascending order. They are two types of streams.format(d). //Applying the format to d String s = fmt.io): .’s & their results. Type a hall ticket number and display his result? 4. I/O efficiency should be a high priority for developers looking to optimally increase performance.Handles character (text) by buffering them. They provide efficiency.They handle storage of objects and primitive data. Reader reads bytes and then decode them into 16-bit Unicode character. Reader | ----------------------------------------------------------------------------------------------| | | | BufferedReader CharArrayReader IntputStreamReader PrintReader | FileReader Writer | ----------------------------------------------------------------------------------------------| | | | BufferedWriter CharArrayWriter IntputStreamWriter PrintWriter | FileWriter  ByteStream stores the data in the form of bytes. c) ObjectInputStream/ObjectOutputStream:. write decodes character into bytes and then write. The basic rules for speeding up I/O performance are: ? Minimise accessing the hard disk.They are bridge between byte streams and character streams. CharacterStream stores the data in the form of characters. b) CharArrayReader/CharArrayWriter:.Handles array of characters. Page 112 of 191 . This means substantial gains can be had from I/O performance tuning. d) PrinterReader/PrinterWriter:.  A file is an organized collection of data. b) FilterInputStream/FilterOutputStream:. Therefore.  Retrieving the data from files is called de-serialization. c) InputStreamReader/OutputStreamWriter: .Handle printing of characters on the screen. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations.They read data from one stream and write it another stream.  Buffered means a block of memory.  Storing objects in a file called serialization. HowcanyouimproveJavaI/O performance: Java applications that utilise Input/Output are excellent candidates for performance tuning.They handle data to be read or written to disk files. a) Buffered Reader/Buffered Writer: .COREJAVA | FileInputStream ---------------------------------------------------------------------| | FilterInputStream ObjectInputStream | ----------------------------------------| | BufferedInputStream DataInputStream OutputStream | ----------------------------------------------------------------------| | | FileOutputStream FilterOutputStream ObjectOutputStream | ----------------------------------------| | BufferedOutputStream DataOutputStream a) FileInputStream/FileOutputStream:. the above code with buffering can be improved further by reading one line at a time as shown below: FileReader fr = new FileReader(f). Instead of reading a character or a byte at a time. The line buffering can be disabled for faster I/O operation as follows: FileOutputStream fos = new FileOutputStream(file). BufferedInputStream bis = new BufferedInputStream(fis). } } //bis should be closed in a finally block. BufferedReader br = new BufferedReader(fr). System. while((b = fis.close() .COREJAVA ? Minimise accessing the underlying operating system. } catch(IOException io){} Note: bis. WithBuffering:yieldsbetter performance try{ File f = new File("myFile. } } // fis should be closed in a finally block. bis. We can store the data permanently into the hard disk. (When we are strong the data in HashTable. BufferedOutputStream bos = new BufferedOutputStream(fos.read() takes the next byte from the input buffer and only rarely access the underlying operating system. FileInputStream fis = new FileInputStream(f). int b = . Let us look at some of the techniques to improve I/O performance. This is required for any interactivity between an input prompt and display of output. int b = .txt"). } catch(IOException io){} Note: fis. fis. int count = 0. ? Use bufferingto minimise disk access and underlying operating system.read()) != -1){ if(b== '\n') { count++. 1024). PrintStream ps = new PrintStream(bos.out. with buffering large chunks of a file are read from a disk and then accessed a byte or character at a time. As shown below. which means that the output buffer is flushed when a new line character is encountered. while (someConditionIsTrue) System. while((b = bis. Withoutbuffering: inefficient code try{ File f = new File("myFile. By default the System. Page 113 of 191 . vector etc… the data will store temporarily on the RAM). While (br. FileInputStream fis = new FileInputStream(f).out is line buffered.false).readLine() != null) count++.setOut(ps). } Usesof files: 1.txt").println(“blah…blah…”). ? Minimise processing bytes and characters individually. int count = 0.read() ) != -1){ if(b== '\n') { count++.close() .read() is a native method call to the underlying system. //reading data from DataInputStream and write that data into FileOutputStream char ch.out will displays normal messages on the monitor.io.out – PrintSream obj – Monitor System. Every time executing & running the program old data will be remove/overwrite and new data will stored. DataInputStream FillOutputStrea m System. in is a field.in). Q) Whatis use of Stream?***** Ans:.in –it is a InputStream object Here System is a class java.out. FileOutputStream fout = new FileOutputStream(“myfile”.println(“Enter data (@at end): ”). The achieving the hardware independent of java programs we are using stream. System.e. we can also open file using command “type” (i. The above two are main advantages of file. System. //close the file fout. while((ch = char) dis. System.in – InputStream obj – Keyboard System.io.COREJAVA 2.read()) != ‘@’) fout.err will displays error messages on the monitor. System. class Create1 { public static void main(String args[ ]) throws IOException { Page 114 of 191 .*.in Ex: - myfile //Creating a file import java. Once we stored the data in the form of file we can share that data in different programs. a MsDos Command). true). Ex: //Creating a file import java. package.write(ch).Stream will handle input/output devices.err – PrintSream obj – Monitor System. //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”). To overcome this problem or to appending the data we have to use ‘true’ in the following statement.close().*. class Create1 { public static void main(String args[ ]) throws IOException { //Attach the keyboard to DataInputStream DataInputStream dis = new DataInputStream(System. } } After executing & running the program.io. //now read from FileInputStream and display int ch.println((char)ch). System.close(). while((ch = fin.out.write(). BufferedOutputStream bos = new BufferedOutputStream(fout. //reading data from DataInputStream and write that data into FileOutputStream char ch.io. //close the file fin. //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”.out. 1024).  Default size used by any Buffered class is 512 bytes.*.read()) != ‘@’) fout.*. true). class Read1 { public static void main(String args[ ]) throws IOException { //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(“myfile”). and in the place of fout.close().out.write(ch).io.close(). true). System.read()) != ‘@’) bos.println(“Enter data (@at end): ”).println(“Enter data (@at end): ”).close().io. we have to use bos. class Create1 { public static void main(String args[ ]) throws IOException { //Attach the keyboard to DataInputStream DataInputStream dis = new DataInputStream(System. BufferedOutputStream bos = new BufferedOutputStream(fout. } } To improve the efficiency or the speed of execution of program we to use Buffered class. } } Ex: //Reading data from a text file import java.read()) != -1) System. //close the file fout. while((ch = char) dis. //reading data from DataInputStream and write that data into FileOutputStream char ch. //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”. //close the file bos. 1024). we have to use bos. while((ch = char) dis. } } Ex: //Reading data from a text file import java. Page 115 of 191 .in).in). In the place of fout.write(ch).close().COREJAVA //Attach the keyboard to DataInputStream DataInputStream dis = new DataInputStream(System.write().*. Ex: //Creating a file import java. io.close(). } } Ex: //Creating a file import java. System.txt”).println(“File not found”). //now read from FileInputStream and display int ch. String fname = readLine().read()) != -1) System.print(“Enter file name: ”). while((ch = bin.in)). //read char by char from str and write into fw for(int i = 0. class Read1 { public static void main(String args[ ]) throws IOException { try{ //to enter filename from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.charAt(i)). //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(fname). //close the file bin. //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(“myfile”).read()) != -1) System.*.io.ot. } catch(FileNotFoundException fe) { System.COREJAVA class Read1 { public static void main(String args[ ]) throws IOException { BufferedInputStream bin = new BufferedInputStream(fin).println((char)ch). //close the file fw. //take string String str = “This is an institute” + “\nIam a student here”.println((char)ch).out. Page 116 of 191 . while((ch = bin. //close the file bin.close().out. class Create2 { public static void main(String args[ ]) throws IOException { //to write data into file FileWriter fw = new FileWriter(“myfile1. } } Ex: //Reading data from a text file import java.*.out.write(str.close(). i<str.length(). //now read from FileInputStream and display int ch. i++) fw. class Create3 { public static void main(String args[ ]) throws IOException { //to write data into file FileWriter fw = new FileWriter(“myfile1.txt”).txt”).println((char)ch). class Read3 { public static void main(String args[ ]) throws IOException { //attach file to FileReader FileReader fr = new FileReader(“myfile1. i++) bw.io. while((ch = br. class Read2 { public static void main(String args[ ]) throws IOException { //attach file to FileReader FileReader fr = new FileReader(“myfile1.close().close().ot. BufferedReader br = new BufferedReader(fr. } } //Reading data from the file import java. //now read data from fr and dispaly int ch. while((ch = fr. //now read data from fr and dispaly int ch.close().write(str.COREJAVA } } //Creating a file import java.io. } } 1001 Rama 7000. //read char by char from str and write into fw for(int i = 0.*. } } //Creating a file import java. //close the file fr.*.println((char)ch).charAt(i)). 1024). 512).length(). //close the file br.05 Ex: - Ex: - Ex: - Page 117 of 191 . i<str. BufferedWriter bw = new BufferedWriter(fw.read()) != -1) System.read()) != -1) System.*.ot.io. //close the file bw. //take string String str = “This is an institute” + “\nIam a student here”.txt”). 2.zip. //attach fos to DeflaterOutputStream DeflaterOutputStream dos = new DeflaterOutputStream(fos). //read data from fis and write into dos int data.util. dos import java. dos import java. } } Here we have to create file1 using Ms-Dos Edit command save it and then execute the java file.*. //attach file2 to FileOutputStream FileOutputStream fos = new FileOutputStream(“file2”).*.It is used to zip the file. File format is changed.It is used to unzip the file.zip packagae. dos. //attach file3 to FileOutputStream FileOutputStream fos = new FileOutputStream(“file3”).read()) != -1) dos. In java language to zip and unzip a file we will use below two classes.util. Writing Writing class Compress here here { public static void main(String args) File 2 File 1 throws Exception { attach fos attach fos //attach file1 to FileInputStream FileInputStream fis = new FileInputStream(“file1”).*.util. //close the files fis.close(). while((data = fis.close(). 2. DeflaterOutputStream: . These above two classes are in java.zip. ZippingandUnzippingthe file: - Most repeated bit pattern 11111111 00000000 10101010 00001111 File WinZip Software Zip 0 1 01 101 Zipped file 1. File converts to compressed.util.util. 1.COREJAVA EMPID EMPNAME EMPSAL ObjectStream  JDBC is more convenience to handle or storing and retrieve the data from the table form.write(data). InflaterOutputStream: . Ex: //UnZip import java. Writing Writing class UnCompress here here iis { File 2 File 3 public static void main(String args) throws Exception { attach fis attach fos //attach file2 to FileInputStream FileInputStream fis = new FileInputStream(“file2”).*. Page 118 of 191 . Ex: //Zipping import java. Ex: 192. Copy a file content into another file (new file) 6. fos.50.  SMTP (Short Mail Transfer Protocol) is used for sending mails. //close the files iis. Count the no.com  DNS – Domain Naming System. } } H. words. Socket: .close(). 7. //read data from iis and write into fos int data.A socket is a point of connection to connect a client and server. 5.It is a IP address of server. Tomcat.50. Ex: .45. Class A 0 Network 7bits Local Address 24bits 16.  POP (Post Office Protocol) is used to receiving mails. An ID number is allotted to a socket is called Port number. Web Sphere. which uses 16 bytes.Apache.  Internet protocol address is a Unique ID number is given to every computer in network.536 Hosts Class C 110 Network 21bits Local Address 8bits 256 Hosts Class D Class E Research/Experimental works  Classes are of IP address. and lines in a text file.TCP/IP – Transmission Control Protocol/Internet Protocol  HTTP is most widely used protocol on internet.01 ----.yahoo.  Server is a machine that provides service to the clients.  The software which is available on the server is called Web Server. etc…  Protocol represented by a set of rules. Client Server Socket Q) Whenyouwill changesocketnumber?***** Page 119 of 191 .01 --------- is a equal to like www.close(). while((data = iis. 192.  The current version of IP address is 6. Web Logic.  Host means Server.write().read()) != -1) fos.  ISP – Internet Service Provider. that is Port No. Ex: .  A client is a machine that sends a request for some service. Every socket has an ID No.216 Hosts Class B 10 Network 14bits Local Address 16bits 65. Append the contents of one file to another file existing file. Network: Inter connections of computers is called Network.COREJAVA //attach fis to InflaterInputStream (iis) InflaterInputStream iis = new InflaterInputStream (fis).45. to be followed by every computer in network. of characters.  FTP (File Transfer Protocol) is used when we are downloading files. W. It will convert the name into the IP address.  Internet is a network of all the computers existing on the earth.777. out. ps. then we have to create socket for client side. [ To display IP address we have to use command igcong Syntax: -C:\rnr>ipconfig↵ ] Ex: //A Client that receives data import java. On the same socket if the service changes.accept(). this enables users to access mail boxes on remote system. import java. ServerSocket is a class to create a Socket server side.     Ex: Port Number 13 21 23 25 67 80 109 Date and time services. class Client1 { public static void main(String args) Page 120 of 191 .*. //Disconnect the Server s. ps. import java.io.println(“Connection Established”).println(“Bye”). which provides configuration at boot time.*. which transfer files. 7. //now send data String str = “Hello”.net.println(str).close(). 1. class Server Server { public static void main(String args) Socket throws Exception { //Create Server Socket Client ServerSocket ss= new Socket ServerSocket(777).net. HTTP. Socket is a class to create a Socket client side. //Create a server that sends messages import java. BOOTP. //attach OutputStream to Socket OutputStream obj = s. 2. Telnet. //to send data to the Socket PrintStream ps = new PrintStream(obj). ps. 6. 4. System.close(). Someallottedport numbers:S.net package. //make that Socket accepts Client connection Socket s = ss. 3. Application java.getOutputStream(). 5. When we use new socket we use a new port number. No.io. } } Now compile this program and don’t run it.*.COREJAVA Ans: 1. which transfer webpage POP. FTP. SMTP. 2. which provides remote login. which delivers mail messages.*. These two classes are in java.net package contains classes to create a socket for server and client. accept(). 2. 777). 6. 2. Read data coming from the Server using BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(obj). Read data coming from the Client using BufferedReader. 5.println(str). Send data to the Server using DataOutputStream. Create a Client Socket Socket s= new Socket(ipaddress/”loacalhost”. s. connect the OutputStream to the Socket OutputStream obj = s.close(). Communicatingfro Server:1. CommunicatingfromClient: 1. Dos. ------ It returns Socket object.COREJAVA throws Exception { //Create Client Socket Socket s= new Socket(ipaddress/”loacalhost”. Create a ServerSocket ServerSocket ss = new ServerSocket(Port No. connect InputStream to the Socket InputStream obj = s. //Disconnect the Server s.read(). 3. br. BufferedReader br = new BufferedReader(new InputStreamReader(obj). Ex: DataOutputStream dos = new DataOutputStream(obj). 3. ClosingCommunication:Close all Streams and Sockets ps.).getInputStream().readLine()) !=null) System. str = br. ps. dos.close(). 4.close().writebyte(str). ps. } }  We can run as many JVM’s at a time. 777). 5.getInputStream().close(). To send data connect the OutputStream to the Socket OutputStream obj = s.close(). To send data.readLine().println(str). str = br. 4.close(). ch = br. Send data to the Client using PrintStream Ex: PrintStream ps = new PrintStream(obj). while(str=br. //Accept data coming from Server String str. Accept any Client Socket s = ss. br. ss.out.read().getOutputStream(). connect InputStream to the Socket InputStream obj = s.getOutputStream().close(). ch = br. 3. Page 121 of 191 .print(str).readLine(). To receive data from the Client.  RMI (Remote Method Invocation) It is a technology to call and use remote methods of remote objects.getInputStream(). To receive data fro the Server. //To receive the data to this Socket BufferedReader br = new BufferedReader(new InputStreamReader(obj)). //attach InputStream to Socket InputStream obj = s. COREJAVA Ex: //Chat Server import java. } } } Ex: //Chat Client import java.io.close(). import java. str1 = kb. str1. kb. br.io. while(str = br. System.getOutputStream()).accept().in())).println(“Connection Established”). System.readLine().println(str).*.out. while(str = br.println(str1).in())).close(). //to receive data from Client BufferedReader br = new BufferedReader(newInputStreamReader (s. ps. } //Disconnect the Server ss. str1. //to send data to the Client PrintStream ps = new PrintStream(s.exit(0). //now start communicate String str.equals(“exit”)) Page 122 of 191 Object .getInputStream())). class Client2 { public static void main(String args) throws Exception { //Create Client Socket Socket s= new Socket(“Localhost”. //to read data from Keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System. ps.getInputStream())).getOutputStream()). class Server2 { public static void main(String args) throws Exception { //Create Server Socket ServerSocket ss= new ServerSocket(888). //now communicate while(true) // Server runs continuously { String str.readLine() != null) { System. //to receive data from Server BufferedReader br=new BufferedReader(new InputStream(s. s. Reference //make this Socket wait for Client connection Socket s = ss.close(). 888).net.*.*.net.out. //to send data to the Server DataOutputStream dos = new DataOutputStream(s.close().close(). //to read data from Keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System. import java.*.readLine() . Multi Threading Thread: . W.  JVM will execute statements step by step. { dos.close(). System. 8.out. dos. In a Single tasking lot of processor Task time wasted.out.Executing one task at a time is called single tasking. Write client server programs so that the client sends the name of a file to the server and the server sends the file content to client display the file contents at client side (the file should present in the server).out. System.readLine(). 5 ------- Normal Priority Priority No.This is first line Present Thread = Thread[main.java↵ C:\rnr>java Current ↵ O/P: . main] is called as Thread group. Priority No.13) 9. Priority number will varies from 1 to 10.  Every java program is executed by using one thread i.  Executing the tasks (one or more statements is two types. 5. 5 is the Priority Number.println(“Present thread = ”+t). kb.println(“This is first line”). str1 = br. 10 ------- Maximum Priority  Main thread priority number is 5. From the above thread name is main.e. System.currentThread(). } } C:\rnr>javac Current. //Every java program has a thread ---------class Current ---------JVM { ---------or public static void main(String args) Microprocessor { Statements System. Microprocessor Ex: - Page 123 of 191 .A thread represents a process of execution (or) executing the set of statements is called a thread. } } H.close(). 5.getName()). Singletasking:. 1. Microprocessor will execute the 10billions of machine code instructions per second.close().writeBytes(str+”\n”). is called main thread. main] Here main is a thread name.println(str1). } //Disconnect the Server s. Thread t = Thread.out. Thread has priority number.COREJAVA //As long as the String are not typing exit. 1 ------- Minimum Priority Priority No.close().println(“Its name = ”+t. br.  We can provide more threads to the microprocessor. Develop a server that sends to system data and time to the client display that data and time at client side (Hint: Use Port No. [main. Create an object to the class.Microprocessor uses round robin method to execute several tasks simultaneously. Microprocessor Memory Task 0.lang package. Thread class. Write a class that extends thread class or implements runnable interface. diff. Multitasking:.Time slice is the time allotted by the Microprocessor to execute each task.println(i). Using more than one thread is called types multithreading to perform multiple tasks of simultaneously at a time. } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(). 5. These two are available in java. then will act upon that object. 2.25ms 0. public void run() Thread can’t act upon any method.25ms 0.Executing several tasks simultaneously is called multitasking. Attach a thread to this object.Executing several programs at a time is called process based multitasking. RoundRobinMethod:. but default it works only on run() method.Executing several Three parts of a program simultaneously is called Microprocessor thread based multitasking. a) Processbasedmultitasking:.out.25milli seconds) for each task.25ms Microprocessor will allot equal timings (0. Ex: //Creating thread Class MyThread extend Thread { public void run() { for(int i = 1. Ex: . b) Thread based multitasking: . Round robin methods are process based multitasking. 2. i<100000. i++) { System. 4.COREJAVA TimeSlice: . Executing first task after last task is called round robin method. Time slice.Robin is a bird which will comes down by making rounds and it will jump up by making rounds that’s why they have compared the microprocessor like that above. Start thread. 3. blocks Createa thread:1. Page 124 of 191 . runnable implements will helpful to create a thread. Write public void run in the class thread will execute only this method.25ms 0.  To stop the thread also we have to use control + c keys.*. 2. MyThread(String str) { this. Q) Whatis the differencebetweenextendsand implementRunnable?Whichone is advantage?***** Ans:There is no difference between these two.COREJAVA Thread t1 = new Thread(). Thread t1 = new Thread().start().1.out. If the variable becomes true using return statement come out run() method Ex: if(stop) return. Implement Runnable is advantage because interfaces is always better than classes. there is no scope any another class. object } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(). i++) Microprocessor } { System. When ever the thread should be stopped store true into this variable Ex: obj. Class MyThread extend Thread { run() boolean stop = false. } }  stop() method is used to stop the thread in old versions.  The main advantage of multitasking is utilizing a processor time in an optimum way. obj.start(). i<100000. System. But stop() method is deprecated in new versions. t1. this is the limitation of extends.stop = true.str = str. Ex: //Creating thread and smoothly terminate/stop the program or thread Import java. } Page 125 of 191 .  Forcibly to terminate the program we have to use “control + c” (Ctrl+c keys in the keyboard). if(stop) return. If we extend thread class. t1. If we implement Runnable interface still there is a scope to extend other class. Declare a boolean variable and initialize it as false Ex: boolean stop = false.io.in.read().println(i). Ex: //Theatre Example class MyThread implements Runnable { String str.stop = true. { public void run() ----{ ----for(int i = 1. 3. } } This above program is for stopping the thread smoothly. Q) Howcanyoustopthe threadwhichis running?***** Ans:. try{ Thread. //start the thread } t1.start(). available = available – wanted. Ex: //Two threads acting on one object class Reserve implements Runnable { int available = 1. } } } run() { --------} object run() Microprocessor } { class Theatre ----{ ----t1 thread public static void main(String args[ ]) } { //create objects to MyThread class Microprocessor object 1 MyThread obj1=new MyThread(“Cut ticket”). try{ Thread.println(“Number of berths available = ”+available).out. object 2 t2.start().println(“Sorry.sleep(2000). System. if(available >= wanted) { String name = Thread. } public void run() { System. } catch(Interrupted Exception ie){ } } else System.sleep(2000). MyThread obj2=new MyThread(“Show ticket”). } Page 126 of 191 .out.printStackTrace(). }catch(InterruptedException ie) { ie. i++) { System. int wanted. run() //Create two threads and attach them to t2 thread { //these two objects ----Thread t1 = new Thread(obj1). no berths to reserve”).COREJAVA public void run() { for(int i = 1.out. ----Thread t2 = new Thread(obj2).getName().out. } }  When multiple threads are acting on the one or same object we will get sometimes unreliable results. Reserve (int i) { wanted = i.println(wanted + “berths reserved for”+name).currentThread.println(str+ “ : ” +i). i<=10. 2nd thread st int wanted.getName(). //create 2 threads and attach them to obj Thread t1 = new Thread(obj). For this permanent solution we have to block the 2nd thread till the completion of the 1st thread. try{ Thread.println(wanted + “berths reserved for”+name). } } } class Syn { public static void main(String args[ ]) { //create an obj to Reserve class with 1 berth Reserve obj = new Reserve(1). //run the threads t1.start(). t2.COREJAVA } class Syn { public static void main(String args[ ]) { //create an obj to Reserve class with 1 berth Reserve obj = new Reserve(1).println(“Number of berths available = ”+available).setName(“Second Person”). So we have to use synchronization method to block the 2nd thread. Ex: //Two threads acting on one object class Reserve implements Runnable { int available = 1. no berths to reserve”). ------------------} public void run() ------------------synchronized(obj) ------------------{ System. Thread t2 = new Thread(obj). 1 thread Reserve (int i) { wanted = i. } catch(Interrupted Exception ie){ } } else System. Thread t2 = new Thread(obj). if(available >= wanted) ------------------object { ------------------Synchronization String name = Thread.out. //give names to threads t1.currentThread. t2. available = available – wanted. //create 2 threads and attach them to obj Thread t1 = new Thread(obj).out.start(). } } This above program will allot tickets for both persons.println(“Sorry.out.setName(“First Person”). Page 127 of 191 .sleep(2000). -System. COREJAVA //give names to threads t1.setName(“First Person”); t2.setName(“Second Person”); //run the threads t1.start(); t2.start(); } } ThreadSynchronization(or) Synchronization: - Synchronization is locking the object, so that when a thread is processing object any other thread will not be allowed to act upon the object. Synchronized object is also called as Mutex i.e. Mutually Exclusive lock. An object can be synchronized in two ways 1. Synchronizedblock(): synchronized(obj) { For group of statements we can use this synchronized statements; block. } Ex: - class BlockLevel{ //shared among threads SharedResource x, y ; //dummy objects for locking Object xLock = new Object(), yLock = new Object(); pubic void method1() { synchronized(xLock){ //access x here. thread safe } //do something here but don't use SharedResource x, y ; synchronized(xLock){ synchronized(yLock){ //access x,y here. thread safe } } //do something here but don't use SharedResource x, y ; } } 2. By making a method as synchronized method synchronized void method() { For entire method to synchronized we will use statements; this method. } Ex: class MethodLevel{ //shared among threads SharedResource x, y ; pubic void synchronized method1() { //multiple threads can't access } pubic void synchronized method2() { //multiple threads can't access } public void method3() { //not synchronized //multiple threads can access } } Page 128 of 191 COREJAVA Synchronizationimportant: - Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. Disadvantageof synchronizationis that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely the performance.  Synchronization is also known as thread safe, unsynchronized is also known as thread unsafe.  Locking means it will not allow another thread still the completion of one task of one thread. Ex: //To cancel the ticket Class CancelTicket extends Thread { object train, comp; CancelTicket(object train, object comp) Thread 1 CancelTicket { this.train = train; this.comp = comp; 100ms comp.obj } public void run() { synchronized(comp) { System.out.println(“CancelTicket locked the train.obj 200ms compartment”); try{ sleep(100); BookTicket Thread 2 }catch(InterruptedException ie){ } System.out.println(“CancelTicket wants to lock on train”); synchronized(train) { System.out.println(“CancelTicket now locked train”); } } } } class BookTicket extends Thread { object train, comp; BookTicket(object train, object comp) { this.train = train; this.comp = comp; } public void run() { synchronized(train) { System.out.println(“BookTicket locked the train”); try{ sleep(200); }catch(InterruptedException ie){ } System.out.println(“BookTicket wants to lock on compartmet”); synchronized(comp) { System.out.println(“BookTicket now locked compartment”); } } } Page 129 of 191 COREJAVA } class DeadLock { public static void main(String args[ ]) throws Exception { //take train and compartment as objects object train = new object(); object compartment = new object(); //create objects to CancelTicket, BookTicket CancelTicket obj1 = new CancelTicket(train, compartment); BookTicket obj1 = new BookTicket (train, compartment); //create 2 threads and attach them to these objects Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); //run the threads t1.start(); t2.start(); } } Save it as DeadLock.java compile & run the program. Output:CancelTicket locked the Compartment BookTicket locked the Train CancelTicket wants to lock on train BookTicket wants to lock the Compartment Press Ctrl+c for forcibly to terminate the program, because to solve this program in another way. Ex: //To cancel the ticket Solution for dead lock Class CancelTicket extends Thread { object train, comp; CancelTicket(object train, object comp); Locking { Solution for this.train = train; DeadLock Changing this.comp = comp; direction of thread 2 } public void run() { Thread 2 synchronized(comp) Thread 1 BookTicket { CancelTicket System.out.println(“CancelTicket locked the compartment”); try{ comp.obj 100ms sleep(100); }catch(InterruptedException ie){ } System.out.println(“CancelTicket wants to lock on train”); train.obj 200ms synchronized(train) { System.out.println(“CancelTicket now locked train”); } } } } class BookTicket extends Thread { object train, comp; BookTicket(object train, object comp); { this.train = train; Page 130 of 191 COREJAVA this.start(). BookTicket obj1 = new BookTicket (train. 4.currentThread().getPriority().println(“BookTicket now locked train”). 7. A programmer should avoid DeadLock situations in his program by properly planning designing the program. //run the threads t1.out.comp = comp.setName(“name”). ThreadClassMethods:1. To get the name of a thread String name = t.out. To set a new to a thread t. To know the currently running thread.println(“BookTicket locked the Compartment”). To get the priority of a thread int priority_no = t. synchronized(train) { System.start(). //create 2 threads and attach them to these objects Thread t1 = new Thread(obj1). 3. compartment). } } DeadLock of thread: . 2. In DeadLock both the threads mutually keep under waiting forever and further processing is canceled.getName().println(“BookTicket wants to lock on compartmet”).out. compartment). BookTicket CancelTicket obj1 = new CancelTicket(train. //create objects to CancelTicket. } public void run() { synchronized(comp) { System. } } } } class DeadLock { public static void main(String args[ ]) throws Exception { take train and compartment as objects object train = new object(). object compartment = new object(). To start thread t. 6.When a thread locked an object and waiting for another object which has been already locked by another thread and the other thread is also waiting for the first object it leads to DeadLock situation. To set the priority of a thread Page 131 of 191 . 5. Thread t = Thread. try{ sleep(200).sleep(milliseconds).start(). Thread t2 = new Thread(obj2). t2. }catch(InterruptedException ie){ } System. To stop execution of a thread for a specified time Thread. notify(). To send a notification to awaiting thread obj.join(). To test if a thread is still alive t.COREJAVA t. } catch(Exception e){ } Page 132 of 191 .The priority number constants are as given below Thread. Note: . To wait till a thread dies t. 10. producer() { 1 sb = new StringBuffer(). 12. To wait till the obj is released (till notification is sent) obj.notifyAll(). returns true/false 9. Ex: //Thread Communication Class Communicate { public static void main(String args[ ]) { //create Producer. Producer System. Thread t2 = new Thread(obj2). 11.append(i+”:”).setPriority(int priority_no).A program thread uses two types of operating system threads.MIN_PRIORITY value is 0 Thread. i++) { try 10 { sb.  The above three methods (10.  notify() method will sends a notification to a thread. Consumer sleep(100).e. // dataprodove is a data production over SrtingBuffer sb.println(“appending”). Green Thread model will provide only one thread for a program thread. //run the threads t1. i. objects Producer obj1 = new Producer(). some object is available to the thread.wait().start().NORM_PRIORITY value is 5 8.start().MAX_PRIORITY value is 10 Thread.out. Data Provider 2 } true 3 public void run() { for(int i = 1. To send notification to all waiting threads obj. //create 2 threads and attach them obj1. Q) Whatis the differencebetweenGreenthreadand Nativethread?***** Ans:. 12) are belong to object class. } } class Producer extends Thread { Boolean dataprodover = false. they are Green Thread model and Native Thread model. where as Native Thread provides a separate thread for each program thread. obj2 Thread t1 = new Thread(obj1). 11. t2. i<=10. Consumer. Consumer obj2 = new Consumer(obj1).isAlive(). Ex: //Thread communication in efficient way Class Communicate { public static void main(String args[ ]) { //create Producer. sleep(100). } } class Consumer extends Thread { Producer prod. objects Producer obj1 = new Producer(). } } class Producer extends Thread { 1 SrtingBuffer sb. //create 2 threads and attach them obj1.sb). Data Provider producer() 2 true { 3 sb = new StringBuffer(). } public void run() { try{ while(!prod. This above program/method is not efficient way to communication between threads.out.append(i+”:”). t2. } public void run() { synchronized() 10 { for(int i = 1.COREJAVA } dataprodover = true.start(). Page 133 of 191 . Thread t2 = new Thread(obj2). Consumer obj2 = new Consumer(obj1).start(). } }catch(Exception e){ } System. } } Save it as communication. If we want communicate efficient way we have to use notify() method. //run the threads t1. Consumer. i<=10. i++) Consumer Producer { try { sb. Consumer(Producer prod) { this.java.dataprodover) { sleep(10). obj2 Thread t1 = new Thread(obj1).prod = prod.println(prob. Consumer(Producer prod) { this. User thread or Main thread. Ex: To start mysql F:\rnr>mysqld↵  Here d is the Daemon thread. }catch(Exception e){ } System. Daemon thread 3. Daemon thread are used for background services. } } class Consumer extends Thread { Producer prod. } catch(Exception e){ } } sn. F:\rnr> Now onwards Daemon thread makes the mysql database running continuously.prod = prod. GUI thread Q) Whatis Daemonthread?***** Ans:. } // or we can use sb.out. } } } Q) Whatis the differencebetweensleep()methodand wait() method?***** Ans:.COREJAVA System.out. 2. } public void run() { synchronized(prod.Both methods will make the thread wait for some time. But both methods will wait temporarily.notify().sb).A Daemon thread is a thread that continuously provides services to other threads i.println(“appending”). Ex: synchronized(obj) synchronized(obj) { { ------------------------------------------locked locked ------------------------------------------sleep(2000).notifyAll(). Page 134 of 191 . Daemon threads are generally used background services. ------------------------------------------Unlocked locked ------------------------------------------} } Whatare differenttypesof threads:1.sb) { try{ prod. When the thread comes out of sleep() method the object may be still lock.println(prod. When the threads comes out of the wait() method the object is automatically unlocked.e. wait(2000).wait(). Afetr executing the all methods by run() method then the thread will be terminated.Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread. Start → run → wait (or) blocked state → Destroy State Life Cycleof Thread Running Yield New Thread Start Runnable The run method terminates Dead/Terminates (or) Not Runnable sleep() wait() Dead blocked on I/O Runnable means it will executes public void run methods yield makes pausing the thread. or voluntarily gives up its turn with this static method Thread. Page 135 of 191 . It runs until it becomes blocked.sleep(milliseconds). Blockedon synchronization : Will move to Runnable when a lock is acquired. Sleeping : . Running : . Blockedon I/O: Will move to runnable after I/O condition like reading bytes of data etc changes. Because of context switching overhead. The states assumed by the thread are called life cycle of a thread.sleep(milliseconds. Not Runnable means thread will stop runnable.A thread is in a blockedstate while it waits for some external processing such as file I/O to finish.yield().The processor is actively executing the thread code. Thread.Waiting for its turn to be picked for execution by the thread schedular based on thread priorities.Life cycle of thread means from the creation of thread till its termination. Runnable: .COREJAVA Q) Whatis threadlife cycle?***** Ans:. nanoseconds). Waiting : . yield() should not be used very frequently. “threadname”). //create another ThreadGroup as a child to tg ThreadGroup tg1 = new ThreadGroup(tg.out. “threadname”). //create 2 threads and add them to ThreadGroup Thread t1 = new Thread(tg. When a task invokes sleep().getThreadGroup()). Thread t3 = new Thread(tg1. //Find parent group of tg1 System.getParent()). Thread t4 = new Thread(tg1. //create a ThreadGroup with name tg ThreadGroup tg = new ThreadGroup(“Reservation Group”).setDaemon(true).Daemon threads are service providers fro other threads or objects. Thread t2 = new Thread(tg.isDaemon().start(). res. } } class Reservation extends Thread Page 136 of 191 . res. To make a thread as Daemon thread t.println(‘Number of threads in a group = ”+tg. 1. res. If we applied certain methods on the ThreadGroup it will effect all other threads.println(‘ThreadGroup of t1 = ”+t1. ThreadGroup tg = new ThreadGroup(“group name”). //start the threads t1.println(‘ThreadGroup of t2 = ”+t2.out.start().start(). because of ThreadGroup.out. It provides generally a background processing. res. it changes from running state to waiting/sleeping state. To know if a thread is Daemon or not t1 Boolean x = t. obj. obj1.start(). t4. Thread t1 = new Thread(tg. ThreadGroup tg1 = new ThreadGroup(tg. it changes from running state to runnable state. “First thread”). t2.New thread state → Runnable → Running → wait (or) blocked state → Destroy State ThreadGroup:. System. 2.  Whatis the differencebetweenyieldand sleeping?***** Ans:When a task invokes yield(). res Ex: /*Using thread groups*/ t2 class WhyTGroups { public static void main(String args[ ]) t3 can throws Exception { t4 Reservation res = new Reservation().COREJAVA Dead : The thread is finished working. //set maximum priority to tg1 as 7 tg1. tg1 Cancellation can = new Cancellation(). System. “Cancellation Group”). We can also add one ThreadGroup to another ThreadGroup. Controlling all the threadsx by giving a single command or method is possible. t3.  Here obj is target object Thread t2 = new Thread(tg. Daemon Thread: .  Whatare the statesof thread?***** Ans:. A daemon thread executes continuously.getThreadGroup()).setMaxPriority (7).println(‘Parent of tg1 = ”+tg1. “group name”). //know the ThreadGroup of t1 and t2 System.activeCount()).A group of threads as single unit is called ThreadGroup. “Fourth thread”). “Third thread”). “Second thread”).out. 0. These all generate events of some kind. application code still has to work out what type of event has occurred. a native code event is generated. say. The Command Pattern was renamed ``delegation'' by Sun engineers. the user performs an action such as moving the mouse. Unfortunately. The event may be caught by the native toolkit or ignored. The new model didn't work until JDK 1.0 version of this book.println(‘I am Reservation thread”). When they arrive. and when an event occurs the application has to figure out what to do with it. It was replaced by the ``new'' event model for Java 1. Both the old and new models had serious Software Engineering deficiences that led to poor quality code as soon as applications started to grow in scale.1 is now up to its third event processing model! The first one .println(‘I am Cancellation thread”). In yet other systems. or any other windowing system will sit in an event loop waiting for these events to occur. There are complex implementation layers and issues arising from the third event model. The way in which application code is called varies between the different windowing systems. The difference between the old and new models is subtle and depends on a complex interplay of events that belong to the underlying native implementation and the Java events. which are called when suitable events arrive. without any further need for intervention by the application programmer.out. and the handler will be called whenever the right event occurs in the right object. Microsoft Windows. so everyone continued to use the old model anyway.COREJAVA { public void run() { System. pressing a key or releasing one. two things marred this transition to the new model: • • Books had already begun to appear using the old event model.2. That is. } } class Cancellation extends Thread { public void run() { System. When one does. and forms a much cleaner way of handling events. application code is called in some way to respond to the event. the application programmer has to write an event loop handler themselves. it allows the application to register handlers (called listeners) with graphical objects. In other systems some assistance may be given with this.out.called the ``old'' event model was abandoned before Java left beta stage. etc. }} Event Handling Introduction Graphical User Interface systems handle user interaction using an event driven model. A GUI system such as the Java AWT. When the user performs an action such as a keypress. In some. the application merely needs to register an event handler with an object. This is firstly handled by native code at. and this was adopted for the third event model for the Java AWT.0. A solution to this was already known as the Command Pattern. Java in release 1. two things may happen: Page 137 of 191 . where events are dispatched to graphical objects automatically. If caught. Basically. and hardly anyone mentioned the new model. Motif. This was covered in the Java 1. the Windows or X level. This is an absolutely appropriate use of the interface mechanism. Listeners A listener is registered with an event type for an object. A listener object encapsulates this behavior. this is used. The event may be given to the Java object and then to the native GUI object. For example. This is not GUI code. it has to be by one of its methods. Not only is the behavior application specific. public abstract void keyTyped(KeyEvent e). So if the mouse is clicked in a Button. for example. Listeners are where the programmer places application specific code to respond to user events. then an action event is generated (invisibly to most applications). an appropriate method on the listener is invoked. an application can register a key event listener for any Component. then the second ``new'' event model is used.COREJAVA • • The event may be given to the native GUI object and then to the Java object. such as by a hot-key or by menu selection. There could be a standard method such as execute() or by one customised to the event that caused it. Java Beans imposes extra requirements which lead to these multiple event types. and should be registered with the Back button. So. though it is clearly application code that affects GUI objects as well as other application objects of the browser. then be reassured: if you only want to do simple things. Java code looks to see if there is an event listener using the third event model. When an event is handed to the Java layer. Most of the time you only want to simple things. current URL pointers. public abstract void keyReleased(KeyEvent e). We may have a Back button to return to the previously displayed page. the ActionListener is defined by public interface ActionListener extends EventListener { public abstract void actionPerformed(ActionEvent e) } whereas KeyListener is defined by public interface KeyListener extends EventListener { public abstract void keyPressed(KeyEvent e). the hot-key combination and the menu selection. Sometimes there is no listener but the third model should be used anyway. Since listeners contain application code. whenever a key is pressed in a Component. When a listener is invoked. When we click on this Back button. the delegation event model lets you do them simply. All the listener needs to do is to implement certain methods. When a suitable event occurs. they will probably have an inheritance based on the application. then the method keyPressed() is called in any key event listener.1 has chosen the second method. but there is more than one way way of invoking this behavior. Page 138 of 191 . not on some vagaries of the GUI side. For example. it is changed into a Java event. If all this sounds grim. the application will need to reload the last page into the browser window and reset history lists. If there is not. suppose we are building a Web browser. The methods defined for listeners are done using interfaces. Which one of these occurs depends on the event type. or an action event listener for objects such as Button or TextField. The JDK 1. and theactionPerformed() method is called on any action listener. If there is. On the other hand. etc. This could have been more simply if simplicity was the only driving force behind this event model: however. This can be forced. so that the internal event handling code can call the right method. The Back function can also be invoked in other ways. just like any object . Button right = new Button("Right"). The other objects are set by special methods Here is a trivial application just to show how listeners are created and used. and the right one has the label ``Right'' When either Button is pressed. Some of these will be GUI objects. some won't. left. import java. // create a listener and add it to each Button SimpleListener simple = new SetText(label). } } Page 139 of 191 . The application has a Button on the left.ActionListener. Label label = new Label("Center").awt. One is graphical.awt. any application code inheriting a listener specification must implement its methods. a Button on the right and a Label in the middle. the label of the Button pressed.e. /** * This application consists of two Buttons with a Label * between them. add(label.get knowledge about other objects in three ways • • • They create the other objects and store them in local variables.Button. the text showing in the Label is set to either ``Left'' or ``Right'' i. "Center"). The other objects are passed in by the constructor. Returning to our browser example. Listener methods will usually interact with other objects of the application.addActionListener(simple). import java.Label. add(right. import java. its text is * set in the Label * * @author Jan Newmarch */ public class DelegateDemo extends Frame { public static void main(String argv[]) { new SimpleEvent(). the Back button listener will need to access the URL object to retrieve the previous URL. The left Button has the label ``Left''.COREJAVA } Implementing Listeners Since a listener is defined as an interface.show(). It doesn't really matter. Listener objects . right. } public DelegateDemo() { // create the GUI objects Button left = new Button("Left"). // set their geometry add(left. the other is not.addActionListener(simple). "West"). "East"). and the browser display object to show it. pack(). The rest of the listener code is upto the application.event. When a Button is pressed.awt. setText(name).ActionEvent e) { // get the label showing in whichever Button was pressed String name = e. then you will have used theEvent class in your event handling code. The AWTEvent is very simple. and you don't even need to look at it unless you are doing arcane things (which we will do later). For each type of event that is present in the delegation model. there is a separate class. // set this in the Label object label. Forget also about all the fields and values that are present inEvent . id. It is superceded by AWTEvent. In addition there are low-level window events that are only received by Frame and Dialog. } public void actionPerformed(java. rather it is a guide to the programmer.getActionCommand().awt. and higher-level semantic events that only have meaning for particular GUI objects. Forget about that class now.COREJAVA /** * A listener object that is invokded when a Button is activated * It finds the Button's label and sets it in a Label */ class SetText implements ActionListener { private Label label. The classes are divided into two types: low-level input or window events that every GUI object receives.event. If you are familiar with the old or new event models. public SetText(Label l) { // the listener needs to know the Label it will act on label = l. } } AWTEvent Events that are handled by delegation objects are all subclassed from AWTEvent. The low-level events for any Component are Table 1: Low-level Event Types Class id ComponentEvent COMPONENT_MOVED COMPONENT_RESIZED COMPONENT_SHOWN COMPONENT_HIDDEN FocusEvent FOCUS_GAINED FOCUS_LOST KeyEvent KEY_PRESSED KEY_RELEASED Page 140 of 191 . and that is protected anyway. This kind of division of types is not captured anywhere in the language.they are all absent from AWTEvent. The class AWTEvent has only one field. the protected id takes on different values to distinguish between the type of event. These values are used by the AWT to call appropriate methods on listeners. that have methods invoked when the event occurs. This value can be found from the event methodgetId(). The semantic events are generated by the following Table 3: Semantic Event Generation Event Object Action ActionEvent Button Click on Button List Double-click on an item MenuItem Click on MenuItem TextField Press <Enter> key AdjustmentEvent Scrollbar Any Scrollbar action ItemEvent Choice Select an item List Select or deselect an item Checkbox ??? CheckboxMenuItem ??? Listeners for Different Events For each event type that can occur. so that an actual listener has to Page 141 of 191 . and you do not usually need to look at these values.COREJAVA MouseEvent KEY_TYPED MOUSE_CLICKED MOUSE_DRAGGED MOUSE_ENTERED MOUSE_EXITED MOUSE_MOVED MOUSE_PRESSED MOUSE_RELEASED Where are PaintEvent. For the semantic level events. it isn't really very useful (unless you have subclassed one of these semantic events and have your own extra id values). the application can add event listeners. so that although getId() will give a value. The listeners are defined asinterfaces.PAINT etc? The low-level window events for Frame and Dialog are Table 2: Low-level Window Event Types Class id WindowEvent WINDOW_CLOSED WINDOW_CLOSING WINDOW_DEICONIFIED WINDOW_ICONIFIED WINDOW_OPENED The semantic level events are Table 3: Semantic Event Types Class Id ActionEvent ACTION_PERFORMED AdjustmentEvent ADJUST_VALUE_CHANGED ItemEvent ITEM_STATE_CHANGED For the low-level events. there is only one value for id. This would cause event tracking for all of the different mouse events. using two separate listeners improves efficiency. When a key is pressed. a TextField. Consistency would have one mouse listener only. When the key is released. the method keyReleased() will be called with a different KeyEvent as parameter. this was done for an ActionEvent listener on a Button by Page 142 of 191 . say.COREJAVA implement these methods. Of course. Table 4: Listeners for Each Event Event Listener Method ActionEvent ActionListener actionPerformed() AdjustmentEvent AdjustmentListener adjustmentValueChanged() ComponentEvent ComponentListener componentResized() componentMoved() componentShown() componentHidden() FocusEvent FocusListener focusGained() focusLost() ItemEvent ItemListener itemStateChanged() KeyEvent KeyListener keyTyped() keyPressed() keyReleased() MouseEvent MouseListener mouseClicked() mouseEntered() mouseExited() mousePressed() mouseReleased() MouseMotionListener mouseDragged() mouseMoved() WindowEvent WindowListener windowClosed() windowClosing() windowDeiconified() windowIconified() windowOpened() The elements of this table should be interpreted as follows: • • An ActionListener has been registered with. except that MouseEvent's have two different types of listener for efficiency reasons. However. the method keyPressed() of the KeyListener will be called with the KeyEvent as parameter.e. the method actionPerformed() of the ActionListener will be called with a single parameter: the ActionEvent that was generated. The names of the listener classes are simply derived from the names of the events they handle. etc. AdjustmentListener. the GUI object has to be capable of generating the right type of event for the listener. it has been typed). Once created. the method keyTyped() is called with a third KeyEvent as parameter. and also. a Button. listeners are registered with GUI objects. Two types of listener may be registered for mouse events: this represents a tradeoff between consistency and efficiency. Since many GUI objects might be interested in mouse clicks but not mouse motion. In the simple example we had earlier. tracking mouse motion is costly: many events are generated as the user moves the mouse around. In network systems such as X Windows. say. Listeners are added to each object by a suitable add<event>Listener() call. • RegisteringListeners A listener implements one of the interfaces ActionListener. because a key has been pressed and released (i. A KeyListener may be registered for key events with. this can often swamp the available bandwidth leading to visible delays in mouse tracking. When the Button is clicked. Key. left. There is no such method for List or TextField. The following table lists which objects can have which listener types added: Table 5: Objects and Listeners for Them GUI Object Listener Button ActionListener Choice ItemListener Checkbox ItemListener Component ComponentListener FocusListener KeyListener MouseListener MouseMotionListener Dialog WindowListener Frame WindowListener List ActionListener ItemListener MenuItem ActionListener Scrollbar AdjustmentListener TextField ActionListener Note that every GUI object inherits from Component. This command may be set by the Button or MenuItem by their setActionCommand(String) method. So every object can have Component. An ActionEvent has two methods that the programmer may find to be of use: public String getActionCommand() public int getModifiers() Each ActionEvent carries around an ``action command''. Mouse and MouseMotion listeners added.COREJAVA SimpleListener simple = new SimpleListener(label). and its method actionPerformed() is called when the user performs the indicated activity. Focus. ActionEvents Action events are generated for the following objects: Table 6: Objects generating Action Events GUI Object Action Button Click on Button List Double-click on an item MenuItem Click on MenuItem TextField Press <Enter> key An ActionListener can be registered with each of these objects. The value of the action command (unless reset) is Table 7: Value of Action Command GUI Object action command Button label List ??? MenuItem label TextField ??? Page 143 of 191 . The next sections look at each event type in turn.addActionListener(simple). If low-level information is required. n++) { if (colorLabels[n].awt. final String colorLabels[] = {"red".println("Unknown color: " + colorName). import java. set foreground comp.awt. n < colorLabels. A single SetColor listener will be created and registered with each button. /** * An ActionListener that changes the foreground * color of a component passed in by the constructor * * @author Jan Newmarch */ public class SetColor implements ActionListener { final Color colors[] = {Color. This method is inherited by every event from the superior class java. } } The first program to use this has a row of three buttons along the top and a label to below them.util.COREJAVA The action command gives runtime information about the context in which the event occurred. "green"}. } } System. Color.setForeground(colors[n]).Component.out. We shall illustrate use of action events by four programs which do basically the same thing.getActionCommand(). This ActionListener is defined by the following: import java. Color. but use different GUI elements to do this. the source object can be obtained from the methodgetSource() (or equivalent methods). return. } /** * Invoked by an action event somewhere * resets the foreground of a component passed * in to the constructor */ public void actionPerformed(ActionEvent e) { String colorName = e.awt. // search for Color matching color name for (n = 0. import java.red. This is semantic-level information.EventObject.event. The application looks like The code is Page 144 of 191 . The common part of these will be a Label which can have its foreground color set to different values. public SetColor(Component c) { comp = c. "blue". rather than low-level information: the text showing in the Button is usually enough useful information.blue.length.ActionListener. private Component comp. but they will all invoke the sameActionListener.Color.green}. The color can be selected in different ways for each program.equals(colorName)) { // found a match. awt.add(red).awt. } public ButtonColor() { // the label that will be colored Label label = new Label("Click on button to change color"). add(panel.COREJAVA import java. import SetColor. } } The second program to use the SetColor listener will just change elements of the user interface. add(label. In this version we shall only implement the double-click action. "North"). // buttons for each color Button red = new Button("red").addActionListener(sc). // add the listener SetColor sc = new SetColor(label). // a panel to hold the buttons Panel panel = new Panel(). panel.show(). Button green = new Button("green"). import SetColor.show(). leaving single-click till later (that uses a different type of event).addActionListener(sc). Button blue = new Button("blue").*.addActionListener(sc). panel. public class ListColor extends Frame { public static void main(String argv[]) { new ListColor(). } public ListColor() { // the label that will be colored Page 145 of 191 . green. pack().add(green). panel.add(blue). public class ButtonColor extends Frame { public static void main(String argv[]) { new ButtonColor().setLayout(new FlowLayout()). "Center"). blue.*. That is. // set geometry panel. The application looks like The code is import java. instead of a set of buttons. it will use a list to the left of the label. red. In this we are partly lucky since we are handling the same event type in both programs. public class MenuColor extends Frame { public static void main(String argv[]) { new MenuColor(). Page 146 of 191 . color.add(red).add("green"). The application looks like The code is import java.*. "Center"). add(label.add(color).add(green).add("red"). colors. } public MenuColor() { // the label that will be colored Label label = new Label("Select color from menu"). color. pack().addActionListener(sc). // menu color items MenuItem red = new MenuItem("red"). color. but even handling different types does not cause many changes. mb. MenuItem blue = new MenuItem("blue"). colors. MenuItem green = new MenuItem("green"). // add the listener SetColor sc = new SetColor(label). } } Note that we have not changed the application code at all.show().add(blue). colors. This time we shall use a menu of colors to make the selection. only the GUI code. Menu color = new Menu("Color"). // the menu bar MenuBar mb = new MenuBar(). colors. The third program will make the same kind of change.add("blue"). just as for the buttons in the first program. "West"). // set geometry add(colors. // the list of colors List colors = new List(3). import SetColor. Each item in the menu will have the same listener added.COREJAVA Label label = new Label("Double-click to change color").awt. pack().addActionListener(sc). "Center"). // the text field to enter the color TextField text = new TextField(20).awt. The last example gives the last variation on this theme. // add the listener SetColor sc = new SetColor(label). } } This last piece of code is rather lacking in ease of use. // add the listener SetColor sc = new SetColor(label). pack(). add(label. } public TextFieldColor() { // the label that will be colored Label label = new Label("Enter color in the TextField"). The application looks like The code is import java. } } Again there is no change to the application code. public class TextFieldColor extends Frame { public static void main(String argv[]) { new TextFieldColor(). blue. green. red.COREJAVA // set the geometry setMenuBar(mb).addActionListener(sc).*. "North"). text. as it gives no clues as to what are allowable text values! AdjustmentEvents Page 147 of 191 . add(label.addActionListener(sc). "Center").show(). // set geometry add(text. import SetColor. using a TextField for color selection.addActionListener(sc). by dragging the slider or by keyboard interaction such as the arrow keys or PageUp/PageDown keys. COMPONENT_MOVED. public void componentMoved(ComponentEvent).down one ``page'' BLOCK_DECREMENT . To use this value. This is used for tracking movement. This will return one of the four values • • • • UNIT_INCREMENT . In objects of class ComponentEvent the id is used field to distinguish between four types: COMPONENT_HIDDEN.1. a visually intensive piece of graphics such as animation should cease when the display object becomes invisible.are available from the event of class Adjustable in which the event occurred (right now we know this is a Scrollbar but it could be other things in the future . There is only the one method called despite the variety of ways that the user can interact with the scrollbar. public void componentResized(ComponentEvent). There is not so much need to use this class in Java 1. so it will want to track visibility changes. a Scale object). so you are unlikely to need to look at this field. An application wanting to track such changes registers a listener that implements ComponentListener.and much other information . For example. it can call the method getAdjustmentType() on the AdjustmentEvent. This interface defines four methods that the listener must implement: public void componentHidden(ComponentEvent). COMPONENT_RESIZED andCOMPONENT_ SHOWN. If the application needs to distinguish between these.up one ``line'' BLOCK_INCREMENT . public void componentShown(ComponentEvent). Here is a program to track resize and movement events on the toplevel Frame: Page 148 of 191 . you need to know where on the scale from minimum to maximum it occurs.COREJAVA Adjustment events are only generated for objects of class Scrollbar in Java 1. These . A listener of class AdjustmentListener is added to a Scrollbar by the method public void addAdjustmentListener(AdjustmentListener) The user can interact with the scrollbar by clicking the mouse within it. The ComponentEvent class supplies a method public Component getComponent() if you need to determine which component has called the listener.for example. The AWT uses this value to select which of the four listener methods to call.up one ``page'' The actual value of the scrollbar can be found from the method getValue() of the AdjustmentEvent. so it will want to track size changes. resizing and visibility. A ``smart'' text display may want to change the size of the font used according to the amount of space it has.down one ``line'' UNIT_DECREMENT . Component Events Most applications will not need to use events of type ComponentEvent. as there is also aScrollPane class which looks after most details of handling a viewport onto a component. There are occasions when an application may want to track such events. An application will generally function perfectly well by ignoring these events: the AWT toolkit will look after things such as calling layout managers on resize.1. These all cause the method public void adjustmentValueChanged(AdjustmentEvent) to be called in the listener. event.width + ".ComponentEvent. } public TrackResize() { Label label = new Label().COREJAVA import java. } } The Tracker class inherits only from Object.x + ".getSize(). public class TrackResize extends Frame { public static void main(String argv[]) { new TrackResize(). } public void componentHidden(ComponentEvent e) { // empty } public void componentMoved(ComponentEvent e) { showGeometry(e). } public void componentResized(ComponentEvent e) { showGeometry(e).awt.setText("Position: (" + p. This may become mildly annoying if it had to be done frequently. label.getComponent(). import java. pack().y + ") Size: (" + d. addComponentListener(new Tracker(label)). } public void componentShown(ComponentEvent e) { // empty } private void showGeometry(ComponentEvent e) { Component c = e. Point p = c. } } class Tracker implements ComponentListener { private Label label.awt." + p. so there is a ``convenience'' classComponentAdaptor which defines all these methods as empty ones. you can inherit from ComponentAdaptor and then just override the Page 149 of 191 .getLocation(). Tracker(Label l) { label = l. Using this.show().height + ")"). Because it has to implement all of the ComponentListener interface it ends up with empty implementations of thecomponentHidden() and componentShown() methods." + d.*. add(label). Dimension d = c. The single inheritance model of Java does of course then require that the listener cannot also inherit from other classes. import java.COREJAVA methods you need. it will have the methoditemStateChanged() called with an ItemEvent as parameter. Item event handling appears to be incomplete in Java 1.event.the list. If you need to.Component. The interface ItemSelectable declares methods interface ItemSelectable { int[] getSelectedIndexes(). FocusEvents Applications are unlikely to need to track focus events.1 beta. but not the single list item that changed state.Frame. There are no extra methods for handling these events. The index is given by the getItem() of theItemEvent. Now consider the information we would be after when an item in a list is selected: the index and the string showing.awt.awt. the classes that implement the ItemSelectable interface are List.awt. From there you can find the set of all selected items (which may be more than one).awt. The method getItemSelectable()returns the item that the selection was performed on . The listener must then implement the methods public void focusGained(FocusEvent). import java. Presently.ItemListener. /** * An ItemListener that changes the foreground Page 150 of 191 . To get at that. // import java. import java. but it has to be coerced to class Integer first. you have to check and then coerce the ItemSelectable to class List and then use the List method getItem() to find the string selected. String[] getSelectitems().ItemEvent. Choice and Checkbox. as the AWT toolkit looks after most aspects of focus changes. public void focusLost(FocusEvent).event. The actual string is not obtainable from the information given.Label. // import java. Item Events Item events are generated for the following objects: Table 8: Objects generating Item Events GUI Object Action Choice Click on item Checkbox Select an item Deselect an item List Select an item Deselect an item Extend a selection Reduce a selection An application wanting to follow selection changes registers an object that implements ItemListener.Color. When such a change occurs. The ItemEvent declares methods ItemSelectable getItemSelectable(). so this may be of limited value.awt. Object getItem(). import java.awt. you can add a focus change listener by AddFocusListener(). Color. // search for Color matching color name //for (n = 0. "green"}.add("green").red.show().println("Unknown color: " + colorName). private Component comp. n < colorLabels. colors. //String colorName = e.out.getItem()). Color. n++) { //if (colorLabels[n]. public SetColor2(Component c) { comp = c. //} //} //System. colors. pack().*.awt.getActionCommand().getStateChange == ItemEvent.add("red").COREJAVA * color of a component passed in by the constructor * * @author Jan Newmarch */ public class SetColor2 implements ItemListener { final Color colors[] = {Color. Page 151 of 191 . public class ListColor2 extends Frame { public static void main(String argv[]) { new ListColor2(). } public ListColor2() { // the label that will be colored Label label = new Label("Hello World"). } /** * Invoked by an item event somewhere * resets the foreground of a component passed * in to the constructor */ public void itemStateChanged(ItemEvent e) { if (e.length.println(e.setForeground(colors[n]). // the list of colors List colors = new List(3). "West"). // add the listener SetColor2 sc = new SetColor2(label).add("blue"). //return. colors. final String colorLabels[] = {"red".out. add(label.equals(colorName)) { // comp.blue. // set geometry add(colors.green}. "Center"). "blue".SELECTED) { System. } } } import java. A KeyEvent defines a large number of constants for the special keys on the keyboard.. . public boolean isControlDown(). the super class of KeyEvent. These allow tests for the modifier keys: public boolean isShiftDown().awt. the application may change any text typed to lower case by mapping any upper case characters entered into lower case. or of the tab key to move between objects.PGUP: . The information from these can also be obtained from the method getModifiers(). and that is they can be changed by the application.show().isActionKey()) { switch (e. For example.getKeyCode()) { case KeyEvent.HOME: .. These are known as action keys and are given in this table: Table 9: Action Keys END PGUP DOWN LEFT PRINT_SCREEN SCROLL_LOCK PAUSE INSERT TAB ESCAPE HOME UP F1 .F12 NUM_LOCK BACK_SPACE PGDN RIGHT CAPS_LOCK ENTER DELETE These can be tested by code such as KeyEvent e.addItemListener(sc). etc. case KeyEvent. . but of course for TextArea and TextField they really have semantic content. case KeyEvent.. import java.awt.. if (e.KeyListener. public boolean isMetaDown().event. For other classes keyboard events are most likely to be use in implementing keyboard traversal mechanisms.. } public ShowKey() { Page 152 of 191 . They count as ``low level'' events for most objects..CTRL_MASK. import java.END: . public class ShowKey extends Frame { public static void main(String argv[]) { new ShowKey().*.COREJAVA colors.. } } KeyEvents Key events may be generated for all components... } } There are related methods inherited from InputEvent. Key events also have an important property not shared with most other event types. and then comparing this to InputEvent. such as the use of arrow keys to move around a grid of labels.. addKeyListener(ki).COREJAVA Label l = new Label("Hello"). and therefore are subject to severe security restrictions. } public void keyTyped(KeyEvent e) { System. KeyInfo ki = new KeyInfo().println(e. can be loaded from anywhere on the Internet.toString()). } public void keyReleased(KeyEvent e) { System. add(l). Java applications are designed to be run in standalone mode on a client machine and therefore can be thought of as a known entity. other than the typical Java runtime files included in the Java Developer's Kit. } private void printInfo(KeyEvent e) { System. These browsers include: Page 153 of 191 .println("char: " + e. The popular Web browsers on the market support embedded Java applets in HTML pages. } } JAVAAPPLETS What Is an Applet? Java applets are special kind of Java programs that run when embedded in a Java enabled Web browser or a specialized tool such as appletviewer.getKeyCode()). printInfo(e).print("Up: ").out. Because of this. l. Java applets currently are being used for advertising purposes because they provide the capability to include simple animation and sound in a Web advertisement. What Is Required to Run an Applet? Java applets are typically run within a Web browser. Java applets. pack(). System.print("Typed: ").out.out. A Java application does not require any additional software. printInfo(e). Java applets are certain to quickly progress from "neat" status to true business use status. } } class KeyInfo implements KeyListener { public void keyPressed(KeyEvent e) { System.print("Down: "). printInfo(e). Many client/server developers currently are looking at the company intranet as an excellent platform on which to finally deliver true cross-platform corporate applications. meanwhile. The Web browser supplies the framework for retrieving and loading an applet and also supplies the main window holding the applet. such as a Web browser.out.getKeyChar() + "keycode: " + e.out. • Make a network connection to a host on the Internet other than the one from which it was downloaded.5 The Applet Viewer tool included with the Java Developer's Kit can be used to test and run Java applets as well. What Can an Applet Do? An applet can: • Draw pictures on a web page • Create a new window and draw in it. set screen colors. and connect to a host database. start().COREJAVA • Sun HotJava 1.0 • Netscape Navigator 2. stop(). public void start() The start() method is called after the applet has been initialized. The following discussion provides some information on each of these methods. an applet cannot read data from the user's disks even with permission. • Play sounds. This method is used to do one-time setup features such as add components to the layout manager. However in practice Java isn't quite stable enough to make this claim yet. public void init() The init() method is called when the applet is initially loaded. The main() method which is necessary for executing standalone applications is not necessary for running applets.applet package contains standard framework for developing applets. There are restriction on what an applet is allowed to do. Applets can be stopped when the user changes to another Web page. An applet is implemented by creating a subclass of the Applet class and overriding the appropriate methods to customize the running of the applet. APPLET LIFE CYCLE Each applet has four major events in its lifetime: • Initialization • Starting • Stopping • Destroying These four events correspond directly to four methods within the Applet class: init(). and also each time the applet is restarted after being stopped. and destroy(). • Call the native API directly (though Java API calls may eventually lead back to native API calls).0 (or greater) • Microsoft Internet Explorer 3. An applet cannot: • Write data on any of the host's disks. All memory access is strictly controlled. To run an applet an HTML file with appropriate information about the applet’s class file must be provided. • An applet is not supposed to be able to crash the host system. GUI components and containers can be embedded in an applet to build a GUI for the applet. If the user returns at a later time to the page with the Page 154 of 191 . • Receive input from the user through the keyboard or the mouse. even on a non-memory-protected operating system like the MacOS. • Read any data from the host's disks without the user's permission. Building a Java Applet The java. In some environments. notably Netscape.0 • Oracle PowerBrowser 1. • Introduce a virus or trojan horse into the host system. • Make a network connection to the server from which it came and can send to and receive arbitrary data from that server. • Delete files • Read from or write to arbitrary blocks of memory. Font. public class LifeCycleApplet extends java.Color.COREJAVA applet on it. repaint(). String1 = "". int i.applet.awt. String2 = "The applet is stopping!".Graphics.drawString(String1 + String2. } public void start() { i = 1. String String1.awt.awt. public void destroy() The destroy() method is called whenever it is time to completely finish the applet's execution. An applet illustrating the life cycle methods. String2 = "The applet is starting!". the applet will be restarted by the browser. g. showStatus("The applet is stopping!").BOLD. repaint().blue). } public void stop() { i = 2. The stop() method is used to temporarily suspend the execution of the applet until the start() method is called again. g. stop(). Common operations that occur during an applet's start() method are the initialization of threads within the applet and the updating of the screen display. Therefore. } public void destroy() Page 155 of 191 .Font. 30). import java. } public void init() { i = 0. String1 = String2. and destroy(). String2. 20). repaint(). The destroy() method is used to free up allocated resources such as threads or database connections. This method is generally called when the browser is exiting or the applet is being reloaded from the host server. showStatus("The applet is initializing!"). import java. The program below shows a simple applet that implements all four life cycle methods: init(). import java. 5. String2 = "The applet is initializing!".Applet { Font theFont = new Font("Helvetica". start(). the start() method can be called many times during an applet's life cycle.setColor(Color. showStatus("The applet is starting!"). public void paint(Graphics g) { g.setFont(theFont). This applet updates the screen as well as the browser status bar with some information indicating which method is being called. String1 = String2. public void stop() The stop() method is called whenever the user leaves the current page. The definition of this method must have the form: public void paint(Graphics g) { // draw some stuff } Page 156 of 191 . This is a handy way of passing arguments to an applet to allow the applet to be more generic. WIDTH-(Required) The WIDTH attribute is used to set the applet's box width. HEIGHT-(Required) The HEIGHT attribute is used to set the applet's bounding rectangle height. showStatus("The applet is being destroyed!"). VSPACE-The VSPACE attribute sets the amount of vertical space to set off around the applet. ALIGN-The ALIGN attribute designates the alignment of the applet within the browser page.class" WIDTH=600 HEIGHT=50> </APPLET> </BODY> </HTML> public void paint() The paint() method is called by the system when the applet needs to be drawn. The <APPLET> Tag The syntax for using the <APPLET> tag is the following: <APPLET attributes> applet_parameters alternate_content </APPLET> The APPLET attributes are standard values that all applets accept and are a standard part of HTML. <APPLET> Tag Attributes ALT-Alternate text that can be displayed by text-only browsers. repaint().class file that loads the applet. HSPACE-The HSPACE attribute sets the amount of horizontal space to set off around the applet. CODE-(Required) The CODE attribute is used to indicate the .COREJAVA { i = 3.html file contents. The LifeCycle. <HTML> <HEAD> <TITLE>This is the LifeCycle applet!</TITLE> </HEAD> <BODY> <H1>Life Cycle of Applet </H1> <BR> <APPLET CODE="LifeCycleApplet. The <APPLET> tag-Used to represent a Java applet to be loaded. String2 = "The applet is being destroyed!". The applet_parameters are applet-specific parameters that are read by the applet at runtime. } } HTML and Java Applets Inorder to run an applet and HTML file with appropriate information about the applet’s class file must be provided. CODEBASE-The CODEBASE attribute is used to indicate the location of the . String1 = String2. NAME-The NAME attribute sets the symbolic name of the applet.class file that loads the applet. is provided by the system when it calls the paint() method.COREJAVA The parameter g. But it can also be called at other times. all drawing of any kind is done using methods provided by a Graphics object. It can happen when you scroll the window of a browser. the text drawn on the screen was drawn using the blue color. It is then left up to the applet to take advantage of this information and actually paint the text blue on the screen. the applet's paint() method can be called because the program makes a request for the applet to be redrawn. Such requests are made by calling a method named repaint().applet. by the way. of type Graphics. In Java. draw GUI components such as buttons and text input boxes that the applet might contain. Such GUI components are objects in their own right. And. The paint() method of an applet does not.Applet parent class. This can be done by passing a parameter to the applet specifying that it use the blue tag. It is called whenever the contents of the applet need to be redrawn. In the previous applet example. The applet's paint() method is called by the system as soon as the applet appears on the screen. Passing Parameters to Java Applets Parameters are an easy way to configure Java applets without actually changing the source file. <HTML> <HEAD> <TITLE>This is the LifeCycle applet!</TITLE> </HEAD> <BODY> <H1> Life Cycle of Applet </H1> <BR> <APPLET CODE="LifeCycleApplet. This might happen if the applet is covered up by another window and is then uncovered. Here are three methods commonly used by applets: • String getParameter(String name)-Returns the value for the specified parameter string • URL getCodeBase()-Returns the URL of the applet • URL getDocumentBase()-Returns the URL of the document containing the applet Page 157 of 191 . defined by other classes. and the applet scrolls into view. it is especially important to note. Passing parameters to the applet using HTML parameters. Calling getParameter("color") using the previous Java applet example would return a String value containing the text "blue".class" WIDTH=600 HEIGHT=50> <PARAM NAME=color VALUE="blue"> </APPLET> </BODY> </HTML> How does the Java applet determine the value of the parameters? The applet has to call the getParameter() method supplied by the java. NAME and VALUE. public class AppletParam extends java.*. public void init() { input_from_page=getParameter("string").drawString(str. import java.*.class" width=350 height=200> <PARAM NAME="string" VALUE="Applet"> </APPLET> </P> <HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT> </BODY> </HTML> The PARAM HTML tag occurs between <APPLET> and </APPLET>.COREJAVA Example import java. } } HTML FILE <HTML> <HEAD> <TITLE>Applet HTML Page</TITLE> </HEAD> <BODY> <H3Applet HTML Page</H3> <P> <APPLET code=" AppletParam. } public void paint(Graphics g) { g.applet.awt. input_from_page="Hello "+ str. 100).Applet { String input_from_page . It has two parameters of its own.applet.10. Both must be enclosed in double quote marks like all other HTML tag parameters. The NAME identifies which parameter this is for the getParameter method. Page 158 of 191 . VALUE is the value of the parameter as a String. if (input_from_page==null) input_from_page="Java". awt.COREJAVA SIMPLE GRAPHICS AND GUI TECHNIQUES Applets can work in a Graphical environment. Commonly used user interface classes in package java.awt.List. The AWT is actually a package named java.Applet { Page 159 of 191 .awt. The following Table lists the most commonly used classes with a brief description of each class. Class Name Button Canvas Checkbox CheckboxGroup CheckboxMenuItem Choice Color Component Container Dialog FileDialog Font Frame Graphics Image Label List Menu MenuBar MenuItem Panel Scrollbar TextArea TextField Window Description A standard pushbutton user interface component A canvas that is used as a graphics drawing context A standard checkbox user interface component A user interface component used to group checkboxes A checkbox that is displayed as a menu item A menu component that displays the currently selected choice A class used to encapsulate colors in Java The base class of all user interface components A base class for all container/grouping components A standard dialog screen that can be either modal or nonmodal A standard file selection dialog that is OS-dependent A class used to encapsulate fonts in Java A frame that can contain window objects The base class used for all graphics and drawing operations A class used to encapsulate images in Java A standard label user interface component A standard list box user interface component A menu component that resides on a menubar The menubar that contains menus and menu items Menu selection items that trigger program events A user interface component used to surround other components A standard scrollbar user interface component A multiline text editing window A single-line text editing window A window inside a frame that contains multiple objects import java.Button. import java. import java.applet.awt.applet.TextField.awt included with the JDK is used for this purpose. import java. public class EditList1 extends java.Applet. or a BorderLayout manager. add(theList). } } Adding components to applets Applets can be used as a container for visual components. Layout managers There are several different layout managers. top to bottom. which creates a text area with a button to its right. here is a code snippet using a BorderLayout. Components are created. add(theText). North West Centre South BorderLayout directions As an example. public void init() { theText = new TextField(). and then added to the applet container. List theList.awt package. and BorderLayouts allow you to specify a general direction. Button theButton. Example of FlowLayout. and can handle different applet sizes. GridLayouts allow you to place applets in a grid format. add(theButton). Applets that use a flow layout will allow components to flow freely from left to right. such as those provided by the java.COREJAVA TextField theText. and you can even write your own if so inclined. first-served manner. Page 160 of 191 East . theButton = new Button("Add text to list!"). // Set layout manager to flow layout setLayout(new BorderLayout()). The positioning of applet components is controlled by a layout manager. The easiest layout manager is the FlowLayout. you could use a GridLayout manager. theList = new List(). which adds components on a first-come. with different applet sizes For more specialised layout. when a user must enter data. Button Buttons are useful when an application must recieve specific instructions from the user before proceeding. add(pizzaChoice). } Choice Choice components take up very little screen space. String msg. pizzaChoice. add(new Button("Ok"). "East"). consider using text fields instead. } Page 161 of 191 .*. and for displaying information that should not be modified by users. along with a sample applet to demonstrate each component's use. public void init() { button= new Button("click here"). a button can be used to instruct the applet / application to proceed when the data entry is complete. pizzaChoice. add(button). and can present the user with a series of choice from which a single selection can be made Example Source import java.awt package is presented below. "North").5). pizzaChoice.applet. If you want to have modifiable labels. public class ChoiceApplet extends Applet { public void init() { Choice pizzaChoice=new Choice().add("Medium Pizza").add("Large Pizza"). and then wants to perform a task.select("Medium Pizza"). click here Example Source public class ButtonApplet extends Applet { Button button. a status bar containing a label is used to convey information to the user. ranging from text labels and buttons to selection lists. Label Labels are great for providing user prompts. In almost all of the examples presented here. pizzaChoice. For example. A selection of more common components from the java. windows and dialogs.add("Small Pizza"). AWTCOMPONENTS There are a wide variety of AWT components.COREJAVA // Add three components to applet add(new TextArea(5. COREJAVA } Page 162 of 191 . applet.COREJAVA TextField Textfield components are useful for obtaining short pieces of information from users.setFont(new Font("Serif".awt. for(int i=0. but can conserve quite a lot of room because they have support for scrollbars.Applet { public void init(){ TextField text=new TextField(18). Furthermore.*."PawPaw"}. import java.awt. use a TextArea instead). import java.add(fruit[i]).12)). as the items can be presented to the user. } } TextArea Textarea components are useful for getting a large amount of data from a user. public class TextFieldApplet extends java. They are limited to single line input (for multiple lines.*.PLAIN. Go ahead and Type Example Source import java. they take up more space than a choice component. This can be useful at times.*. Page 163 of 191 . text. multiple selections are allowable with the list component (though this feature must be enabled).applet.Applet { public void init() { String fruit[]={"Mango". add(fruitlist). and the currently selected item can be returned.setText("Go ahead and Type "). List fruitlist=new List(fruit. text.true).*. add(text). Items can be added. public class ListApplet extends java. or for displaying a large amount of data that is free to be modified. without he or she having to actually click on the component to see. However.length-1.applet.i++) fruitlist. They take up more screen real estate than textfields. } } List List components fulfill much the same functionality as choice components."Banana".applet.length.i<fruit. Font."Pineapple". however. import java. applet.PLAIN. } } CheckBox Medium Pizza Large Pizza Small Pizza Example Source public class CheckboxApplet extends java.*. Consider a simple base class for an Applet that maintains a Thread to automatically update its display at regular intervals. import java.Applet implements ItemListener{ String msg. Unlike threads.setEditable(false).applet. add(option3).awt.Applet Page 164 of 191 .applet. Checkbox option1. option1.Applet { public void init() { TextArea display=new TextArea(10. option2 = new Checkbox("Medium Pizza"). and resume it when started again. Checkbox option3.setState(true). option3 = new Checkbox("Small Pizza"). we would like an applet to cease its nonessential activity when it is stopped. display. public class UpdateApplet extends java. add(option1). } ThreadingApplets Applets are embeddable Java applications that are expected to be able to start and stop themselves on command.*. display. add(display). public void init() { option1 = new Checkbox("Large Pizza"). display. UpdateApplet handles the basic starting and stopping behavior as shown below. A Java-enabled Web browser normally starts an applet when the applet is displayed and stops it when the user moves to another page or scrolls the applet out of view.Font.6). Checkbox option2. applets can be started and stopped any number of times. In general.applet. add(option2).COREJAVA import java.setText(" This is a test and interesting too").12)).setFont(new Font("Monospaced". public class TextAreaApplet extends java. When UpdateApplet's start() method is called. It has two other public methods: start() and stop(). These are methods of the Applet class that are overridden. 25 ). 10. and to indicate to UpdateApplet's start() method that the thread is gone.awt.COREJAVA implements Runnable { private Thread updateThread. updateThread.sleep( updateInterval ). we shouldn't have to check for the existence of updateThread in start() With UpdateApplet is a simplest clock applet with just a few lines of code. Setting updateThread to null serves both to allow the garbage collector to clean up the dead Thread object. } } Page 165 of 191 . updateThread = null.drawString( new java. } catch (InterruptedException e ) { } repaint(). UpdateApplet kills its thread each time the applet is stopped and recreates it if the applet is restarted.util.toString(). an Applet's start() and stop() methods are guaranteed to be called in sequence. As a result.start(). When our applet is subsequently stopped. These start() and stop() methods are called by the Java environment to tell the applet when it should and should not be running.Date(). } } public void stop() { if ( updateThread != null ) { updateThread. Figure shows the Clock. public class Clock extends UpdateApplet { public void paint( java. } } } UpdateApplet is a Runnable object that alternately sleeps and calls its repaint() method. int updateInterval = 1000. we kill the thread by invoking its stop() method and throw away the reference by setting it to null. In truth. public void run() { while ( true ) { try { Thread.Graphics g ) { g. We then create one to begin our execution.stop(). } } public void start() { if ( updateThread == null ) { updateThread = new Thread(this). we first check to make sure there is no currently executing updateThread. UpdateApplet illustrates an environmentally friendly way to deal with threads in a simple applet. The method is called by the Java environment when the applet is going to be removed (often from a cache). What's new here is the destroy() method. otherwise it assumes that the thread has been suspended. It provides a place where we can free up any resources the applet is holding. The new start() method creates the thread and calls start() if updateThread is null. UpdateApplet: public void start() { if ( updateThread == null ) { updateThread = new Thread(this). say a user scrolls our applet out of view.util. so it calls resume(). In our destroy() method. The Clock applet provides a good example of a simple thread.Date(). updateThread. However. Now we have no way of ensuring that the user will bring the applet back into view before moving on to another page.stop(). } public void stop() { updateThread. and if it does. imagine a case where a button-click in one applet could update a Page 166 of 191 . } } These modifications change UpdateApplet so that it suspends and restarts its updateThread. The applet's stop() method simply suspends the thread by calling suspend(). public void destroy() { if ( updateThread != null ) { updateThread. rather than killing and recreating it. And actually. } else updateThread. updateThread = null.start(). we'd really like to make sure we call resume() at a later date. The problem with applets is that we have no control over how a user navigates Web pages. or we'll end up leaving the thread hanging in permanent suspense. Inter AppletCommunication The button component was used to add items to the list component. This is another method that UpdateApplet inherits from the Applet class.toString() sequence simply creates a string that contains the current time.resume(). the same situation would occur if the user simply moves on to another page and never comes back. For example.suspend(). we check to see that the thread exists. so just putting a call to resume() in the applet's start() method won't work. All of these operations occurred inside a single applet.COREJAVA Figure: The clock applet The java. and we use suspend() to suspend the applet. This is the perfect place to cut the suspense and clean up after our thread. But we have no way of knowing if the applet will ever be restarted. we call stop() to kill it and set its reference to null. If we call suspend(). • • Swing and Threads . Using the component model. Possibilities of Inter-Applet Communication There are several interesting possibilities that will be available when applets are truly enabled to communicate among themselves. the applet could potentially be dropped onto a Visual Basic form or used to communicate with applications written in other programming languages. Here are possible types of communication: • Applets that share the same Web page within the same browser • Applets loaded in completely different browser windows • Applets loaded on different client's browsers • Applets loaded from different servers Using a technology such as Java Beans or ActiveX will also allow developers to "wrap" their applets with code that will expose an applet's methods and properties in some standardized way.starting up Page 167 of 191 .4 (!) Part of JFC Java Foundation Classes (compare now defunct MFC) Swing and the AWT • • • • • • AWT = abstract windows toolkit (cross platform) AWT = earliest version of Java GUI eg Frame AWT not JFrame Swing Most Swing components are 'lightweight' Do not mix AWT and Swing Use Swing Swing and threads • • • A thread is a lightweight process Most Swing components are not thread-safe Solution is to make sure all code that creates and modifies Swing components executes in the same 'event-dispatching' thread Start a Swing application using the following code.COREJAVA database and trigger update messages to another applet running within the same Web page or even running on a remote computer. This type of communication is known as inter-applet communication.. JavaSwing What is Swing? • • • A group of 14 packages to do with the UI 451 classes as at 1. Try this out . } LayoutManagers • • • • Most Swing UIs utilise a LayoutManager to control positioning of items There is a choice of these which work in different ways Initially we do without one.. frame.30. // << method to start it } }).start with last example and put this in CreateandShowGUI() Responding to user actions Page 168 of 191 .invokeLater(new Runnable() { public void run() { createAndShowGUI().").300.setBounds(20. and position items ourselves: frame. Absolutepositioning JFrame frame = new JFrame("I am a JFrame"). frame.setVisible(true). 200.setBounds(20. JLabel label = new JLabel("Hello World"). //Display the window.setVisible(true). frame. //Add a label. 20.setDefaultCloseOperation(JFrame. butt.EXIT_ON_CLOSE).pack().setLayout(null). JFrame frame = new JFrame("Hi. frame.20). frame. frame.add(butt). frame.getContentPane().setLayout(null).COREJAVA public static void main(String[] args) { SwingUtilities. frame.setDefaultCloseOperation(JFrame. frame.100). JButton butt=new JButton("Click me").EXIT_ON_CLOSE).add(label).getContentPane(). } CreateAndShowGUI private static void createAndShowGUI() { //Create and set up the window. JButton and JLabel Instantiate application object Set to be the listener of the button Page 169 of 191 .COREJAVA • Based on an event-handling model • New component eg a button should have a Listener specified • The Listener object is programmed to respond to Event objects coming from the component • The Listener object needs to implement the appropriate interface Interfaces • An interface is a set of methods • eg the ActionListener interface has just one method public void actionPerformed(ActionEvent e) • A class can declare that it implements it eg public class Main implements ActionListener • Then it must actually define the methods in that interface • Or the compiler will complain • Classes can implement multiple interfaces Buttonclickdemo • • • • • • • See source code in Word JButton and JLabel clickCounts remembers the number of clicks Class implements ActionListener Make JFrame. motif. all must link to actionPerformed How to know which button was clicked? Use the .java. else label.setText("Butt1 clicked"). .setText("Butt2 clicked")..COREJAVA Which button? • • • If have several buttons.getSource()==butt1) label. . } Setting a laf try { UIManager. butt2 = new JButton("Button 2"). public void actionPerformed(ActionEvent e) { if (e.getSource method of the ActionEvent object Example which button butt1=new JButton("Button 1").setLookAndFeel( "com. Page 170 of 191 .swing.sun.MotifLookAndFeel" )..plaf. for (int i=0.setDefaultLookAndFeelDecorated(true).getInstalledLookAndFeels().set laf as first step try . because could fail UIManager is in java.JFrame JApplet JDialog general purpose containers panel scroll pane split pane tabbed pane Page 171 of 191 . JFrame. This in main() . call JFrame constructor Swing has a lot of classes 1.COREJAVA } catch (Exception e) { System. i<a.out. JFrame frame = new JFrame().out.. catch.println("Cant get laf").println(a[i])..lang Findinginstalledlafs Object a[]= UIManager.length.controls User I/O widgets eg JButton Containers top level containers .containers things that hold other things eg JFRame 2. ... } . i++) System. myPanel. frame. JPanel • Is a subclass of JComponent • So are all the other Swing components except the top-level containers • You can add a border • And a tool-tip Tooltipandborder Page 172 of 191 .25)). frame. JFrame frame = new JFrame("I am a JFrame"). frame.setDefaultLookAndFeelDecorated(true).setBackground(new Color(255.100).setDefaultCloseOperation(JFrame.setBounds(20.setContentPane(myPanel).300. frame.setOpaque(true). frame. //Create a panel JPanel myPanel = new JPanel().3. //Make it the content pane.setVisible(true).COREJAVA tool bar JPanel( in createAndShowGUI) JFrame.30. myPanel.EXIT_ON_CLOSE).setLayout(null). textArea). app.textArea = new JTextArea("Type here". myPanel. set as content pane Make and add text field Add actionlistener Make and add a label Program actionPerformed JTextArea JPanel myPanel = new JPanel().COREJAVA JTextField • • • For single-line text input Methods getText.5. TextArea expands rows and columns as needed Page 173 of 191 . triggered when Enter pressed Example of JTextField • • • • • • • See source in Word doc Check Main object fields for label and textfield Make a panel. setText Can use ActionListener.add(app. 20). getValue() Page 174 of 191 . 20). JScrollPane scrollPane = new JScrollPane(textArea). frame. JScrollBar See source code JScrollBar and JLabel Constructor arguments implements AdjustmentListener adjustmentValueChanged e.setContentPane(scrollPane).COREJAVA JScrollPane JTextArea textArea = new JTextArea("Type here".5. getContentPane().add(app. groupPanel.100.setBounds(10. groupPanel.createLineBorder(Color.. • See source code Page 175 of 191 .60).add(app.10.choice2). groupPanel.black)).COREJAVA JCheckBox • • • See source code implements ActionListener isSelected() RadioButton • • • • • • Come in groups – only 1 selected per group See demo code Make radiobuttons Make group Add radiobuttons to group ActionListener RadioButtongroupborder . ListBox . frame.. JPanel groupPanel = new JPanel().choice1). groupPanel.setBorder(BorderFactory.add(groupPanel). .COREJAVA • • • • Data held in array List box shows array List box inside scroll pane myList.getModel().getElementAt(. LayoutManagers Page 176 of 191 . getContentPane().5)). i++) frame. Menus Page 177 of 191 .setDefaultLookAndFeelDecorated(true). i<10.pack(). frame. frame. frame.setLayout(new GridLayout(4.EXIT_ON_CLOSE).3.setDefaultCloseOperation(JFrame. JFrame frame = new JFrame("Grid").COREJAVA Grid JFrame.getContentPane(). for (int i=0. frame.setVisible(true).5.add(new JButton(""+i)). . • • • • • JComponents have a paint() method This is called by the system when it needs to display the object Initially and eg after a re-size You can over-ride paint() to control the appearance of the component This implies you sub-class the component Page 178 of 191 . JMenuItem item = new JMenuItem("Exit"). myMenuBar. . frame is BorderLayout ..COREJAVA Main app = new Main().add(butt1).. frame. public void actionPerformed(ActionEvent e) { System.setJMenuBar(myMenuBar). menu1.exit(0). JButton butt1 = new JButton(new ImageIcon("icon. . item. toolBar. frame. } JToolBar .. .addActionListener(app).gif")).. BorderLayout. JMenu menu1 = new JMenu("File"). ..add(toolBar. JMenuBar myMenuBar = new JMenuBar().add(menu1). JToolBar toolBar = new JToolBar("Test").PAGE_START).add(item). COREJAVA • • • The paint method has a Graphics object as a parameter This is a context eg color. myPanel = new MyPanel().drawLine (0.getWidth()/2. } MyPanel myPanel. } public class MyPanel extends JPanel { public void paint(Graphics g) { g.setOpaque(true).drawString ("Hello". g. setDefaultCloseOperation(EXIT_ON_CLOSE).180).230. font etc You tell the Graphics object to show things public class MyFrame extends JFrame { public MyFrame() { super("Some title").getHeight()).0. setBounds(20. myPanel.30.getHeight()/2). setContentPane(myPanel). setVisible(true).getWidth(). } } ------------------* * * *----------------- Page 179 of 191 . List The Features of Java? Simple Architecture-neutral Object-oriented Portable Distributed High-performance Interpreted Multithreaded Robust Page 180 of 191 .COREJAVA Viva Questions 1. COREJAVA Dynamic Secure 2.What is Byte code? Java compiler translates a Java program into an intermediate language called Java bytecodes-the platform-independent codes interpreted by the Java interpreter. 3.What are he various applications of Java? Applets Networking Internationalization Security Object serialization Java Database Connectivity (JDBC) 4.Why do Java is called Plat Form Independent? Java is called platform independent language because 100% Pure Java programs are compiled into machine-independent bytecodes, they run consistently on any Java platform Explain the Structure of Typical Java Program? Documentation section Package statement Import statement Interface Statements Class definitions Main Method Class { Main Method Definition } 5.What is Branching? When a program breaks the sequential flow and jumps to another part of the code ,it is called branching. 6.What is a Conditional and Unconditional Branching? When the branching is based on a particular condition, it is known as conditional branching. If branching takes place without any decision, it is known as unconditional branching. 7.What is the use of Switch statement? The switch statement tests the value of a given variable against a list of case values and when a match is found,a block of statements associated with that case is executed. 8.What are the Control Statements Available in Java? While The general syntax of the while statement is: Page 181 of 191 COREJAVA while (expression) { statement } …………………………………………………………………………………………………… ………………….. do-while The general syntax of the do-while is: do { statement(s) } while (expression); …………………………………………………………………………………………………… …………………….. for The general form of the for statement can be expressed like this: for (initialization; termination; increment) { statement } What are the Decision-Making Statements are Available in Java? The if/else Statements the simple form of if can be written like this: if (expression) { statement(s) } if (response == OK) { // code to perform OK action } else { // code to perform Cancel action } The switch Statement switch(expression) { case value1 : statements; break; case value 2 : statements; break; case value 3 : statements; break; default : } What is the use of “? :” Operator? It is used for making two-way decisions,it is a combination of ? and : ,and three operands. This operator is known as ternary operator. What is the Encapsulation?What is the Role in Object Oriented Programming? Encapsulation provides the ability to hide the internal details of an object from its users. The outside user may not be able to change the state of an object directly. Encapsulation is Page 182 of 191 COREJAVA implemented using the access modifier keywords public, private and protected. The concept of encapsulation is also known as data hiding or information hiding. Define Abstraction? Abstraction is one of the object-oriented concepts; it is nothing but expresses the essential things not much in detail. What is the Inheritance? Inheritance is the process by which one object acquires the properties of another. Define Polymorphism? Polymorphism is a feature that allows one interface to be used for ageneral class of action. What is Unicode? Java use Unicode to represent a character. Unicode defines a fully international character set that can represent all of the characters found in all human languages. What is Scope and LifeTime of variables in Java? The variable has the scope only with in the block, where it is declared. They are created when their scope is entered, and destroyed when their scope is left. What do you Mean by Casting? Conversion of data into one type to another type is known as casting. They are classified into two types explicit casting and implicit casting. Explicit casting – two incompatible types need explicit conversion (target-type) value Implicit casting – it is also known as automatic type conversion . When the two types are compatible that is the destination type is larger than the source type automatic type conversion will be tack place. What will be the output of the following statement (A= 64;)? System.out.println(A<<2) 64- 0100 0000 64<<2-0001 0000 0000=256. What will be the output of the following statement (A= 64;)? System.out.println(A<<2) 64- 0100 0000 64>>2-0000 1000=8 What is the Use of Break Statement? A Java(TM) programming language keyword used to resume program execution at the statement immediately following the current statement. If followed by a label, the program resumes execution at the labeled statement. What is the Use of Continue Statement? A Java(TM) programming language keyword used to resume program execution at the end of the current loop. If followed by a label, "continue" resumes execution where the label occurs. What is the Use of Transient Keyword? A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included. 141. Write short note on isAlive(). How we can get size of an Array? The size of an array can be get by using the statement arrayname.length Page 183 of 191 Software objects are often used to model real-world objects you find in everyday life. String and StringBuffer. Define Class & Object? A class is prototype. Class methods affect the class as a whole. An object is a software bundle of related variables and methods. Java supports the following access specifier Page 184 of 191 . Also called a static method.reference? In the case of call-by-value only the copies of the parameter are passed. Class variables are defined in class definitions. Define Class Variable? A data item associated with a particular class as a whole--not with particular instances of the class. Also called a field. What is the Wrapper Class? An object that encapsulates and delegates to another object to alter its interface or behavior in some way. All the primitive data types has it is own wrapper class. So that changes made to the parameter has no effect on the argument used to call it. What is Garbage Collection? When there is no more reference to an object is found jvm collect the memory automatically.COREJAVA Why two classes are used to handle String in java? The Java platform provides two classes. This process is known as Garbage Collection. What is an Access Specifier? A member of a class can be accessed is determined by the access specifier. What is an Instance of a class? Any item of data that is associated with a particular object. that defines the variables and the methods common to all objects of a certain kind. In the case of call-by-reference a reference to the argument is passed to the parameter. with different signature. What is a destructor and how it is implemented in java? The destructor is invoked when an object is destroyed. you use string buffers when you know that the value of the character data will change. that store and manipulate strings-character data consisting of more than one character. The StringBuffer class provides for strings that will be modified. not a particular instance of the class. And also used to hide the instance variable. What is the difference between call-by-value and call–by. In java a mechanism called finalization is used to handle the destructor. You typically use string buffers for constructing character data dynamically. What is the Use of “this” keyword? ‘this’ keyword can be used to represent the current object. The String class provides for strings whose value will not change. So that changes made to the parameter change the argument used to call it. Each instance of a class has its own copy of the instance variables defined in the class. Also called a static field. What is a Static Method? A method that is invoked without reference to a particular object. It needs to override a method called protected void finalize() What is Method Overloading? Two or methods with in the same class have the same name. One base class and one derived class. More specifically: a final class cannot be subclassed. Write short notes on final key word? A Java(TM) programming language keyword. There is no explicit need to destroy objects in java. Finalization is a mechanism provided by java to allow an object to perform some action when it is destroyed. simply define the finalize() method. then you might want to make sure these resources are freed before a object is destroyed. that object is assumed to be no longer needed. That is defining one method with same name and signature. and therefore can never be instantiated. You define an entity once and cannot change it or derive from it later.COREJAVA public private protected What do you mean by garbage collection? Why do we need finalize() method? Deallocation of memory allocated dynamically for an object is done automatically in java. Abstract method is a method that has no implementation. When no reference to an object exists.a sub class derived from another sub class Hierarchical inheritance – two or more sub class have the same base class Define Method Overriding? Providing a different implementation of a method in a subclass of the class that originally defined the method. The technique that accomplishes this is called garbage collection. By using finalization. Private signifies that the method or variable can only be accessed by other elements of Page 185 of 191 . The garbage collection occurs sporadically during the execution of your program. private and protected? Public signifies that the method or variable can be accessed by elements residing in other classes. For eg if an object is holding some non-java resource such as a file handle or window character font. a final method cannot be overridden and a final variable cannot change from its initialized value. we can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. Distinguish between public. Define Abstract class and Method? A class that contains one or more abstract methods. To add a finalizer to a class. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods. and the memory occupied by the object can be reclaimed. The general form is: protected void finalize() { //finalization code here } List out Various types of Inheritance? Simple inheritance . Multilevel inheritance . which must be supported.. public class Circle extends Graphic implements Draggable { . programmers bundle groups of related classes and interfaces into packages. if there is one. or classes in the same package. Define Subclass? Sub class is a class that is derived from a particular class. subclasses. Define Interface? An interface is a named collection of method definitions (without implementations). A subclass is a class that extends another class. whereas an abstract class can. And all the data members are static final members. What are the difference between the abstract class and interface? An interface cannot implement any methods. A Java(TM) programming language keyword used to access members of a class inherited by the class in which it appears. in any and all compatible implementations..java and puts the Circle class in the graphics package: package graphics. and to control access. All the methods declared in the interface are abstract methods by default. Define a Package? A package is a collection of related classes and interfaces providing access protection and namespace management. Unrelated classes can implement the same interface Page 186 of 191 . } To import a specific member into the current file. A class can implement many interfaces but can have only one superclass. to avoid naming conflicts. import graphics. What do you mean by Core Packages? The required set of APIs in a Java platform edition.Circle. An interface can also declare constants. the following code appears in the source file Circle.COREJAVA its class. perhaps with one or more classes in between. perhaps with one or more classes in between. The specification of how a programmer writing an application accesses the behavior and state of classes and objects. What do you mean by API? Application Programming Interface. put an import statement at the beginning of the file before any class or interface definitions but after the package statement. For example. What is super class and what is the use of super keyword? A class from which a particular class is derived. To make classes easier to find and to use. How a Package is created in Java? To create a package and put a class or an interface in it. Protected signifies that the method or variable can only be accessed by elements residing in its class. A subclass inherits state and behavior from all of its ancestors. An interface is not part of the class hierarchy. put a package statement at the top of the source file in which the class or the interface is defined. Secured. It is class file. byte code requires JVM What is new feature in control statements comparing with C/C++? Labeled break and labeled continue are new What are new features in basic features comparing with C/C++? Data types: All data types on all machines have fixed size. robust. high performance. To declare a class that implements an interface.obj file directly understood by machine. Strings are classes in Java (Arrays are classes) What are length and length( ) in Java? Both gives number of char/elements. identity and behavior.COREJAVA How is an interface used in Java? A class that implements an interface adheres to the protocol defined by that interface. They are Simple. so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. Object is real world entity which has state. Portable. both are machine understandable codes No. length is variable defined in Array class. Class is collection of objects. Class gives the general structure for objects. What is Java? Java is an object oriented programming language Is Java invented for Internet? No. .obj file in C? Yes. it was developed for programming towards tiny devices What is byte code? It is machine understandable code and targeted for JVM (Java Virtual Machine). Constants: final is used to declare constant Boolean Type: boolean is new data type in Java which can store true/false There are no structures/unions/pointers Is String data type? No. A class can implement more than one interface (the Java platform supports multiple inheritance for interfaces). What is object? Object is an instance of class. include an implements clause in the class declaration. architecture neutral. What is encapsulation? Encapsulation is packing of data with their methods Page 187 of 191 . dynamic. length( ) is method defined in String class What is class? Class is blue print for objects. What is JVM? Java Virtual Machine which accepts java byte code and produces result What are java buzzwords? Java buzzwords explain the important features of java. interpreted etc. Is byte code is similar to . similar methods of super class are hidden What is overloading? Same method name can be used with different type and number of arguments (in same class) What is overriding? Same method name. Extracting the features of super class Why inheritance is important? Reusability is achieved through inheritance Which types of inheritances are available in Java? Simple. Possible by dynamic method dispatch What is dynamic method dispatch? When you assign object of sub class for the super class instance. Hierarchical and Multilevel Can we achieve multiple inheritances in Java? With the help of interfaces we can achieve What is interface? Interface is collection of final variables and abstract methods (We need not give final and abstract keywords and By default they are public methods) What is the difference between class and interface? Class contains implemented methods. but interface contains non-implemented methods What is polymorphism? Multiple (poly) forms (morphs) Same instance can respond different manners is called polymorphism Can we achieve run time polymorphism in Java? Yes. run time polymorphism achieved through overriding Page 188 of 191 .COREJAVA What is abstraction? Abstraction is the process of identification of essential features of objects What is data hiding? Implementation details of methods are hidden from the user What is hierarchy? Ordering of classes (or inheritance) What is inheritance? Extending an existing class is called inheritance. What is the difference between overloading and overriding? Overloading related to same class and overriding related sub-super class Compile time polymorphism achieved through overloading. Sub class methods override the super class methods. similar arguments and same number of arguments can be defined in super class and sub class. also called as dynamic polymorphism. *.awt. What is exception? Abnormal termination of program is called exception Page 189 of 191 . for. import java.g.*.awt.COREJAVA What is keyword? Java reserved word which should is not used as variable/class-name (e.: parseInt method of Integer class) What is abstract keyword? Used for creating abstract class.: break.awt. package.event.awt.package. while etc) What is final keyword? Used before variables for declaring constants Used before methods for preventing from overriding Used before class-name for preventing from inheritance What is static keyword? Used before variable for defining shared variables Used before method for defining class-level methods. This doesn't imports other packages defined in java.g. class which doesn't have any instance What is this keyword? To call current class variables and current class methods we can use this key word What is this( )? Used for calling another constructor of current class What is super keyword? To call super class variables and super class methods we can use super key word What is super( )? Used for calling of super class constructor and it should be first executable statement in sub class constructor What is package? Package is collection of classes and interfaces How to define package? By using package keyword before the definition of class What is CLASSPATH? It is an environment variable which is used for defining the location of class files What is jar? Jar stands for Java archive files.? Import all the classes and interfaces in the java. these methods can be called without creating objects (e.* given? Yes. compressed set of class files and can be used in CLASSPATH What is the meaning of import java. if.* doesn't imports event package defined in java. Is it necessary to give import java..awt. when already import java.awt. package.awt. throws and finally What is the difference between throw and throws keywords? throw keyword is used for invoking an exception (For raising) throws keyword lists exception names which can be ignored from the method execution What is the difference between final and finally? final is used for defining constants finally is used for executing code after completion of exception handler What is catch( ) block? Exception handler that controls abnormal termination of program Can we have multiple catch( ) blocks? Yes. but first sub class exceptions should be handled What happen is we not handle sub class exception first? Generates compile time error saying that unreachable code is defined in the program Multithreading Section What is thread? Thread is a part of process. throw. stand alone program frames can also display graphics What is the relation between java and Internet? With the help of java applets. join( ). setPriority( ). running. catch. wait. we can write programming for Internet Page 190 of 191 . setName( ). also called as light weight process What is multithreading? Simultaneous execution of threads is called multithreading What is a process? Program under execution is called process How to create thread? By creating instance of Thread class or implementing Runnable interface Can you name any methods of Thread class? currentThread( ).COREJAVA What is exception handler? A method which controls abnormal termination of program What are the keywords used for exception handling? try. isAlive( ) What is join( ) method of Thread? Combines two or more threads running process and wait till their execution is completed What are the states in Thread Life Cycle? Ready. getPriority( ). getName( ). dead What is an applet? Applet is a java program which runs via java-enabled browser Is graphics possible only in applets? No. block. awt Which package is required to write Applets? Java. Page 191 of 191 .COREJAVA Which package is required to write GUI (Graphical User Interface) programs? Java. MouseListener What is the method available in ActionListener Interface? public void action performed(AcitonEvent e) How to pass parameters to Applets? By using PARAM tag.applet What is an event? A kind of action What is event handling? A procedure which gives functionality for the events How to implement event handling? By using interfaces like ActionListener.
Copyright © 2024 DOKUMEN.SITE Inc.