Used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level systems.
Java was invented by James Gosling and Oracle currently owns it. JDK 23 is the latest version of Java.
Java’s syntax is similar to C/C++.
Popular platforms like LinkedIn, Amazon, and Netflix rely on Java for their back-end architecture, showcasing its stability and scalability across different environments.
Popularity is so high that 3 Billion+ devices use Java across the world.
Java Hello World Program

// A Java program to print “Hello World”
public class GFG {
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}

// Output:”Hello World”

Java Arrays

An array is typically a grouping of elements of the same kind that are stored in a single, contiguous block of memory.https://techzone360.shop/javascript-tutorial/

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

In contrast to C/C++, the length member allows us to obtain the array’s length. We must utilise the sizeof operator in C/C++.PauseNextMute

Current Time 0:34

/

Duration 18:10

Loaded: 8.81%Fullscreen

An object of a dynamically formed class is called an array in Java. Java arrays implement the Serializable and Cloneable interfaces and derive from the Object class. In Java, an array can hold objects or primitive values. Java allows us to create single- or multi-dimensional arrays, just like C/C++ does.

Additionally, C/C++ does not support the anonymous array functionality that Java does.

Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.

Disadvantages

  • Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Single-Dimensional Array in Java

A single-dimensional array in Java is a linear collection of elements of the same data type. It is declared and instantiated using the following syntax:

  1. dataType[] arr; (or)  
  2. dataType []arr; (or)  
  3. dataType arr[];  

Instantiation of an Array in Java

  1. arrayRefVar=new datatype[size];  

Example of Java Array

Let’s see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

  1. //Java Program to illustrate how to declare, instantiate, initialize  
  2. //and traverse the Java array.  
  3. class Testarray{  
  4. public static void main(String args[]){  
  5. int a[]=new int[5];//declaration and instantiation  
  6. a[0]=10;//initialization  
  7. a[1]=20;  
  8. a[2]=70;  
  9. a[3]=40;  
  10. a[4]=50;  
  11. //traversing array  
  12. for(int i=0;i<a.length;i++)//length is the property of array  
  13. System.out.println(a[i]);  
  14. }}  

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated below:

  1. int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let’s see the simple example to print this array.

  1. //Java Program to illustrate the use of declaration, instantiation   
  2. //and initialization of Java array in a single line  
  3. class Testarray1{  
  4. public static void main(String args[]){  
  5. int a[]={33,3,4,5};//declaration, instantiation and initialization  
  6. //printing array  
  7. for(int i=0;i<a.length;i++)//length is the property of array  
  8. System.out.println(a[i]);  
  9. }}  

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

  1. for(data_type variable:array){  
  2. //body of the loop  
  3. }  

Let’s see the example of printing the elements of the Java array using the for-each loop.

Testarray1.java

  1. //Java Program to print the array elements using for-each loop  
  2. class Testarray1{  
  3. public static void main(String args[]){  
  4. int arr[]={33,3,4,5};  
  5. //printing array using for-each loop  
  6. for(int i:arr)  
  7. System.out.println(i);  
  8. }}  

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the Java array to the method so that we can reuse the same logic on any array. When we pass an array to a method in Java, we are essentially passing a reference to the array. It means that the method will have access to the same array data as the calling code, and any modifications made to the array within the method will affect the original array.

Let’s see the simple example to get the minimum number of an array using a method.

Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don’t know. Notice that parent class reference variable can refer the child class object, know as upcasting.

Let’s take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();//we don’t know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be compared, object can be cloned, object can be notified etc.
Pause

Next
Mute
Current Time
0:09
/
Duration
18:10

Fullscreen

object class in java
Methods of Object class
The Object class provides many methods. They are as follows:
Method
Description
public final Class getClass()
returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()
returns the hashcode number for this object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString()
returns the string representation of this object.
public final void notify()
wakes up single thread, waiting on this object’s monitor.
public final void notifyAll()
wakes up all the threads, waiting on this object’s monitor.
public final void wait(long timeout)throws InterruptedException
causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException
causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException
causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable
is invoked by the garbage collector before object is being garbage collected.

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’,’o’,’i’,’n’,’t’};
String s=new String(ch);
is same as:

