3-4-Unit-Edited (1).pptx of java for ii b.sc students
asmita26j24
1 views
45 slides
Oct 15, 2025
Slide 1 of 45
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
About This Presentation
unit 3 and 4 of java
Size: 388.24 KB
Language: en
Added: Oct 15, 2025
Slides: 45 pages
Slide Content
Unit 3 and 4
Arrays Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Arrays Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
Arrays
Declaring Array Variables: dataType [] arrayRefVar ; // preferred way. or dataType arrayRefVar []; // works but not preferred way
Declaration of Array- Example double[] myList ; or double myList [];
Creating an array using “new” keyword Array Ref_Var = new datatype [ array_Size ]; It creates an array using new datatype [array Size]; It assigns the reference of the newly created array to the array variable Ref_Var
Declaration and creation of array dataType [] array_Ref_Var = new datatype [ array_Size ]; Example: double[] myList = new double[10];
Example Array Program D :\KPRACS\AY-2024-2025-Odd Sem\BSc_IT-2nd Year\Java\notes\TestArray.java“
Multidimensional array int [][] myNumbers = { { 1 , 2 , 3 , 4 }, { 5 , 6 , 7 } }; int [][] myNumbers = { { 1 , 2 , 3 , 4 }, { 5 , 6 , 7 } }; for ( int i = ; i < myNumbers . length ; ++ i ) { for ( int j = ; j < myNumbers [ i ]. length ; ++ j ) { System . out . println ( myNumbers [ i ][ j ]); } }
Java String In Java , string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char [] ch ={' j','a','v','a','t','p',’r',’ g ',’ r ',’m '}; String s= new String( ch );
Java String class provides many methods to perform operations on strings such as compare(), concat (), equals(), split(), - length(), - replace(), - compareTo (), - intern(), - substring() etc .
What is String in Java? Generally, String is a sequence of characters. But in Java, the string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
public class StringExample { public static void main(String args []) { String s1="java";//creating string by Java string literal char ch []={'s','t','r',' i ',' n','g','s '}; String s2= new String( ch );//converting char array to string String s3= new String("example");//creating Java string by new keyword System.out.println (s1); System.out.println (s2); System.out.println (s3); }}
To check the strings are equal by ignoring case sensitivity Class stingequal { Public Static void main(String[] args ) { String myStr1 = "Hello" ; String myStr2 = "HELLO" ; String myStr3 = "Another String" ; System . out . println ( myStr1 . equalsIgnoreCase ( myStr2 )); // true System . out . println ( myStr1 . equalsIgnoreCase ( myStr3 )); } }
Java Vector Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList , the ArrayList will perform better in such case. The Iterators returned by the Vector class are fail-fast . In case of concurrent modification, it fails and throws the ConcurrentModificationException .
Java Array differs from vectors Vector is synchronized. Java Vector contains many legacy methods that are not the part of a collections framework.
Threads in JAVA Threads are a lightweight subprocess with the smallest unit of processes and separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time).
Life Cycle Of Thread There are different states Thread transfers into during its lifetime. New State Active State Waiting/Blocked State Timed Waiting State Terminated State
Threads Lifecycle
1. New State By default, a Thread will be in a new state, in this state, code has not yet been run and the execution process is not yet initiated.
2. Active State A Thread that is a new state by default gets transferred to Active state when it invokes the start() method, his Active state contains two sub-states namely: Runnable State: In This State, The Thread is ready to run at any given time and it’s the job of the Thread Scheduler to provide the thread time for the runnable state preserved threads. A program that has obtained Multithreading shares slices of time intervals which are shared between threads hence, these threads run for some short span of time and wait in the runnable state to get their schedules slice of a time interval. Running State: When The Thread Receives CPU allocated by Thread Scheduler, it transfers from the “Runnable” state to the “Running” state. and after the expiry of its given time slice session, it again moves back to the “Runnable” state and waits for its next time slice.
3. Waiting/Blocked State If a Thread is inactive but on a temporary time, then either it is a waiting or blocked state. F or example, if there are two threads, T1 and T2 where T1 needs to communicate to the camera and the other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its work, at this state T1 is parked in waiting for the state, and in another scenario, the user called two Threads T2 and T3 with the same functionality and both had same time slice given by Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple threads parked in a Blocked/Waiting state Thread Scheduler clears Queue by rejecting unwanted Threads and allocating CPU on a priority basis.
4. Timed Waiting State Sometimes the longer duration of waiting for threads causes starvation. if we take an example like there are two threads T1, T2 waiting for CPU and T1 is undergoing a Critical Coding operation and if it does not exist the CPU until its operation gets executed then T2 will be exposed to longer waiting with undetermined certainty, In order to avoid this starvation situation, we had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting, each thread has a time period for which sleep() method is invoked and after the time expires the Threads starts executing its task.
5. Terminated State A thread will be in Terminated State, due to the below reasons: Termination is achieved by a Thread when it finishes its task Normally. Sometimes Threads may be terminated due to unusual events like segmentation faults, exceptions…etc. and such kind of Termination can be called Abnormal Termination. A terminated Thread means it is dead and no longer available.
Methods in threads Methods Action Performed checkAccess() Determines if the currently running thread has permission to modify this thread sleep() Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers clone() Throws CloneNotSupportedException as a Thread can not be meaningfully cloned getPriority() Returns this thread’s priority interrupt() Interrupts this thread start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread toString() Returns a string representation of this thread, including the thread’s name, priority, and thread group yield() A hint to the scheduler that the current thread is willing to yield its current use of a processor
How to Create Threads using Java Programming Language? Extending Thread Class Implementing a Runnable interface
1. By Extending Thread Class We can run Threads in Java by using Thread Class, which provides constructors and methods for creating and performing operations on a Thread, which extends a Thread class that can implement Runnable Interface. We use the following constructors for creating the Thread: Thread Thread(Runnable r) Thread(String name) Thread(Runnable r, String name)
import java.io.* ; import java.util .* ; public class GFG extends Thread { // initiated run method for Thread public void run () { System . out . println ( "Thread Started Running..." ); } public static void main ( String [] args ) { GFG g1 = new GFG (); // Invoking Thread using start() method g1 . start (); } }
Multithreaded P rogramming in JAVA Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins. There are certain properties associated with the main thread which are as follows: It is the thread from which other “child” threads will be spawned. Often, it must be the last thread to finish execution because it performs various shutdown actions
Flow diagram of Threading
Example // Java program to control the Main Thread // Importing required classes import java.io.*; import java.util .*; // Class 1 // Main class extending thread class public class Test extends Thread { // Main driver method public static void main(String[] args ) { // Getting reference to Main thread Thread t = Thread.currentThread (); // Getting name of Main thread System.out.println ( "Current thread: " + t.getName ()); // Changing the name of Main thread t.setName ( "Geeks" ); System.out.println ( "After name change: " + t.getName ()); // Getting priority of Main thread System.out.println ( "Main thread priority: " + t.getPriority ());
Example Continue // Class 2 // Helper class extending Thread class // Child Thread class class ChildThread extends Thread { @Override public void run() { for ( int i = ; i < 5 ; i ++) { // Print statement whenever child thread is // called System.out.println ( "Child thread" ); } } // Setting priority of Main thread to MAX(10) t.setPriority (MAX_PRIORITY); // Print and display the main thread priority System.out.println ( "Main thread new priority: " + t.getPriority ()); for ( int i = ; i < 5 ; i ++) { System.out.println ( "Main thread" ); } // Main thread creating a child thread Thread ct = new Thread() { // run() method of a thread public void run() { for ( int i = ; i < 5 ; i ++) { System.out.println ( "Child thread" ); } } }; // Getting priority of child thread // which will be inherited from Main thread // as it is created by Main thread System.out.println ( "Child thread priority: " + ct.getPriority ()); // Setting priority of Main thread to MIN(1) ct.setPriority (MIN_PRIORITY); System.out.println ( "Child thread new priority: " + ct.getPriority ()); // Starting child thread ct.start (); } }
What Are Java APIs? APIs are important software components bundled with the JDK. APIs in Java include classes, interfaces, and user Interfaces. They enable developers to integrate various applications and websites and offer real-time information. The following image depicts the fundamental components of the Java API.
API In java
The Most Commonly Used Java APIs The Most Commonly Used Java APIs API Acronym RESTful API none Web API none Facebook.4j none Twitter.4j none JavaHelp none Java Advanced Imaging JAI Java Data Objects JDO Java Media Frameworks JMF
Exception Handling in Java The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Reference Link: Must Watch https://youtu.be/ohpCMpderow
Types of Exception Handling Exceptions can be categorized into two ways: Built-in Exceptions Checked Exception Unchecked Exception User-Defined Exceptions
Types of Exception
Built-in Exception Exceptions that are already available in Java libraries are referred to as built-in exception . These exceptions are able to define the error situation so that we can understand the reason of getting this error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked exception . Checked Exception Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. The compiler ensures whether the programmer handles the exception or not. The programmer should have to handle the exception; otherwise, the system has shown a compilation error.
Built-in Exception Unchecked Exceptions The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn't handle or declare it, the program would not give a compilation error. Usually, it occurs when the user provides bad data during the interaction with the program.
User-defined Exception In Java , we already have some built-in exception classes like ArrayIndexOutOfBoundsException , NullPointerException , and ArithmeticException . These exceptions are restricted to trigger on some predefined conditions. In Java, we can write our own exception class by extends the Exception class. We can throw our own exception on a particular condition using the throw keyword. For creating a user-defined exception, we should have basic knowledge of the try-catch block and throw keyword .
What is Exception Handling? Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException , IOException , SQLException , RemoteException , etc.
Java Exception Keywords Keyword Description try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
Java Exception Keywords finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.