Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [...

22
Serializaon Serializaon is a mechanism of converng the state of an object into a byte stream. Deserializaon is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is plaorm independent. So, the object serialized on one plaorm can be deserialized on a different plaorm. To make a Java object serializable we implement the java.io.Serializable interface. Only the objects of those classes can be serialized which are implemenng java.io.Serializable interface. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote. It is mainly used to travel object's state on the network (known as marshaling). Reflecon Reflecon is a mechanism which allows to get the informaon or use the informaon. Using reflecon we can get informaon about an object, about a class or about an interface. Reflecon is commonly used by programs which require the ability to examine or modify the runme behavior of applicaons running in the Java virtual machine.” This concept is oſten mixed with introspecon. Java Reflecon makes it possible to inspect classes, interfaces, fields and methods at runme, without knowing the names of the classes, methods etc. at compile me. It is also possible to instanate new objects, invoke methods and get/set field values using reflecon. Java Reflecon is quite powerful and can be very useful. For instance, Java Reflecon can be used to map properes in JSON files to geer / seer methods in Java objects, like Jackson, GSON, Boon etc. does. Or, Reflecon can be used to map the column names of a JDBC ResultSet to geer / seer methods in a Java object. Java Reflecon provides ability to inspect and modify the runme behavior of applicaon. Reflecon in Java is one of the advance topic of core java. Using java reflecon we can inspect a class, interface, enum, get their structure, methods and fields informaon at runme even though class is not accessible at compile me. We can also use reflecon to instanate an object, invoke it’s methods, change field values. Annotaon Annotaon is Metadata. Metadata is data about data. So Annotaons are metadata for code. ava Annotaon is a tag that represents the metadata i.e. aached with class, interface, methods or fields to indicate some addional informaon 1 | Page Core Java

Transcript of Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [...

Page 1: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

SerializationSerialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.

The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform. To make a Java object serializable we implement the java.io.Serializable interface. Only the objects of those classes can be serialized which are implementing java.io.Serializable interface. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote. It is mainly used to travel object's state on the network (known as marshaling).

Reflection Reflection is a mechanism which allows to get the information or use the information. Using reflection we can get information about an object, about a class or about an interface. Reflection is commonly used by programs which requirethe ability to examine or modify the runtime behavior of applications running in the Java virtual machine.” This concept is often mixed with introspection.

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. Java Reflection is quite powerful and can be very useful. For instance, Java Reflectioncan be used to map properties in JSON files to getter / setter methods in Java objects, like Jackson, GSON, Boon etc. does. Or, Reflection can be used to map the column names of a JDBC ResultSet to getter / setter methods in a Java object.Java Reflection provides ability to inspect and modify the runtime behavior of application. Reflection in Java is one of the advance topic of core java. Using java reflection we can inspect a class, interface, enum, get their structure, methods andfields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values.

Annotation Annotation is Metadata. Metadata is data about data. So Annotations are metadata for code. ava Annotation is a tag thatrepresents the metadata i.e. attached with class, interface, methods or fields to indicate some additional information

1 | P a g e C o r e J a v a

Page 2: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

which can be used by java compiler and JVM. Annotations can be used to generate source code from, or be accessed at runtime via reflection.Annotations in java are used to provide additional information, so it is an alternative option for XML and java marker interfaces. Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose. Java annotations were added to Java from Java 5. Annotations have a number of uses, among them:Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.Runtime processing — Some annotations are available to be examined at runtime..

Web service architecture & IntroductionModern day business applications use variety of programming platforms to develop web-based applications. Some applications may be developed in Java, others in .Net, while some other in Angular JS, Node.js, etc.Most often than not, these heterogeneous applications need some sort of communication to happen between them. Since they are built using different development languages, it becomes really difficult to ensure accurate communication between applications. Here is where web services come in. Web services provide a common platform that allows multiple applications built on various programming languages to have the ability to communicate with each other.

As you can see in the figure, java, .net or PHP applications can communicate with other applications through web service over the network. For example, java application can interact with Java, .Net and PHP applications. So web service is a language independent way of communication.Types of Web ServicesThere are mainly two types of web services.SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard protocol for designing and developing web services. REST: REST is an architectural style for developing web services.

What is WSDLWeb Services Description Language (WSDL)WSDL stands for Web Services Description Language. It is the standard format for describing a web service. WSDL was developed jointly by Microsoft and IBM. WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special datatypes used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL.Features of WSDL

WSDL is an XML-based protocol for information exchange in decentralized and distributed environments. WSDL definitions describe how to access a web service and what operations it will perform. WSDL is a language for describing how to interface with XML-based services. WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide

business registry. WSDL is the language that UDDI uses.

2 | P a g e C o r e J a v a

Page 3: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

In Java Web Development World, WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. A WSDL document defines services as collections of network endpoints, or ports.

What is multithreadingMultithreading in java is a process of executing multiple threads simultaneously. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time.A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread. Threads are lightweight sub-processes, they share the common memory space. In Multithreaded environment, programs that are benefited from multithreading, utilize the maximum CPU time so that the idle time can be kept to minimum. Java Multithreading is mostly used in games, animation etc,Advantages of Java Multithreading1) It doesn't block the user because threads are independent and you can perform multiple operations at same time.2) You can perform many operations together so it saves time.3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life cycle of threadA thread can be in one of the following states:NEW – A thread that has not yet started is in this state.RUNNABLE – A thread executing in the Java virtual machine is in this state.BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.TIMED_WAITING – A thread that is waiting for another thread to perform an action for up to a specified waiting time is inthis state.TERMINATED – A thread that has exited is in this state.A thread can be in only one state at a given point in time.

What are Java Threads?A thread is a:

Facility to allow multiple activities within a single process Referred as lightweight process A thread is a series of executed statements Each thread has its own program counter, stack and local variables A thread is a nested sequence of method calls Its shares memory, files and per-process state

Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or by instantiating classes that extend the Thread class.

Synchronizing - Thread in javaWhen we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threadstry to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Synchronization is the way to make our program safe. Synchronization is the safe mechanism for memory leakage problem. In which we can modify one thread to complete another thread's process and then executes other. Synchronization control the access the multiple threads to a shared resources.

3 | P a g e C o r e J a v a

Page 4: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Zipping unzippingJava provides the java.util.zip package for zip-compatible data compression. It provides classes that allow you to read, create, and modify ZIP and GZIP file formats. It also provides utility classes for computing checksums of arbitrary input streams that can be used to validate input data. Also includes classes for compressing and decompressing data using the DEFLATE compression algorithm, which is used by the ZIP and GZIP file formats. The overall concept is quite straight forward

Read file with "FileInputStream" Add the file name to"ZipEntry" and output it to "ZipOutputStream"

What is network SerializationWhen building a client – server based application, we need to send objects between the client and the server applications. And java provides two great mechanisms to achieve this: Object Serialization and Sockets. The client application: will connect to the server and pass objects to the server. The passed objects will contain a String which the user entered on the console. The server application: will echo the messages back to the client. We can transfer a Serialized object via network because Java serialized object remains in form of bytes which can be transmitted via network. We can also store serialized object in Disk or database as Blob. The primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. After a serialization object has been written into a file, it can be read from the file and deserialized. Most important point is that the entire process is JVM independent, an object can be serialized on one platform and deserialized on an entirely different platform. Serialization make is easier for object to travel over a network connection.

What an App needs to achieve network communicationTo communicate over a network, we need to know three things; name of the machine, port number through which we want to carry out the communication and the underlying set of the agreed upon rules i.e. a protocol. Machine name internally gets mapped into Internet Protocol Addresses i.e. IPAddress. Port number is able to distinguish between different applications running on a machine. To distinguish one from the other, we need port number. There are protocols in a network communication about how to send a request from our application to the application running on other side of the network.

Networking programming model.The Network programming model always involves the two machines; one is client and another is server. Communication will always happen between client and server. Client will send the request and server will send the response to that request. These services include e-mail, newsgroups, file transfer, remote login, and the Web. Internet services are organized according to a client/server architecture. Client programs, such as Web browsers and file transfer programs, create connections to servers, such as Web and FTP servers. The clients make requests of the server, and the server responds to the requests by providing the service requested by the client. Java supports Network Programming so we can make such program in which the machines connected in network will send and receive data from other machine in the network by programming. The first and simple logic to send or receive any kind of data or message is we must have the address of receiver or sender. So when a computer needs to communicate with another computer, it`s require the other computer’s address. Java networking programming supports the concept of socket. A socket identifies an endpoint in a network. The socket communication takes place via a protocol. Most modern network programming is based on a client/server model.

How does the HTTP works?HTTP is the protocol that is used by web servers and browsers to communicate. HTTP is based on a request and a response.

4 | P a g e C o r e J a v a

Page 5: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Usually, the protocol is "http". To retrieve a document via HTTP the browser transmits the following request to the server: "GET /request-URI HTTP/version", where version tells the server which HTTP version is used. The moment the response is received. There are different types of HTTP request that we can send. Most common HTTP requests are GET and POST. GET is used for getting a file from a Web server. If we wish to fill up a form and submit it to a particular websitethen we would be required to make a POST request. There are other requests like OPTIONS, HEAD, PUT, DELETE. Likewise, when a response is send back from a server to a client, response is come back in several different forms. It might come back in the form of some file that we request for downloading or in the form of HTML + JavaScript response or ActiveX control or Java Applet.

HTTP HeadersHTTP headers are the core part of these HTTP requests and responses, and they carry information about the client browser, the requested page, the server and more.

HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon ':',HTTP header fields provide required information about the request or response, or about the object sent in the message body. There are four types of HTTP message headers:General-header: These header fields have general applicability for both request and response messages.Client Request-header: These header fields have applicability only for request messages.Server Response-header: These header fields have applicability only for response messages.Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.

HTTP & FTP Download Name of the package is networking and import java.io.*, java.net.* and java.util.*. HttpDownload is the class name within which we have main( ). We define static final int BUF_SIZE = 100. Inside main( ), we define a variable u of the type URL. Then we say u = new URL ( "http://quest.ksetindia.com/dl/myfile.zip" ). Then we try to open the HttpConnection by using u.openConnection( ). Once the connection has been established, a request will be send. Once the request is send, we will try to check the response code to figure out whether the request has been made was successfully accepted and the response was returned to us. If the status code is HttpURLConnection.HTTP_OK means the request is successful. If it is successful then we got to download the file. To carry out the downloading of the file, we will call a function downloadFile( ) which is user-defined function. To this function we pass getInputStream( ) means the connection object will have within itself a InputStream where we can extract the file from where we can read the bytes to that stream. Bytes from myfile.zip file. We will also create one more URL object u = new URL ( "ftp://quest.ksetindia.com/pub/myftp.zip" ) and this time we had given FTP URL. myftp.zip file we wish to download from a pub directory. Once again we call downloadFile( ) and pass to it u.openStream( ) and myftp.zip. myftp.zip is a localfilename. u.openStream( ) will not only create the FTP connection, it will also make a request to download myfile.zip or myftp.zip. For both HTTP and FTP downloads, we make use of common function downloadFile( ). openStream( ) also returns the InputStream which we can use for reading.

What is MD5MD5 is a type of algorithm that is known as a cryptographic hash algorithm. MD5 produces a hash value in a hexadecimalformat. MD5 (technically called MD5 Message-Digest Algorithm) is a cryptographic hash function whose main purpose is

5 | P a g e C o r e J a v a

Page 6: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

to verify that a file has been unaltered. Instead of confirming that two sets of data are identical by comparing the raw data, MD5 does this by producing a checksum on both sets, and then comparing the checksums to verify that they're thesame. he MD5 function is a cryptographic algorithm that takes an input of arbitrary length and produces a message digest that is 128 bits long. The digest is sometimes also called the "hash" or "fingerprint" of the input. MD5 is used in many situations where a potentially long message needs to be processed and/or compared quickly. The most common application is the creation and verification of digital signatures. MD5 is a good solution for security. JAVA developer may try to quote MD5 algorithm but is very complicated and therefore Java standard edition SE6 has a built in support for MD5 algorithm and is in package of Java.Security in class Message Digest.

Then why do we need Collections Framework?All three of these collections viz, Vector, Hashtable, array have different methods and syntax for accessing members: arrays use the square bracket ([]) symbols, Vector uses the elementAt method, and Hashtable uses get and put methods. These differences have forced programmers to implement their own inconsistent collections - some imitate the Vector access methods and some imitate the Enumeration interface. To make it worse, most of the Vector methods are marked as final; that is, you cannot extend the Vector class to implement a similar sort of collection. We could create a collection class that looked like a Vector and acted like a Vector, but it couldn't be passed to a method that takes a Vector as a parameter. Finally, none of the collections (array, Vector or Hashtable) implements a standard member access interface. When programmers develop algorithms (like sorting) to manipulate collections, what object should be passed to the algorithm - is it an array or a Vector or implement both interfaces? A lot of such questions pop up.

What are Generics?The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects. Generics is a feature of the Java Language that promotes type safety, code manageability and efficiency and, most importantly, much cleaner and reduced code. You can use generics to create typesafe collections with no boxing and un-boxing overhead; this is also known as parametric polymorphism.Advantage of Java GenericsThere are mainly 3 advantages of generics. They are as follows:Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.Type casting is not required: There is no need to typecast the object. Before Generics, we need to type cast. After Generics, we don't need to typecast the object.Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

Why Use Generics?In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.Code that uses generics has many benefits over non-generic code:Stronger type checks at compile time - A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.Elimination of casts - When re-written to use generics, the code does not require casting:Enabling programmers to implement generic algorithms - By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

Arraylist collectionArraylist class implements List interface. It is widely used because of the functionality and flexibility it offers. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays. ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null. The issue with arrays is that they are of fixed length so if it is full you cannot add any more elements to it, likewise if

6 | P a g e C o r e J a v a

Page 7: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink. On the other ArrayList can dynamically grow and shrink after addition and removal of elements. Apart from these benefits ArrayList class enables us to use predefined methods of it which makes our task easy.orArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. ArrayList inherits AbstractList class and implements List interface. ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if objects are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList cannot be used for primitive types, like int, char, etc. ArrayList in Java can be seen as similar to vector in C++.

TreeSet TreeSet collection is also an ordered collection. TreeSet is going to be sorted in the natural order i.e. if we take integers asan example then they are sorted by value, if we take names then they are sorted alphabetically, if we have dates in a collection then they would be sorted chronologically. Duplication of items never happens in the TreeSet collection. Nameof the package is collections and import java.io.* and java.util.*. TreeSet is backed by Set Data structure. TreeSet doesn't allow duplicate elements. TreeSet keeps all elements in the sorted order. TreeSet doesn't provide a way to get the highest or lowest element but since they are in sorted order it's usually the first or last element.

Java inner class or nested classJava inner class or nested class is a class which is declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the members of outer class including private data members and methods. Nested classes are divided into two categories:Static nested class : Nested classes that are declared static are called static nested classes.Inner class : An inner class is a non-static nested class.Advantage of java inner classesThere are basically three advantages of inner classes in java. They are as follows:1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.3) Code Optimization: It requires less code to write.

Collections in JavaCollections in java is a framework that provides an architecture to store and manipulate the group of objects.All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections. Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). Collection represents a single unit of objects i.e. a group.

Collection Types There are different types of collections that can exist; ordered collection, indexed collection and a mapping collection. The ordered collection is one in which input / output is order based. Means we cannot insert an element in the middle ofa stack or a queue. Stack is a Last-In-First-Out collection whereas Queue is a First-In-First-Out collection. The collection can be indexed based. Example of this is an ArrayList and a Vector collection. Means based on the index value, we decideto insert an element. If we want to retrieve a value from an ArrayList at position 5 or we may want to set a value at position 2, then this type of operation is indexed based rather than order based. Third type of collection is a mapped collection where input / output is based on a key. Example of this is a HashTable and TreeMap. This always contains a key/ value pairs. For this particular key, this is a value. We insert using a key and retrieve also using a key.

Vector

7 | P a g e C o r e J a v a

Page 8: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Vector implements a dynamic array. The Vector class implements a growable array of objects. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. It extends AbstractList and implements List interfaces. Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand automatically when new data is added to them. It is similar to ArrayList, but with two differences −

Vector is synchronized. Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program.

Iterator Iterator is used for iterating (looping) various collection classes such as HashMap, ArrayList, LinkedList etc. Iterator took place of Enumeration, which was used to iterate legacy classes such as Vector.

Expectations From An IO System When we write to a file or read from a file, we should be able to communicate in multiple ways. We must be able to readthe data sequentially or we must be able to access the data randomly from a file. If we have a file which contains records of 100 different employees and we want to read the record of 50th employee then sequential access will not be effectivebecause we have to read first 49 records and then the 50th record. So at that time random access of a file is effective which allows to jump directly to the 50th record. We should also be capable of dealing with underlying file system. For example, in any file system there would be files and folders. We should be able to go through different files and folders that are there. We should also be able to get the path for a particular file. We must also be able to check whether we have an access permissions to that file or access permissions to that folder. Means read, write and execute permissions we must be able to figure out. In addition to that we must have a facility to figure out at what different dates and times were the files accessed, created or modified.

Java I/O Java I/O (Input and Output) is used to process the input and produce the output.Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for inputand output operations.We can perform file handling in java by Java I/O API.StreamA stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow.In java, 3 streams are created for us automatically. All these streams are attached with console.1) System.out: standard output stream2) System.in: standard input stream3) System.err: standard error stream

IO StreamJava performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical.Java encapsulates Stream under java.io package. Java defines two types of streams. They are,Byte Stream : It provides a convenient means for handling input and output of byte.Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

Byte stream

8 | P a g e C o r e J a v a

Page 9: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Byte stream classes are used to perform reading and writing of 8-bit bytes. Streams being unidirectional in nature can transfer bytes in one direction only, that is, either reading data from the source into a program or writing data from a program to the destination. Therefore, Java further divides byte stream classes into two classes, namely, InputStream class and OutputStrearn class. The subclasses of InputStrearn class contain methods to support input and the subclasses of OutputStrearn class contain output related methods.

Character streamOne of the limitations of byte stream classes is that it can handle only 8-bit bytes and cannot work directly with Unicode characters. To overcome this limitation, character stream classes have been introduced in java.io package to match the byte stream classes. The character stream classes support 16-bit Unicode characters, performing operations on characters, character arrays, or strings, reading or writing buffer at a time. Character stream classes are divided into two stream classes namely, Reader class and Writer class.Reader ClassesReader classes are used to read 16-bit unicode characters from the input stream. The Reader class is the superclass for all character-oriented input stream classes. All the methods of this class throw an IOException.Writer ClassesWriter classes are used to write 16-bit Unicode characters onto an outputstream. The Writer class is the superclass for allcharacter-oriented output stream classes .All the methods of this class throw an IOException.

What Are PackagesA java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because softwarewritten in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.Advantage of Java Package

Java package is used to categorize the classes and interfaces so that they can be easily maintained. Java package provides access protection. Java package removes naming collision.

Split packages

9 | P a g e C o r e J a v a

Page 10: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

'Split packages' is an old Java term where two packages having the same name exist in different libraries/applications. Java 9 does not allow split packages in different modules for the reason of the reliable configuration. This restriction is even applied to the packages which are not exported. Only unnamed modules are exempted from this restriction.examplePlugin A” and “Plugin B”, where “Plugin A” contained the main functionality and “Plugin B” was providing some library functions. So naturally “Plugin A” depended on “Plugin B”. Though not intentional, both plugins ended up having a package with the same name “SplitPackage”. A “Class A” in “SplitPackage” in “Plugin A” had a method call on “Class B” in “SplitPackage” in “Plugin B”.

What Are InterfacesAn interface in java is a blueprint of a class. It has static constants and abstract methods.The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class. To declare an interface, use interface keyword.interface <interface_name>{ // declare constant fields // declare methods that abstract // by default.}There are mainly three reasons to use interface. They are given below.

It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

10 | P a g e C o r e J a v a

Page 11: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Bow and Arrow classIn this game we had a set of balloons which used to travel from bottom of the screen towards the top of the screen and they used to move at top at a fixed time interval. Then we have a guy called Robin who holds a bow and a arrow and the moment we hit the Enter key, from the bow an arrow used to get shot out and aim of Robin is to shoot down as many balloons as he can. So as the balloons move up, we cannot keep Robin as fixed. Robin has to reach at the height of the balloon and then shoot out the arrow. So Robin also can be moved up and down. We have to maintain different positionsof Robin and different positions of different balloons.We can think of having a Shooter class, a Balloon class and a Timer class. Within the Shooter class we have methods like setstep( ) and move( ).A possible solution that we can make is a Person class, Timer class and a Target class. Because in place of balloon there might be any other object and in place of one shooter there can be multiple shooters. Then we create a Shooter class which we derive from the Person as well as the Timer class and create a class called Balloon which we derive from the Timer and the Target class

What is dynamic dispatch mechanismRuntime Polymorphism or Dynamic method dispatchDynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred determines which version of overridden method will be called.

Abstract class in JavaA class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. Abstract class in java is similar to interface except that it can contain default method implementation. An abstract class can have abstract method without body and it can have methods with implementation also. Abstract keyword is used to create a abstract class and method. We can run abstract class in java like any other class if it has main() method.Example abstract classabstract class <class name>{//Code

}refer note from book

Derived classA derived class is a class created or derived from another existing class. The existing class from which the derived class is created through the process of inheritance is known as a base class or superclass.

ExceptionException is the abnormal condition which occur during the execution of a program and interrupts the normal flow of the program. It is one of the powerful mechanism to handle the runtime error.

Type of Exception

11 | P a g e C o r e J a v a

Page 12: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Java’s exceptions can be categorized into two types: Checked exceptions Unchecked exceptions

Checked exceptionsThese are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. Checked exceptions are subject to the catch or specify a requirement, which means they require catching or declaration. A checked exception is an exception which the Java source code must deal with, either by catching it or declaring it to be thrown. Checked exceptions are generally caused by faults outside of the code itself - missing resources, networking errors, and problems with threads come to mind. These could include subclasses of FileNotFoundException, UnknownHostException, etc.Unchecked ExceptionsUnchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.

Checked Exception Unchecked Exception

CE are the exceptions which requires to be handled at compile time

UE are those exceptions which are not require to be handled at compile time

All classes that inherit from class Exception but not directly or indirectly from class RuntimeException

All exception types that are direct or indirect subclasses of RuntimeException are UE

These exception are typically caused by conditions whichare not under control of program These are caused by defects in programs code.

CE are also known as compile time exceptions UE are also know as Run Time Exceptions

We can create custom exception by extending java.lang.Exception class

By extending Runtime exception we can create custom exception

CE are propagated using throws keyword UE are automatically propagated

How to handle the exceptionException handling in Java is made possible through the use of some keywords like try, catch, throw, throws, and finally. These keywords are used to manage how exceptions are thrown and handled.Any piece of code that might cause an exception to be thrown is written in a try block. Code that might throw an exception usually deal with input values, which are not guaranteed to always be the way the programmer wants.Imagine a baby that tries to walk. You simply put your hands around the baby to ensure that the baby does not fall and injure themselves. In the same way, the try block is used to surround code that might throw an exception while running.A try block is followed immediately by a catch block or a finally block or both.

12 | P a g e C o r e J a v a

Page 13: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

A catch block does exactly what its name says: it catches an exception thrown in the try block. Since a number of exceptions can be thrown, the catch block must specify the class of exception it is handling.Beyond a catch block, there is the finally block, which simply works when the try block is done. So, the finally block waits for the try block to execute. Note that a try block can be followed by a catch block or a finally block or a combination of both. If the try block has a catch block, finally runs after the catch, otherwise the finally block runs immediately after the try block.Exceptions in the Error or RuntimeException and their subclasses need not be included in the throws statement. They areclassified as Unchecked Exceptions, which are exceptions that should be prevented in any way possible and must not be consciously allowed to occur.The number of Unchecked Exceptions that can occur in a program are so enormous that we cannot throw all the Unchecked Exceptions in a method. It would cause the method to lose its clarity, so Java assumes that a programmer running a program does not intentionally throw these type of exceptions.Every method is already liable of throwing unchecked exceptions when something goes wrong, so no need to add unchecked exceptions in the throws statement.

Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwableis checked.

User define exceptionUser Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’keyword. This can be done by extending the class Exception. There is no need to override any of the above methods available in the Exception class, in your derived class. But practically, you will require some amount of customizing as peryour programming needs. The keyword “throw” is used to create a new Exception and throw it to the catch block. Java custom exceptions are used to customize the exception according to user need. By the help of custom exception, you canhave your own exception and message.

Exception Etiquette • Create a public static variable in class and anytime an exceptional condition arises we try to set different values in this global variable which is a public static variable of some class. • Force the method to return a Boolean value indicating the success or failure of that function. Also return int or a string or an object to indicate the success or failure of that function. • Catch the exception and if we do not catch the exception, an error occurs. We write a catch block and completely ignore the exception which is a bad way. • Do not use exception handling only for cosmetic purpose. • Do not catch everything using Exception. • Always try to distinguish between types of exceptions. • Make it optimally elaborate – not too much, not too little.

BankException Class BankException class is derived from the Exception class. Inside this class we have two private integers acc and bal. We need these because anytime the BankException object is constructed we pass this account number and balance to it. Wealso have a inform( ) method inside it. In the inform( ) method, we are going to display the account number as well as thebalance where the transaction failure had occurred. From the client when we try to call a method which we anticipate will throw an exception then either we got to catch that exception or throw it further

13 | P a g e C o r e J a v a

Page 14: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

What is the purpose of the finally block Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. A finally block must be associated with a try block, you cannot use finally without a try block. You should place those statements in this block that must be executed always.

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. The Main purpose of Finally Block is to close all the files that are opened in the code or any databases in the code .Here(in Finally Block)we write code to close all databases ,files etc.The Finally Block will Execute Whether there is an Exception or not. the finally block will ALLWAYS be executed, no matterwhat not just if an exception was not caught.

How to catch multiple exceptionsn Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multipleexceptions and they have similar code, then using this feature will reduce code duplication. If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it. We can combine the multiple exceptions in catch block using Pipe (|) Operator. The byte code generated by this feature is smaller and reduce code redundancy. he two exceptions SQLException and IOException are handled in the same way, but you still have to write two individual catch blocks for them. In Java 7 you can catch multiple exceptions using the multi catch syntax. when an exception occurs, the specific catch block (that declares that exception) executes. At a time only single catch block can be executed. After the execution of catch block control goes to the statement next to the try block. At a time Only single exception can be handled. All the exceptions or catch blocks must be arranged in order. All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception

Java rethrow exceptionAnother improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration. in rethrow method, catch block is catching Exception but it’s not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block. The Java SE 7 compiler performs more precise analysis ofrethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

What are ways to Prevent Inheritance in Java Programming?There are 2 ways to stop or prevent inheritance in Java programming. By using final keyword with a class or by using a private constructor in a class. Using final keywordUsing final keyword before a class declaration we can stop a class to be inherited by other classes. For example,

14 | P a g e C o r e J a v a

Page 15: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

public final class A{

}If we try to extend the class A which is final, compiler will flash an error i.e.“The Type B cannot the subclass the final Class A”, if class B is trying to extend final class A.By making a class constructor private:We can also stop a class to be extended/inherited by other classes in Java by making the class constructor private.If we make the class constructor private we’ll not be able to create the object of this class from outside of this class. But, our purpose is to just prevent a class to be inherited and not to stop object creation. Hence, we need a method that can create an object of this class and return it.

What is ContainershipContainership is basically type of hierarchy. It can also be called containment hierarchy. Containership is the ability of a class to contain objects of different classes as member data. For example, class A could contain an object of class B as a member. Here, all the public methods (or functions) defined in B can be executed within the class A. Class A becomes thecontainer, while class B becomes the contained class. Containership is also referred to as Composition. In this example, it can be said that class A is composed of class B. In OOP, Containership represents a “has-a” relationship. It is important to note that, even though the container has access to execute all the public methods of the contained class, it is not able to alter or provide additional functionality. When it comes to a real world programming problem, an object of class TextBox may be contained in the class Form, and thus can be said that a Form contains a TextBox (or alternatively, a Form is composed of a TextBox).

Reuse Mechanisms Reuse can be done using two different mechanisms, one is Inheritance and another is Containership.

Bitwise complement operator ~Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.35 = 00100011 (In Binary)Bitwise complement Operation of 35~ 00100011 ________ 11011100 = 220 (In decimal)The one's complement operator (~), sometimes called the "bitwise complement" operator, yields a bitwise one's complement of its operand. That is, every bit that is 1 in the operand is 0 in the result. Conversely, every bit that is 0 in the operand is 1 in the result. The operand to the one's complement operator must be an integral type.

What is the Array?An array is a collection of variables of the similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. Array in java is index based, first element of the array is stored at 0 index. Each item in an array is called an element, and each element is accessed by its numerical index.

There are two types of array. Single Dimensional Array

15 | P a g e C o r e J a v a

Page 16: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Multidimensional Array

Jagged Array in JavaJagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays. It is a new feature supported by Java. In Jagged arrays, each row, in a two-dimensional array, may contain different lengths. Let us design a two-dimensional array with 4 rows where the first row contains 4 elements, the second row with 1 element, the third row with 2 elements and the fourth row with 3 elements.Following is the schematic representation of the array.

Jagged arrays in java are arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. Jagged arrays in java sometimes are also called as ragged arrays.

Needs of ArrayArrays in Java are the preferred data structure used to store elements of same data type. The advantage with arrays is that their elements can be accessed using index number which makes performing sorting, searching, fetching and other preferred operations on those elements(in arrays) very fast. Arrays generally store homogeneous data i.e same type of data in consecutive memory locations which will help us to fetch data in constant access time. Arrays are used to store data in sequential way. It allows easy access on the basis of index or position. Like all the students in class have roll numbers which help to maintain records and easy access and manipulation

Main properties of arrays in Java:1. Arrays are objects.2. Arrays are created dynamically (at run time).3. Arrays may be assigned to variables of type Object.4. Any method of the Object class may be invoked on an array.5. An array object contains a sequence of variables.6. The variables are called the components or elements of the array.7. If the component type is T, then the array itself has type T[].8. An array type variable holds a reference to the array object.9. The component type may itself be an array type.10. An array element is a component whose type is not an array type.11. An element’s type may be either primitive or reference.12. The length of an array is its number of components.13. An array’s length is set when the array is created, and it cannot be changed.14. An array’s length can be accessed as a public final instance variable.15. Array index values must be integers in the range 0...length 1.16. An ArrayIndexOutOfBoundsException is thrown if Property 15 is violated.17. Variables of type short, byte, or char can be used as indexes.18. Arrays can be duplicated with the Object.clone() method.19. Arrays can be tested for equality with the Arrays.equals() method.

16 | P a g e C o r e J a v a

Page 17: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

20. Array objects implement Cloneable and java.io.Serializable.

Two Dimensional Array in JavaThe Two Dimensional Array in Java programming language is nothing but an Array of Arrays. If the data is linear we can use the One Dimensional Array but to work with multi-level data we have to use Multi-Dimensional Array.Two Dimensional Array in Java is the simplest form of Multi-Dimensional Array. In Two Dimensional Array, data is stored in row and columns and we can access the record using both the row index and column index (like an Excel File).

Selection sort AlgorithmSelection sort is one of the simplest sorting algorithms. It is similar to the hand picking where we take the smallest element and put it in the first position and the second smallest at the second position and so on. The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array. In the selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that value into its proper location. The basic idea is to look at each element in the array, and for each element look at all remaining elements to see if there is something smaller that should be in this position. If there is, exchange the two values.

Bubble Sort AlgorithmBubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Bubble sort, also referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm getsits name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

17 | P a g e C o r e J a v a

Page 18: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Singleton Class in JavaA Singleton class is a class that can have only one object (an instance of the class) at a time. After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined. Saves memory because object is not created at each request. Only single instance is reused again and again. Provide a global point of access to the object. There are twoforms of singleton design pattern

Early Instantiation: creation of instance at load time. Lazy Instantiation: creation of instance when required.

Need for a Singleton classThe Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets. The purpose of singleton is to control object creation by keeping private constructor. Singleton pattern is mostly used in multi-threaded and database applications. It is used in logging, caching, thread pools, configuration settings etc.

Finalize( ) Method • finalize( ) method is called whenever an object is about to be destroyed. • The actual destruction of the object is not done by the finalize( ) method, it will be done by the Garbage Collector. • The finalize( ) method is used to free non-Java resources like file handle of a font. • The finalize( ) method is called by Java-Runtime just before the garbage collection and it is defined as protected void finalize( ) { //finalization code }

18 | P a g e C o r e J a v a

Page 19: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

• The finalize( ) method will not be called just because when an object goes out of scope. It is called just before the Garbage Collector destroys that object.

Garbage collectionGarbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management. Main objective of Garbage Collector is to free heap memory by destroying unreachable objects. The programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects. Garbage collector is best example of Daemon thread as it is always running in background. The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing.Advantage of Garbage CollectionIt makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Define Stack A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end. This end is commonly referred to as the “top.” The end opposite the top is known as the “base.”The base of the stack is significant since items stored in the stack that are closer to the base represent those that have been in the stack the longest. The most recently added item is the one that is in position to be removed first. This ordering principle is sometimes called LIFO, last-in first-out. It provides an ordering based on length of time in the collection. Newer items are near the top, while older items are near the base.Many examples of stacks occur in everyday situations. Almost any cafeteria has a stack of trays or plates where you take the one at the top, uncovering a new tray or plate for the next customer in line. Imagine a stack of books on a desk (Figure 1). The only book whose cover is visible is the one on top. To access others in the stack, we need to remove the ones that are sitting on top of them. When we insert data into a stack, it is placed at the head of a queue. This means that when we remove data, it will be in reverse order. Adding 1,2,3,4 will return 4,3,2,1. Stacks aren't the most frequentlyused data structure, but they are extremely useful for certain tasks.

321

4321

Figure 1.1 Stack before push operation, and stack after

4321

321

19 | P a g e C o r e J a v a

Page 20: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Figure 1.2 Stack before pop operation, and stack after

Considering this reversal property, you can perhaps think of examples of stacks that occur as you use your computer. For example, every web browser has a Back button. As you navigate from web page to web page, those pages are placed on a stack (actually it is the URLs that are going on the stack). The current page that you are viewing is on the top and the first page you looked at is at the base. If you click on the Back button, you begin to move in reverse order through the pages.Explain the Properties of Stack• Stack is used for storing not only local variables but also in Stack addresses of different functions goes. • Whatever goes into Stack works very fast i.e. recycling of elements can happen very fast in Stack. • Contents of the Stack can be kept in Cache memory which is a high speed memory. • Caching adds to the efficiency of the Stack because we can access elements on the Stack faster. • Whatever goes into Stack, actually occupies only as much memory as it deserves to occupy. • Creation of elements in the Stack is very fast. There is special register called Extended Base Pointer ( EBP ) which alwayspoints to the base of the Stack. From there onwards calculate the offset in which a new variable would get stored.

Explain the Properties of Heap • Objects are always created in the Heap. The nameless object that we would create using new always goes into Heap • There is no size barrier to how big an object we create. As much as Heap memory is available to us that big an object we can easily create. • Heap is slow because recycling of elements in the Heap is take time. The objects that have gone to the Heap have to bephysically eliminated from memory whenever we give up the object. Whenever we do not want to use the object, the object is removed from the Heap. • Cashing is done in Heap but it was not as effective as it was in case of Stack because objects in a Heap are not guaranteed to be in adjacent locations. • Whatever we create on Heap will always occupy more space than it deserves to occupy. Whenever we create an object on Heap, on the Stack we have to create the reference to that object i.e. if the object needs 50 bytes then the reference would need at least 4 bytes in the Stack. So an object occupies more space. • Creation of object always happens at execution time or at runtime, it will take some amount of time. So Heap works slower.

What Is a Queue?A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and theremoval of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and makes its way toward the front, waiting until that time when it is the next element to be removed.The most recently added item in the queue must wait at the end of the collection. The item that has been in the collection the longest is at the front. This ordering principle is sometimes called FIFO, first-in first-out. It is also known as “first-come first-served.”The simplest example of a queue is the typical line that we all participate in from time to time. We wait in a line for a movie, we wait in the check-out line at a grocery store, and we wait in the cafeteria line (so that we can pop the tray stack). Well-behaved lines, or queues, are very restrictive in that they have only one way in and only one way out. There is no jumping in the middle and no leaving before you have waited the necessary amount of time to get to the front.

Difference between class and object

20 | P a g e C o r e J a v a

Page 21: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

Class Object

Class is a data type Object is an instance if class

It generates objects It gives life to CLASS

Does not occupy memory location It occupies memory location

It cannot be manipulated because it is not available in memory

It can be manipulated

One class definition should exist only once in the program For one class multiple objects can be created.Class is a logical entity. Object is a physical entity.Class is declared using class keyword e.g.class Student{}

Object is created through new keyword mainly e.g.Student s1=new Student();

Class is declared once. Object is created many times as per requirement.Class is a group of similar objects. Object is a real world entity such as pen, laptop, mobile,

bed, keyboard, mouse, chair etc.

What is RecursionRecursion in java is a process in which a method calls itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. Java supports recursion. Recursion is a basic programming technique you can use in Java, in which a method calls itself to solve some problem. A method that uses this technique is recursive. Many programming problems can be solved only by recursion, and some problems that can be solved by other techniques are better solved by recursion.One of the classic problems for introducing recursion is calculating the factorial of an integer. The factorial of any given integer — call it n so that you sound mathematical — is the product of all the integers from 1 to n. Thus, the factorial of 5is 120: 5 x 4 x 3 x 2 x 1.The recursive way to look at the factorial problem is to realize that the factorial for any given number n is equal to n times the factorial of n–1, provided that n is greater than 1. If n is 1, the factorial of n is 1.private static long factorial(int n)class Factorial {int fact(int n) { if (n == 1) return 1; else return n * factorial(n-1); }What is Function ? Explain the Types of Function CallsFunction or a method is a named callable piece of code which performs some operations and optionally returns a value.Java is a complete object oriented programming language. This language supports all rules and regulation of object oriented programming language. Function is very important part in our language specification and software development criteria so that using the function model we can develop our programming strategy.Generally this function is of two types, one is predefined function and other is user defined function. User defined function is totally based on the user control and through this control we can develop our own function model and easily set in our commercial project.A Java program is basically a set of classes. A class is defined by a set of declaration statements and methods or functions. The java programming supports different types of function as line User defined function [A function which is created by user so it is known as user defined function.] and also there are some functions available with java system that provides some imperative support to the java programmer for developing their programming logic as well as their programming architecture with very smooth and fine way.Functions are called by their names. Well if the function does not have any arguments, then to call a function you can directly use its name. But for functions with arguments, we can call a function in two different ways, based on how we specify the arguments, and these two ways are:

Call by Value Call by Reference

21 | P a g e C o r e J a v a

Page 22: Serialization - ycmoubca.files.wordpress.com · Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or

ASCII Codes For character A, its ASCII code is 01000001. Likewise, there are codes for B, C, D, E, etc. They are known as standard codes because whenever we hit any key, same code would get generated. So standardization is necessary. It is difficult to remember the binary of any characters. We are not comfortable with binary equivalent of any characters but we are comfortable with decimal. So to remember the ASCII codes, convert them into their decimal equivalent. If A is 65, then B is 66, and so on. Decimal equivalents are commonly known as ASCII values. So ASCII code means binary equivalents whereas ASCII values are their equivalent decimals.

ASCII Values ASCII values of A to Z range from 65 to 90. Similarly ASCII values of a to z range from 97 to 122 whereas digits have ASCII values in the range 48 to 57. The ASCII value range of non-printable characters will range from 0 to 33 whereas graphic character will range from 128 to 255. The ASCII value for Tab is 9, Enter is 13, Escape is 27 and Space is 32. In general, all characters will range from 0 to 255. We are not trying to remember special symbol’s range because it is not a range but a series of range. In the range of 0 to 255, special symbols do not have a particular range but they are distributed in this range and forms series of range. So they form different slots and it is difficult to remember different slots. So as given in the slide, whatever does not fall in any of these ranges, forms a special symbol.

22 | P a g e C o r e J a v a