String s=”javatpoint”;
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Pause

Next
Mute
Current Time
0:09
/
Duration
18:10

Fullscreen

String in Java
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes.

CharSequence in Java
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let’s first understand what String in Java is and how to create the String object.

What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?
There are two ways to create String object:

By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:

String s=”welcome”;
Each time you create a string literal, the JVM checks the “string constant pool” first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new string instance is created and placed in the pool. For example:

String s1=”Welcome”;
String s2=”Welcome”;//It doesn’t create a new instance

Java String
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value “Welcome” in string constant pool that is why it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as the “string constant pool”.
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

2) By new keyword
String s=new String(“Welcome”);//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).

Interfaces and Classes in Strings in Java
In Java, both String and CharBuffer interact with sequences of characters, but they are designed with different use cases and underlying mechanisms in mind. Here’s an exploration of their interfaces, classes, and how they fit into the Java ecosystem.

String
The String class is one of the most fundamental types in Java, designed to represent immutable sequences of characters. Here’s a closer look at its characteristics and the interfaces it implements:

Immutability: Once instantiated, a String object cannot be modified. This immutable design is a deliberate choice to ensure thread safety, consistency, and efficiency, especially regarding the String pool mechanism.
String Pool: Java maintains a pool of string literals to help save memory. When a new string literal is created, Java checks the Pool for a matching string. If found, the new variable references the pooled string. If not, the new string is added to the Pool.
Implemented Interfaces: The String class implements several interfaces, including:
Serializable: Allows string objects to be serialized into byte streams, facilitating their transmission or storage.
Comparable: Enables lexical comparison between two strings, supporting natural ordering within collections.
CharSequence: Provides a unified read-only interface for different kinds of char sequences, allowing String objects to be manipulated and accessed generically.
CharBuffer
CharBuffer, on the other hand, is part of the java.nio package, which provides a set of classes for non-blocking I/O operations. CharBuffer is a mutable sequence of characters with more flexibility for manipulation. Here’s more about CharBuffer:

Mutability and Direct Buffers: Unlike strings, CharBuffer instances can be modified. They can be either heap-based or direct buffers. Direct buffers can offer higher performance, especially for I/O operations, as they are managed outside the Java heap and interact directly with the operating system’s native I/O operations.
Implemented Interfaces: CharBuffer extends the Buffer class and implements the CharSequence, Appendable, Comparable, and Readable interfaces, providing a rich set of functionalities for character sequence manipulation, comparison, and reading operations.
Usage Scenarios: It is particularly useful for reading and writing to channels, regular expressions, and character processing in a more efficient manner, especially when dealing with large datasets or requiring fine-grained control over character data.
CharSequence Interface
Java’s CharSequence interface provides a unified, read-only view of character sequences and is a component of the java.lang package. It facilitates consistent access and manipulation across various types of character sequences, including String, StringBuilder, StringBuffer, and CharBuffer. Through this interface, key functionalities for handling character data are defined, enabling actions like measuring sequence length, accessing particular characters, generating character subsequences, and transforming into a String format. By providing a common blueprint for character sequences, CharSequence enables flexible and implementation-independent text processing across the Java platform.

String
StringBuffer
StringBuilder
String
In Java, the String class encapsulates a series of characters. Once instantiated, a String object’s content is fixed and cannot be modified, attributing to its immutable nature. This immutability ensures that String objects are safe for concurrent use across threads and are optimally performant in situations where the textual content remains constant. To enhance memory efficiency, Java employs a technique called string interning. This approach optimizes the storage and access of commonly utilized string literals.

Syntax:

Direct assignment using string literals:

String str = “Hello, World!”;
Using the String constructor:

