m4 Java
m4 Java
// String literal
String s="Geeks for Geeks String in Java1";
// string s="Geeks for Geeks String in Java2"; compile error
System.out.println(s);
}
}
Note in java string variable is defined by String class only we cannot take
string otherwise give u compile time error
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.
char ch[]={'s','t','r','i','n','
g','s'};
Creating a String // Java Program to Create a String
There are two ways to create string in Java: import java.io.*;
Stringmethods.java in
notepad
3 ways to create string in Java
Note:String example-name,email,address,phone number,account no
Whose values changed only one or two times changes done through creating new instance
String Buffer –whose values changed frequently like calculator,notepad changes done in same instance
Here are some important features and methods of the StringBuffer class:
StringBuffer objects are mutable, meaning that you can change the contents of the buffer
without creating a new object.
The initial capacity of a StringBuffer can be specified when it is created, or it can be set later
with the ensureCapacity() method.
The append() method is used to add characters, strings, or other objects to the end of the
buffer.
The insert() method is used to insert characters, strings, or other objects at a specified
position in the buffer.
The delete() method is used to remove characters from the buffer.
The reverse() method is used to reverse the order of the characters in the buffer.
Important Constructors of StringBuffer class
•StringBuffer(): creates an empty string buffer with an initial capacity of 16.
•StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
1) StringBuffer Class append() Method
The append() method concatenates the given argument
with this String.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and
endIndex.
StringBufferExample3.java
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex (not included).
class Main{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("012345");
sb.delete(1,4); end index is not inclusive
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder
class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuffer capacity() Method
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Lot of delays in the application so need more
optimized way for handling strings
jagged arrays can be applied in various real-world situations where data is inherently irregular or sparse.
Application Domain Description Example
Store grades for students enrolled in different int[][] studentGrades = {{85, 90}, {78, 82, 88},
Student Grades
numbers of courses. {92}};
Represent departments with varying int[][] employees = {{101, 102}, {201, 202,
Company Hierarchy
numbers of employees. 203}, {301}};
Schedule sessions for each day of a String[][] schedule = {{"Session1",
Conference Scheduling conference where each day has different "Session2"}, {"Keynote"}, {"Workshop1",
sessions. "Workshop2", "Workshop3"}};
Efficiently store rows with varying numbers of
Sparse Matrix int[][] sparseMatrix = {{1, 2}, {}, {4, 5, 6}};
non-zero elements.
Group data points from clustering algorithms,
Clustering int[][] clusters = {{1, 2}, {3}, {4, 5, 6}};
where groups have different sizes.
Store layouts for game levels with different
Game Level Design char[][] levels = {{'X', 'O'}, {'X'}, {'O', 'X', 'O'}};
numbers of obstacles or enemies.
Track expenses where each month has a double[][] expenses = {{200.5, 300.75},
Monthly Expenses
different number of entries. {150.0}, {250.0, 100.25}};
String[][] routes = {{"Stop1", "Stop2"},
Store routes where each route has a different
Navigation Routes {"Stop1", "Stop3"}, {"Stop1", "Stop2",
number of stops.
"Stop4"}};
Represent books categorized by genres, String[][] books = {{"Fiction1", "Fiction2"},
Library Management where each genre has a different number of {"SciFi1"}, {"Biography1", "Biography2",
books. "Biography3"}};
Store seating plans where each row has a int[][] seatingPlan = {{1, 2, 3}, {4, 5}, {6, 7, 8,
Exam Seating Arrangement
different number of seats. 9}};
public class JaggedArrayExample {
public static void main(String[] args) {
// Declare a jagged array
int[][] studentMarks = new int[3][];
studentMarks[0] = new int[]{85, 90, 78}; // Student 1 marks in 3 subjects
studentMarks[1] = new int[]{92, 88}; // Student 2 marks in 2 subjects
studentMarks[2] = new int[]{76, 81, 85, 90}; // Student 3 marks in 4 subjects
//printing values
System.out.println("Student Marks:");
for (int i = 0; i < studentMarks.length; i++) {
System.out.print("Student " + (i + 1) + ": ");
for (int j = 0; j < studentMarks[i].length; j++) {
System.out.print(studentMarks[i][j] + " ");
}
System.out.println(); // Move to the next line for the next student
}
}
}
Java arrays are versatile and widely used in real-world applications to handle and process collections of similar data
types efficiently. Here are some real-life applications of Java arrays presented in a structured way:
Java arrays are versatile and widely used in real-world applications to handle and process collections of similar data
types efficiently. Here are some real-life applications of Java arrays presented in a structured way:
Java arrays are versatile and widely used in real-world applications to handle and process collections of similar data
types efficiently. Here are some real-life applications of Java arrays presented in a structured way:
Java arrays are versatile and widely used in real-world applications to handle and process collections of similar data
types efficiently. Here are some real-life applications of Java arrays presented in a structured way:
In Java, the Collection interface (java.util.Collection) and Map interface (java.util.Map) are the
two main “root” interfaces of Java collection classes.
ArrayList is part of the modern collection framework, preferred for new applications.Vector is considered outdated but is
still in use for backward compatibility with older applications.
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set,
List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
•The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.
•The List interface offers methods to access elements by their index and includes the listIterator() method,
which returns a ListIterator.
•Using ListIterator, we can traverse the list in both forward and backward directions.
// Java program to show the use of List Interface
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Creating a List of Strings using ArrayList
List<String> li = new ArrayList<>();
li.add("Java");
li.add("Python");
li.add("DSA");
li.add("C++");
System.out.println("Elements of List are:");
for (String s : li) {
System.out.println(s);
}
System.out.println("Element at Index 1: "+ li.get(1));
li.set(1, "JavaScript");
System.out.println("Updated List: " + li);
li.remove("C++");
System.out.println("List After Removing Element: " + li);
}
}
The Vector class in Java is a part of the java.util package and represents a dynamic
array that can grow or shrink in size as needed. It is synchronized, making it thread-safe for
multi-threaded environments.Despite its usefulness, Vector is considered somewhat
outdated and is often replaced by ArrayList in non-threaded contexts due to performance
reasons.
If thread safety isn't a concern, it’s better to use ArrayList.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
System.out.println("First Element: " + vector.firstElement());
System.out.println("Last Element: " + vector.lastElement());
for (String fruit : vector) {
System.out.println(fruit);
}
vector.remove("Banana");
System.out.println("After removal: " + vector);
System.out.println("Size: " + vector.size());
System.out.println("Capacity: " + vector.capacity());}}
Online Chat Application
In a multi-threaded chat server, you might need to store a list of active users in a thread-safe way. Since multiple
threads (representing user sessions) could simultaneously add or remove users, using Vector ensures
synchronization.
ChatRoom.java
The ArrayList class in Java is a part of the Java Collections Framework and is
used to store dynamically resizable arrays. Unlike standard arrays, ArrayList
can grow or shrink in size as elements are added or removed. It is one of the
most commonly used collection classes due to its flexibility and performance.
Student Management System In a Student Management System, an ArrayList can be used to maintain a
dynamic list of students enrolled in a course. As students register or drop out, the list dynamically adjusts to
accommodate these changes.
StudentManagement.java
The LinkedList class in Java is a part of the Java Collections Framework and implements the List and Deque
interfaces. It represents a doubly linked list, which means each node contains data and references to the previous and
next nodes in the sequence.Unlike ArrayList, which uses a dynamic array, LinkedList provides better performance for
frequent insertions and deletions because elements do not need to be shifted.
LinkedListExample.java
Browser History ManagementIn a browser, the history of visited web pages can be implemented using a
LinkedList. Each page visited is added to the history, and when navigating back and forth, the list ensures efficient
traversal without reloading pages unnecessarily.
LinkedListRealLifeExample.java
The Stack class in Java is a part of the Java Collections Framework and is a subclass of Vector. It represents a last-in-
first-out (LIFO) data structure, meaning the last element added to the stack is the first one to be removed.The Stack class
provides methods to perform typical stack operations such as push, pop, peek, and search.
The Deque interface provides a modern implementation of stacks and queues. Use ArrayDeque for
better performance and less overhead compared to Stack.
The Map interface in Java is a part of
the Java Collections Framework and provides
a way to store data as key-value pairs. Each
key is unique, and each key maps to exactly
one value. It is widely used in scenarios
where fast lookups and associations
between keys and values are required.
MapExample.java
Java I/O Streams
In Java, streams are the sequence of data that are read from the source and written to
the destination.
An input stream is used to read data from the source. And, an output stream is used to
write data to the destination.
For example, in our first Hello World example, we have used System.out to print a string. Here, the System.out
is a type of output stream.
Similarly, there are input streams to take input(reading data .( System.in) used in Scanner
class
Types of Streams
Depending upon the data a stream holds, it can be classified into:
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream
and OutputStream.
Reading can be from diff sources like
Keyboard,mouse,Socket,Database,array,string,StringBuffer
Writing can be in diff sources like
Monitor(console),file,Socket,Database,array,string,StringBuffer
Filehandling1.java – Reading Data from file input.txt
Since InputStream is an abstract class, it is not useful by itself. However, its subclasses
can be used to read data.
Filehandling2.java – writing Data from java file into output.txt
If file not created it will create and overwrite everytime with
changes.