Java Unit-2 One Shot Marathon Notes
Java Unit-2 One Shot Marathon Notes
FileOutputStream outputStream = new ieoutputstrean(outputee | String data =(Hello, won // Write data to the file = ZPytell bytes = data.getBytes(); // Convert string to byte array outputStream.close(); // Closs the Stream } — 5 “atch (IOException e) { ——e.printStackTrace(); 238Java Programming by VikasSir Example of reading files with byte streams: import java.io.FileInputStream;_ import java.io.lOException;_— ublic class ByteStreamReadExample { _Bublic static void main(Stringl] args) { try{ _// Create a FileInputStream FileInputStream inputStream = new FileinputStrearp(“input.txt”); ) vy, _ // Read data from the file ars, int data; tee ae while ((data=inputStream.read0) =I); pore out.printin((char)data ); // convert byte to char and print. inputStream.close(); } eure (IOException e) { e.printStackTrace(); ynJava Programming by Vikassir = Character Stream: * Character streams in Java are represented by the abstract classes Reader and Writer. — * These classes define the@ssential mathodslfor readingandwriting _character data, and several subclasses provide specialized implementations for various sources and destinations, like files, buffers, endimare. Reader Class Members it read(): Reads a singl¢ character/from the input stream and returns it Casaninteger./_ buf}; Reads characters into an array; Returns the number of characters read.Java Programming by VikasSir . oe .. Ab i * int read(char{] cbuf, int off, int len): Reads up to len characters into a portion of an array starting at the specified offset off Returns the + long skip(loifg n): Skips n characters in the input stream. Returns the actual number of characters skipped. uU————_s u + GooteanfnarkSupported(): Returns true if the(mark(|and(reset() fnethods are supported by this stream. = _Astye > # Isc> rid reset(): Repositions the stream to thi ition it was at when mark() was last called-— | * void close(): Closes the stream associated with it. releases any system resourcesJava Programming by Vikassir = Writer Class Members __— ovoid write(int c): Writes a single character to the output stream. Void write(char[] cbuf): Writes the characters from the specified array to the output stream. a write(String str, int off, int len): Writes a portion of a string (starting at offset off and length len) to the output stream. Goi flush): Flushes the output stream, forcing any buffered output characters to be written out to theunderlyin; ream. _xzyoid close(): Closes the stream and releases any system resources associated with it. Also flushes the stream before closing._Java Programming by VikasSir ifference between byte stream & character stream S.No. Aspect | C Byte Streams Character Stream: Used for handling binary | Used for handling textual 1. Purpose —| data like image, audios, data, such as(strings of videos etc characters.) Handle characters, 2. | Handling Data | Handle(raw binary data] | automatically encoding and decoding them — 3. Data Type | DAlwith bytes(Binary _A@eal with Characters Data) (textual data)Java Programming by Vikassir = S.No. | Aspect Byte Streams Character Streams Automatic encoding and N i i 4. | Encoding i eae = oe nBOr | decoding using specified jecoding of aka character encoding. / 5 Ria Suitable for handling non- Suitable for handling 7 textual dater ‘Textual data) 6 Efficienc: Less efficient for text-based. More efficient for text : ¥ operations~ based opsrstiGns.Thread in Java: * In Java, a thread is afightweight process Ehat allows concurrent execution of code * Java supports multithreading, which is the ability to run multiple threads simultaneously, allowing programs to perform tasks in parallel. * This is particularly useful for tasks that can beexecuted independently] like handling multiple client requests in a server or performing background computations without blocking the main application flow. Significance/importance of thread in concurrent programming: ‘Concurrency: Threads enable concurrent execution of tasks withina Java application. eThread in Java: © Multitasking: Threads allow a Java program to perform multiple tasks simultaneously. * Responsiveness : Threads can help ensure that an application remains responsive even when@erform ing time-consuming tasks. * Parallelism: Threads can be used to achieve parallelism, where multiple tasks are executed simultaneouslyon multi-core processors.) Asynchronous programming: Threads facilitate asynchronous pene ee certain tasks to execute independently of the main program flow. * Resource sharing: Threads can share resources such as memory, files, and network connections within the same process_Java Programming by VikasSir Thread Life Cycle in Java: * In Java, a thread goes through several states from its creation to its termination. These states are collectively known as the "Thread Life Cycle." Yew (Born): * When a thread is(created usii eyword| but has not yet started, it is in the "New" state. The thread has been instantiated but thd start()/method has not been called yet. ial Runnable: * When theGtart() method is called(on a thread, it moves from the "New" state to the "Runnable" state~ * In this state, the thread is ready to run and is waiting for Feu time.Running: * When a thread from the "Runnable" state is selected by the thread schedulerjto execute, it moves into the "Running" state. * This is when the thread's run() method is ee New Thread. resume) notify¢] Idle Thread (Not runnable) ThreadBlocked (Non-Runnable): * Athread enters the "Blocked" state when it is alive but unable to run due to some conditio: * Common feieoen ites waiting for_1/O operations to complete, waiting to _acquire a lock, or waiting for another thread toyetease a resource] — Waiting: 7 * Athread enters the "Waiting" state when it is waiting indefinitely for another thread to perform a particular action (e.g., calling notify() or notifyAll() on a lock that the thread is waiting for). Terminated (Dead)p 7 * Athread enters the "Terminated" state when it ha Finished executingjits run() method. Once a thread is in this state, it cannot be restarted. SS* In Java, a thread can be created in two main ways: — A. Extending the(hread class] * You can create a class that extends the (Thread classhnd overrides the(rund)] method. * The run() method contains the code that will be executed in the(new thread] example: Zi u class MyThread extends Thread { public void run() { System.out, printinThis is anew thread." GP a public class (Mai —Public static void rae ingl] args) { MyThread my Thread = ridw néw MyThread(y~ myThread.start0);}} —implementing the Runnable interfac * You can create a class that implements the Runnable interface And overrides the Gant metho) od. 7 7 + Then, you can create an instance of Thread and pass an instance of your class toits —— example: yy _class MyRunnable impi¢mentdunnebtalt public void run() { System.out.printin("This is a new thread."); pub Maint seul lic static void eee args) { iw Thread(new MyRunnable()); twa start; nyDifference between threads and processes: S Aspect Thread Process A thread is the smallest unit of execution within a process. A process is an independent program in execution with its own memory space. Memory Threads share the same memory space within a process. Each process has its own separate memory spgser— Communication Communication between threads is easy and fast since they share the ‘Communication between processes requires inter-process communication (IPC) mechanisms, _ which are more complex and slower.Difference between threads and processes: Aspect Thread Process Threads are generally lighter and Processes are heavier and take more Creation faster_to create. e and resources to create. Threads within a process are Processes are independent of each Dependency | depen ach other and share : other, with their own resources. the process's resources. nasi Threads share the resources of the | Each process has its own resources . parent process (e.g., file handles, Allocation memory). and does not share them with other processs®Difference between threads and processes: S Aspect Thread Process Multiple threads within the same | Multiple processes can also execute Execution concurrently, but they are Isolated process can execute concurrently. | Soncurrently, from each other, Ifa thread crashes, it may affect the | Ifa process crashes, it does not Crash Impact entire process, directly affect other processes. Threads are used for tasks that require parallel execution within the Procesems sts lieed for niniing Use Case eek separate applications or isolated same application, like handling Multiple requests ina server. tasks that require full independence.Synchronization in java: * Thread synchronization in Java is a way td control the access)of multiple threads to shared resourcesito avoid conflicts and ensure data consistency. — * Java provides theynchronized keywordko achieve thread synchronization. When a method or a block of code is marked as synchronized, only one thread€an execute that code at a time. * Other threads trying to access the same(code will be blocked until the first thread finishes * This synchronization is implemented in Java with a concept called monitors or locks.* There are two synchronizations in Java mentioned below: (A.) Process Synchronization. (B.) Thread Synchronization. Process Synchronization in Java: * Process Synchronization is a technique used to(coordinate the execution o It ensures that the shared resources/are safejand in “order. Jee aT 4 Fr 7 z Thread Synchronization in Jav: * Thread Synchroniz: execution of the threads in a mult lg 3* There are two types of thread synchronization are mentioned below: * Mutual Exclusive —_ * Cooperation (Inter-thread communication in Java) Synchronized Block: public void myMethod() { synchronized (this) { // 'this' refers to the current object // Code that needs to be Ee } i }S Thread Prio! + Every Java thread has a(fhread priorit) (from MIN_PRIORITY to MAX_PRIORITY) that helps the operating system determine the order in eee which threads are scheduled. * Itis represented as integer value ranging from 1 to 10, — * By default, every thread is given priority NORM PRIORITY(constant of()) © The minimum priority that a thread can have, with afvalue of 1) * The maximum priority that a thread can have, with a(falue of 10] (0 Ly? y “Oe@