String str = new String(“Hello, World!”);
Filename: StringExample.java

public class StringExample {
public static void main(String[] args) {
// Creating a String
String greeting = “Hello”;
// Concatenating strings
String sentence = greeting + “, World!”;
// Using a method from the String class
int length = sentence.length();
System.out.println(sentence); // Output: Hello, World!
System.out.println(“Length: ” + length); // Output: Length: 13
}
}
Output:

Hello, World!
Length: 13
StringBuffer
StringBuffer represents a mutable sequence of characters that ensures thread safety, making it suitable for scenarios involving multiple threads that modify a character sequence. It includes various string manipulation capabilities, including the ability to insert, delete, and append characters. This design avoids the necessity of generating new objects with each change, leading to enhanced efficiency in situations requiring regular adjustments to the string content.

Syntax

StringBuffer sb = new StringBuffer();
Filename: StringBufferExample.java

public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer
StringBuffer sb = new StringBuffer(“Hello”);
// Appending to the StringBuffer
sb.append(“, World!”);
// Inserting into the StringBuffer
sb.insert(5, ” Java”);
// Deleting from the StringBuffer
sb.delete(5, 10);
System.out.println(sb); // Output: Hello, World!
}
}
Output:

Hello, World!

Java String charAt()

The charAt() method is a fundamental tool in Java for accessing individual characters within a string. In this section, we will delve into the intricacies of the charAt() method, exploring its syntax, functionality, and common use cases. The Java String class charAt() method returns a char value at the given index number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.

Syntax

  1. public char charAt(int index)    

The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length.

Specified byPauseNextMute

Current Time 0:14

/

Duration 18:10

Loaded: 5.50%Fullscreen

CharSequence interface, located inside java.lang package.

Internal implementation

The String class in Java represents a sequence of characters stored in a character array (char[]). When we call the charAt(int index) method on a String object, Java retrieves the character at the specified index from this underlying character array.

  1. public char charAt(int index) {    
  2.        if ((index < 0) || (index >= value.length)) {    
  3.            throw new StringIndexOutOfBoundsException(index);    
  4.        }    
  5.        return value[index];    
  6.    }    

Java String charAt() Method Examples

Let’s see Java program related to string in which we will use charAt() method that perform some operation on the give string.

FileName: CharAtExample.java

  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name=”javatpoint”;  
  4. char ch=name.charAt(4);//returns the char value at the 4th index  
  5. System.out.println(ch);  
  6. }}  

Test it Now

Output:

t

We define a string variable name with the value “javatpoint”. Using the charAt() method, we retrieve the character at the 4th index (indexing starts from 0) from the name string. The character is stored in the variable ch. Finally, we print the value of ch using System.out.println().

Let’s see the example of the charAt() method where we are passing a greater index value. In such a case, it throws StringIndexOutOfBoundsException at run time.

FileName: CharAtExample.java

  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name=”javatpoint”;  
  4. char ch=name.charAt(10);//returns the char value at the 10th index  
  5. System.out.println(ch);  
  6. }}  

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Accessing First and Last Character by Using the charAt() Method

Accessing the first and last characters of a string using the charAt() method in Java is a common operation. This method allows developers to retrieve individual characters from a string by specifying their indices. Here’s how we can use the charAt() method to access the first and last characters of a string:

FileName: CharAtExample3.java

  1. public class CharAtExample3 {  
  2.     public static void main(String[] args) {  
  3.     String str = “Welcome to Javatpoint portal”;      
  4.     int strLength = str.length();      
  5.     // Fetching first character  
  6.     System.out.println(“Character at 0 index is: “+ str.charAt(0));      
  7.     // The last Character is present at the string length-1 index  
  8.     System.out.println(“Character at last index is: “+ str.charAt(strLength-1));      
  9.     }  
  10. }  

Output:

Character at 0 index is: W
Character at last index is: l

Print Characters Presented at Odd Positions by Using the charAt() Method

Let’s see an example where we are accessing all the elements present at odd index.

FileName: CharAtExample4.java

  1. public class CharAtExample4 {  
  2.     public static void main(String[] args) {  
  3.         String str = “Welcome to Javatpoint portal”;          
  4.         for (int i=0; i<=str.length()-1; i++) {  
  5.             if(i%2!=0) {  
  6.                 System.out.println(“Char at “+i+” place “+str.charAt(i));  
  7.             }  
  8.         }  
  9.     }  
  10. }  

Output:

Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place
Char at 23 place o
Char at 25 place t
Char at 27 place l

The positions 7 and 21 are empty spaces because they denote the space.

Counting Frequency of a character in a String by Using the charAt() Method

Let’s see an example in which we are counting frequency of a character in the given string.

FileName: CharAtExample5.java

  1. public class CharAtExample5 {  
  2.     public static void main(String[] args) {  
  3.         String str = “Welcome to Javatpoint portal”;  
  4.         int count = 0;  
  5.         for (int i=0; i<=str.length()-1; i++) {  
  6.             if(str.charAt(i) == ‘t’) {  
  7.                 count++;  
  8.             }  
  9.         }  
  10.         System.out.println(“Frequency of t is: “+count);  
  11.     }  
  12. }  

Output:

Java Regex

The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.

It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

java.util.regex package

The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides following classes and interfaces for regular expressions.PauseNextMute

Current Time 0:07

/

Duration 18:10

Loaded: 4.40%Fullscreen

  1. MatchResult interface
  2. Matcher class
  3. Pattern class
  4. PatternSyntaxException class

Matcher class

It implements the MatchResult interface. It is a regex engine which is used to perform match operations on a character sequence.

No.MethodDescription
1boolean matches()test whether the regular expression matches the pattern.
2boolean find()finds the next expression that matches the pattern.
3boolean find(int start)finds the next expression that matches the pattern from the given start number.
4String group()returns the matched subsequence.
5int start()returns the starting index of the matched subsequence.
6int end()returns the ending index of the matched subsequence.
7int groupCount()returns the total number of the matched subsequence.

Pattern class

It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.

No.MethodDescription
1static Pattern compile(String regex)compiles the given regex and returns the instance of the Pattern.
2Matcher matcher(CharSequence input)creates a matcher that matches the given input with the pattern.
3static boolean matches(String regex, CharSequence input)It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.
4String[] split(CharSequence input)splits the given input string around matches of given pattern.
5String pattern()returns the regex pattern.

Example of Java Regular Expressions

There are three ways to write the regex example in Java.

  1. import java.util.regex.*;  
  2. public class RegexExample1{  
  3. public static void main(String args[]){  
  4. //1st way  
  5. Pattern p = Pattern.compile(“.s”);//. represents single character  
  6. Matcher m = p.matcher(“as”);  
  7. boolean b = m.matches();  
  8.   
  9. //2nd way  
  10. boolean b2=Pattern.compile(“.s”).matcher(“as”).matches();  
  11.   
  12. //3rd way  
  13. boolean b3 = Pattern.matches(“.s”, “as”);  
  14.   
  15. System.out.println(b+” “+b2+” “+b3);  
  16. }}  

Output

true true true

Regular Expression . Example

The . (dot) represents a single character.

  1. import java.util.regex.*;  
  2. class RegexExample2{  
  3. public static void main(String args[]){  
  4. System.out.println(Pattern.matches(“.s”, “as”));//true (2nd char is s)  
  5. System.out.println(Pattern.matches(“.s”, “mk”));//false (2nd char is not s)  
  6. System.out.println(Pattern.matches(“.s”, “mst”));//false (has more than 2 char)  
  7. System.out.println(Pattern.matches(“.s”, “amms”));//false (has more than 2 char)  
  8. System.out.println(Pattern.matches(“..s”, “mas”));//true (3rd char is s)  
  9. }}  

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.

In this section, we will learn about Java exceptions, it’s types, and the difference between checked and unchecked exceptions.

What is Exception in Java?

In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. These exceptions can occur for various reasons, such as invalid user input, file not found, or division by zero. When an exception occurs, it is typically represented by an object of a subclass of the java.lang.Exception class.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let’s consider a scenario:

  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Java Exceptions

In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. Additionally, there is a third category known as errors. Let’s delve into each of these types:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

1. Checked Exceptions

Checked exceptions are the exceptions that are checked at compile-time. This means that the compiler verifies that the code handles these exceptions either by catching them or declaring them in the method signature using the throws keyword. Examples of checked exceptions include:

IOException: An exception is thrown when an input/output operation fails, such as when reading from or writing to a file.

SQLException: It is thrown when an error occurs while accessing a database.

ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date.

ClassNotFoundException: It is thrown when an application tries to load a class through its string name using methods like Class.forName(), but the class with the specified name cannot be found in the classpath.

2. Unchecked Exceptions (Runtime Exceptions)

Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These exceptions usually occur due to programming errors, such as logic errors or incorrect assumptions in the code. They do not need to be declared in the method signature using the throws keyword, making it optional to handle them. Examples of unchecked exceptions include:

NullPointerException: It is thrown when trying to access or call a method on an object reference that is null.

ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid index.

ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero.

IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate argument.

Java Inner Classes (Nested Classes)
Java Inner classes
Advantage of Inner class
Difference between nested class and inner class
Types of Nested classes
Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.

Additionally, it can access all the members of the outer class, including private data members and methods.

Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of Java inner classes
There are three advantages of inner classes in Java. They are as follows:
Pause

Next
Mute
Current Time
0:08
/
Duration
18:10

Fullscreen

Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
Code Optimization: It requires less code to write.
Need of Java Inner class
Sometimes users need to program a class in such a way so that no other class can access it. Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class. That way all the outer class can access all the objects of the inner class.

You Know
What is the internal code generated by the compiler for member inner class?
What are the two ways to create an anonymous inner class?
Can we access the non-final local variable inside the local inner class?
How to access the static nested class?
Can we define an interface within the class?
Can we define a class within the interface?
Difference between nested class and inner class in Java
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.

Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.

Non-static nested class (inner class)
Member inner class
Anonymous inner class
Local inner class
Static nested class

Synchronization in Java

Synchronization in Java is a critical concept in concurrent programming that ensures multiple threads can interact with shared resources safely. In a nutshell, synchronization prevents race conditions, where the outcome of operations depends on the timing of thread execution. It is the capability to control the access of multiple threads to any shared resource. Synchronization is a better option where we want to allow only one thread to access the shared resource.

Understanding Threads and Shared Resources

Thread represents an independent path of execution within a program. When multiple threads access shared resources concurrently, problems may arise due to unpredictable interleaving of operations. Consider a scenario where two threads increment a shared variable concurrently:

  1. class Counter {  
  2.     private int count = 0;      
  3.     public void increment() {  
  4.         count++;  
  5.     }  
  6. }  

If two threads execute increment() simultaneously, they might read the current value of count, increment it, and write it back concurrently. This can result in lost updates or incorrect final values due to race conditions.

Introducing Synchronization

Synchronization in Java tackles these problems through the capacity of a single thread to have exclusive access to either a synchronized block of code or a synchronized method associated with an object in question at a time. There are two primary mechanisms for synchronization in Java: synchronized blocks and synchronized methods.

Synchronized Blocks

Synchronized block provides exclusive access to shared resources, and only one thread is allowed to execute it in the same time frame. It’s structured as follows:

  1. synchronized (object) {  
  2.     // Synchronized code block  
  3. }  

This monitor object or lock is the subject. While only one thread can be holding a lock on a monitor object at one instance. Other threads that want to go into the synchronized blocks with this object must wait till the lock becomes available.

Synchronized Methods

In Java, you can declare entire methods as synchronized which prevent multiple threads from accessing the method simultaneously. With this, synchronization becomes a simpler process because the mechanism is applied to all invocations of the synchronized method automatically.

Example: Synchronized Counter

  1. class SynchronizedCounter {  
  2.     private int count = 0;      
  3.     public synchronized void increment() {  
  4.         count++;  
  5.     }      
  6.     public synchronized int getCount() {  
  7.         return count;  
  8.     }  
  9. }  

With this modification, concurrent calls to increment() or getCount() will be synchronized, preventing race conditions.

Intrinsic Locks and Synchronization

In Java, every object automatically has an intrinsic lock (or monitor lock) associated to it. The moment a thread enters the synchronized block or method, it gets the lock for the object, and then no other thread is allowed to enter the synchronized block or method for that object until the lock is released.

Deadlocks

On the one hand, synchronization ensures that race condition is ruled out, but on the other hand, it may lead to deadlocks if not used critically. Stalemates could result as two or more threads are ceaseless when they are waiting for resources from each other. Avoid deadlocks by ordering the locks and releasing them in an opposite sequence of both.

Locking Granularity

The best locking granularity has to be selected and has to avoid contention and thus be good for performance. Leaning too broadly can reduce concurrency, while leaning too finely can lead to overhead increase. Identification of the only section of the code which needs to be the only one having an exclusive access to the shared resources and synchronization of that section alone.

Concurrent Collections

Java contains a thread-safe versions of the common collections classes that found in the java.util.concurrent package, including the ConcurrentHashMap and ConcurrentLinkedQueue. These classes provide internal synchronization mechanisms that guarantee the thread safety without giving up the synchronization control to the user.

Volatile Keyword

Furthermore, volatile keyword may be used to maintain the visibility of changes made to the variables among the threads. For variables declared as volatile, their value will always be read directly from memory and the writes to them will be visible to all the other threads immediately. However, volatile does not ensure as such for complex instructions such as incrementing.

Atomic Classes

Java gives atomic classes in the java.util.concurrent.atomic package including Atomic Integer and Atomic Long, which offer atomic operations of variables without using explicit synchronization. These kind of classes use hardware’s low level atomic operations to make thread safety.

Why use Synchronization?

The synchronization is mainly used to

  1. thread interference, and
  2. Consistency problem

Types of Synchronization

There are the following two types of synchronization:

  1. Process Synchronization
  2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  1. Mutual Exclusive
    1. Synchronized method.
    2. Synchronized block.
    3. Static synchronization.
  2. Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:

  1. By Using Synchronized Method
  2. By Using Synchronized Block
  3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object’s fields has to acquire the object’s lock before accessing them, and then release the lock when it’s done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding The Problem Without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let’s see the example:

TestSynchronization1.java

  1. class Table {  
  2.     // Method to print the table, not synchronized  
  3.     void printTable(int n) {  
  4.         for(int i = 1; i <= 5; i++) {  
  5.             // Print the multiplication result  
  6.             System.out.println(n * i);  
  7.             try {  
  8.                 // Pause execution for 400 milliseconds  
  9.                 Thread.sleep(400);  
  10.             } catch(Exception e) {  
  11.                 // Handle any exceptions  
  12.                 System.out.println(e);  
  13.             }  
  14.         }  
  15.     }  
  16. }  
  17. class MyThread1 extends Thread {  
  18.     Table t;  
  19.     // Constructor to initialize Table object  
  20.     MyThread1(Table t) {  
  21.         this.t = t;  
  22.     }  
  23.     // Run method to execute thread  
  24.     public void run() {  
  25.         // Call printTable method with argument 5  
  26.         t.printTable(5);  
  27.     }  
  28. }  
  29. class MyThread2 extends Thread {  
  30.     Table t;  
  31.     // Constructor to initialize Table object  
  32.     MyThread2(Table t) {  
  33.         this.t = t;  
  34.     }  
  35.     // Run method to execute thread  
  36.     public void run() {  
  37.         // Call printTable method with argument 100  
  38.         t.printTable(100);  
  39.     }  
  40. }  
  41. class TestSynchronization1 {  
  42.     public static void main(String args[]) {  
  43.         // Create a Table object  
  44.         Table obj = new Table();  
  45.         // Create MyThread1 and MyThread2 objects with the same Table object  
  46.         MyThread1 t1 = new MyThread1(obj);  
  47.         MyThread2 t2 = new MyThread2(obj);  
  48.         // Start both threads  
  49.         t1.start();  
  50.         t2.start();  
  51.     }  
  52. }  

Output:

5
100
10
200
15
300
20
400
25
500

Java Synchronized Method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Java Networking

Java Networking is a concept of connecting two or more computing devices together so that we can share resources.

Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking

  1. Sharing resources
  2. Centralize software management

Do You Know ?

  • How to perform connection-oriented Socket Programming in networking ?
  • How to display the data of any online web page ?
  • How to get the IP address of any host name e.g. www.google.com ?
  • How to perform connection-less socket programming in networking ?

The java.net package supports two protocols,

  1. TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
  2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be transferred along two or more nodes

Java Networking Terminology

The widely used Java networking terminologies are given below:PauseNextMute

Current Time 0:14

/

Duration 18:10

Loaded: 5.50%Fullscreen

  1. IP Address
  2. Protocol
  3. Port Number
  4. MAC Address
  5. Connection-oriented and connection-less protocol
  6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

  • TCP
  • FTP
  • Telnet
  • SMTP
  • POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.

The port number is associated with the IP address for communication between two applications.

4) MAC Address

MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.

Visit next page for Java socket programming.

java.net package

The java.net package can be divided into two sections:

  1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces.
  2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs.

The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below:

  • Authenticator
  • CacheRequest
  • CacheResponse
  • ContentHandler
  • CookieHandler
  • CookieManager
  • DatagramPacket
  • DatagramSocket
  • DatagramSocketImpl
  • InterfaceAddress
  • JarURLConnection
  • MulticastSocket
  • InetSocketAddress
  • InetAddress
  • Inet4Address
  • Inet6Address
  • IDN
  • HttpURLConnection
  • HttpCookie
  • NetPermission
  • NetworkInterface
  • PasswordAuthentication
  • Proxy
  • ProxySelector
  • ResponseCache
  • SecureCacheResponse
  • ServerSocket
  • Socket
  • SocketAddress
  • SocketImpl
  • SocketPermission
  • StandardSocketOptions
  • URI
  • URL
  • URLClassLoader
  • URLConnection
  • URLDecoder
  • URLEncoder
  • URLStreamHandler

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

  • It works at client side so less response time.
  • Secured
  • It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

  • Plugin is required at client browser to execute applet.

 Do You Know

  • Who is responsible to manage the life cycle of an applet ?
  • How to perform animation in applet ?
  • How to paint like paint brush in applet ?
  • How to display digital clock in applet ?
  • How to display analog clock in applet ?
  • How to communicate two applets ?

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component.

Lifecycle of Java Applet

  1. Applet is initialized.
  2. Applet is started.
  3. Applet is painted.
  4. Applet is stopped.
  5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.PlayNextMute

Current Time 0:01

/

Duration 18:10

Loaded: 3.30%FullscreenBackward Skip 10sPlay VideoForward Skip 10s

  1. public void init(): is used to initialized the Applet. It is invoked only once.
  2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
  3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
  4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

  1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.


How to run an Applet?

There are two ways to run an applet

  1. By html file.
  2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.

  1. //First.java  
  2. import java.applet.Applet;  
  3. import java.awt.Graphics;  
  4. public class First extends Applet{  
  5.   
  6. public void paint(Graphics g){  
  7. g.drawString(“welcome”,150,150);  
  8. }  
  9.   
  10. }  

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html

  1. <html>  
  2. <body>  
  3. <applet code=”First.class” width=”300″ height=”300″>  
  4. </applet>  
  5. </body>  
  6. </html>  

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.

  1. //First.java  
  2. import java.applet.Applet;  
  3. import java.awt.Graphics;  
  4. public class First extends Applet{  
  5.   
  6. public void paint(Graphics g){  
  7. g.drawString(“welcome to applet”,150,150);  
  8. }  
  9.   
  10. }  
  11. /* 
  12. <applet code=”First.class” width=”300″ height=”300″> 
  13. </applet> 
  14. */  

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Java Reflection API
Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used
The Reflection API is mainly used in:
Play

Next
Mute
Current Time
0:00
/
Duration
18:10

Fullscreen

Backward Skip 10s

Play Video

Forward Skip 10s

IDE (Integrated Development Environment) e.g., Eclipse, MyEclipse, NetBeans etc.
Debugger
Test Tools etc.
Do You Know?
How many ways can we get the instance of Class class?
How to create the javap tool?
How to create the appletviewer tool?
How to access the private method from outside the class?
java.lang.Class class
The java.lang.Class class performs mainly two tasks:

provides methods to get the metadata of a class at run time.
provides methods to examine and change the run time behavior of a class.
Commonly used methods of Class class:
Method
Description
1) public String getName()
returns the class name
2) public static Class forName(String className)throws ClassNotFoundException
loads the class and returns the reference of Class class.
3) public Object newInstance()throws InstantiationException,IllegalAccessException
creates new instance.
4) public boolean isInterface()
checks if it is interface.
5) public boolean isArray()
checks if it is array.
6) public boolean isPrimitive()
checks if it is primitive.
7) public Class getSuperclass()
returns the superclass class reference.
8) public Field[] getDeclaredFields()throws SecurityException
returns the total number of fields of this class.
9) public Method[] getDeclaredMethods()throws SecurityException
returns the total number of methods of this class.
10) public Constructor[] getDeclaredConstructors()throws SecurityException
returns the total number of constructors of this class.
11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException
returns the method class instance.
How to get the object of Class class?
There are 3 ways to get the instance of Class class. They are as follows:

forName() method of Class class
getClass() method of Object class
the .class syntax
1) forName() method of Class class
is used to load the class dynamically.
returns the instance of Class class.
It should be used if you know the fully qualified name of class.This cannot be used for primitive types.
Let’s see the simple example of forName() method.

FileName: Test.java

class Simple{}

public class Test{
public static void main(String args[]) throws Exception {
Class c=Class.forName(“Simple”);
System.out.println(c.getName());
}
}
Output:

Simple
2) getClass() method of Object class
It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.

FileName: Test.java

class Simple{}

class Test{
void printName(Object obj){
Class c=obj.getClass();
System.out.println(c.getName());
}
public static void main(String args[]){
Simple s=new Simple();

Test t=new Test();
t.printName(s);
}
}

Output:

Simple
3) The .class syntax
If a type is available, but there is no instance, then it is possible to obtain a Class by appending “.class” to the name of the type. It can be used for primitive data types also.

FileName: Test.java

class Test{
public static void main(String args[]){
Class c = boolean.class;
System.out.println(c.getName());

Class c2 = Test.class;
System.out.println(c2.getName());
}
}
Output:

boolean
Test
Determining the class object
The following methods of Class class are used to determine the class object:

1) public boolean isInterface(): determines if the specified Class object represents an interface type.

2) public boolean isArray(): determines if this Class object represents an array class.

3) public boolean isPrimitive(): determines if the specified Class object represents a primitive type.

Let’s see the simple example of reflection API to determine the object type.

FileName: Test.java

class Simple{}
interface My{}

class Test{
public static void main(String args[]){
try{
Class c=Class.forName(“Simple”);
System.out.println(c.isInterface());

Class c2=Class.forName(“My”);
System.out.println(c2.isInterface());

}catch(Exception e){System.out.println(e);}

}
}
Output:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *