Unit - III
Unit - III
datatype[] arrayName;
or
datatype arrayName[];
• The arrayName can be any valid array name and datatype can be any
like: int, float, byte etc.
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr;
• Initialization of Array
• Initialization is a process of allocating memory to an array.
• At the time of initialization, we specify the size of array to reserve memory
area.
• Initialization Syntax
arrayName = new datatype[size]
• The arrayName is the name of array, new is a keyword used to allocate memory and
size is length of array.
Example
int[][] intArray = new int[10][20];
class multiDimensional {
public static void main(String args[]) {
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++) {
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
Addition of 2 Matrices in Java
class Testarray5{
public static void main(String args[]){
//creating matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
• Output
Compile by: javac Testarray5.java
Run by: java Testarray5
268
6 8 10
Matrix multiplication
Example
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++) {
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}
Output
String
String s="java";
• CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer and StringBuilder classes implement it.
• Java String is immutable which means it cannot be changed.
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.
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.
Example
• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance
class Main {
public static void main(String[] args) {
// create a string using new
String name = new String("Java String");
System.out.println(name); // print Java String
}
}
2) By new keyword
• String s=new String("Welcome"); //creates two objects and one reference variable.
• 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).
Output
String: Hello! World
Length: 12
• Join two Strings
• We can join two strings in Java using the concat() method.
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output
First String: Java
Second String: Programming
• String Concatenation in Java
• There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method
• By concat() method
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin“ + " Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
• Output
• Sachin Tendulkar
• 2) String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
• Output
• Sachin Tendulkar
• Compare two Strings
• In Java, we can make comparisons between two strings using the equals() method.
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}
Output
• Strings first and second are equal: true
• There are three ways to compare string in java:
• By equals() method
• By = = operator
• By compareTo() method
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output
True
• String compare by == operator
• The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//
false(because s3 refers to instance created in nonpool)
}
}
Output :
True
False
• String compare by compareTo() method
• The String compareTo() method compares values lexicographically and
returns an integer value.
• it describes if first string is less than, equal to or greater than second string.
String s="hello";
System.out.println(s.substring(0,2));//he
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
• Java String trim() method
• The string trim() method eliminates white spaces before and after string.
• Output
Sachin
Sachin
• Java String charAt() method
• The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output
• S
• h
• Java String valueOf() method
• The string valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output
1010
• Java String replace() method
• The string replace() method replaces all occurrence of first sequence of
character with second sequence of character.
• Output
C++ is a programming language. C++ is a platform independent.
• The java.lang.StringBuffer
• The StringBuffer and StringBuilder classes are used when there is a necessity
to make a lot of modifications to Strings of characters.
• objects of type StringBuffer and String builder can be modified over and over
again without leaving behind a lot of new unused objects.
2 public StringBuffer reverse()The method reverses the value of the StringBuffer object
that invoked the method.
3 public delete(int start, int end)Deletes the string starting from the start index until the
end index.
4 public insert(int offset, int i)This method inserts a string s at the position mentioned by
the offset.
5 replace(int start, int end, String str)This method replaces the characters in a substring
of this StringBuffer with characters in the specified String.
Interface in Java
• An 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.
• An interface is used to group related methods with empty bodies
Syntax
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Declaring Interfaces
import java.lang.*;
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations
}
• Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details
of an object (interface).
2) Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma
• The relationship between classes and interfaces
• Multiple inheritance in Java by interface
• Extending Interfaces
• An interface can extend another interface in the same way that a class can extend another class.
• The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent
interface.
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
• Extending Multiple Interfaces
• A Java class can only extend one parent class.
• Multiple inheritance is not allowed.
• Interfaces are not classes, however, and an interface can extend more than
one parent interface.
• Example
• public interface Hockey extends Sports, Event
• Interfaces have the following properties −
• An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is
not needed.
• Methods in an interface are implicitly public.
Example
interface Animal {
public void eat();
public void travel();
}
• Implementing Interfaces
• A class uses the implements keyword to implement an interface.
• The implements keyword appears in the class declaration following the extends portion of the declaration.
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support , for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc).
• Example
• import java.util.Scanner;
package package_name;
public class ClassOne {
public void methodClassOne() {
System.out.println("Hello there its ClassOne");
}
}
• Creating our second package:
• File name – ClassTwo.java
package package_one;
public class ClassTwo {
public void methodClassTwo(){
System.out.println("Hello there i am ClassTwo");
}
}
• Making use of both the created packages:
• File name – Testing.java
import package_one;
import package_name.ClassOne;
Output:
package p1;
class c1(){
public void m1(){
System.out.println("m1 of c1");
}
public static void main(string args[]){
c1 obj = new c1();
obj.m1();
}
• To put a class into a package, at the first line of code define package
p1
• Create a class c1
• Defining a method m1 which prints a line.
• Defining the main method
• Creating an object of class c1
• Calling method m1
Step 2) In next step, save this file as demo.java
Step 3) In this step, we compile the file.
• The compilation is completed.
• A class file c1 is created. no package is created
package p1.p2;
class c1{
public void m1() {
System.out.println("m1 of c1");
}
}
• Step 8) Compile the file
java p1.p2.c1
• This is how the package is executed and gives the output as "m1 of
c1" from the code file.
• The package keyword is used to create a package in java.
Syntax
package nameOfPackage;
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
• Multitasking:
• Ability to execute more than one task at the same time is known as
multitasking.
• Multithreading:
• It is a process of executing multiple threads simultaneously.
• Multithreading is also known as Thread-based Multitasking.
• Multiprocessing:
• It is same as multitasking, however in multiprocessing more than one CPUs
are involved.
• On the other hand one CPU is involved in multitasking.
• Parallel Processing:
• It refers to the utilization of multiple CPUs in a single computer system.
MULTITHREADING
• A single thread is basically a lightweight and the smallest unit of
processing.
• Java uses threads by using a "Thread Class".
• There are two types of thread –
• user thread - When an application first begins, user thread is created.
• daemon thread - daemon threads are used when we want to clean the
application and are used in the background.
• Single Thread Example:
package demotest;
public class SingleThread {
public static void main(String[] args) {
System.out.println("Single Thread");
}
}
• Advantages of single thread:
• Reduces overhead in the application as single thread execute in the system
• Also, it reduces the maintenance cost of the application.
Multithreading
• Process of executing two or more threads simultaneously to
maximum utilization of CPU.
• Multithreaded applications execute two or more threads run
concurrently.
• Each thread runs parallel to each other.
• Multiple threads don't allocate separate memory area, hence they
save memory.
• Context switching between threads takes less time.
Advantages of multithread:
• The users are not blocked because threads are independent, and we
can perform multiple operations at times
• As such the threads are independent, the other threads won't get
affected if one thread meets an exception.
• New
• Runnable
• Running
• Waiting
• Dead
• New:
• In this phase, the thread is created using class "Thread class".
• It remains in this state till the program starts the thread. It is also known as
born thread.
• Runnable:
• In this page, the instance of the thread is invoked with a start method.
• The thread control is given to scheduler to finish the execution.
• It depends on the scheduler, whether to run the thread.
• Running:
• When the thread starts executing, then the state is changed to "running"
state.
• The scheduler selects one thread from the thread pool, and it starts executing
in the application.
• Waiting:
• This is the state when a thread has to wait.
• As there multiple threads are running in the application, there is a need for
synchronization between threads.
• Hence, one thread has to wait, till the other thread gets executed.
• Dead:
• This is the state when the thread is terminated.
• The thread is in running state and as soon as it completed processing it is in
"dead state".
•Timed Waiting:
•A thread lies in timed waiting state when it calls a method with a time out
parameter.
•A thread lies in this state until the timeout is completed or until a notification
is received.
•For example, when a thread calls sleep or a conditional wait, it is moved to a
timed waiting state.
• BLOCKED
• A thread that is blocked waiting for a monitor lock is in this state.
• To get the current state of the thread, use Thread.getState() method .
• Java provides java.lang.Thread.State class that defines the ENUM
constants for the state of a thread.
Commonly used Methods
Method Description
start() This method starts the execution of the thread and JVM calls the run()
method on the thread.
Sleep(int milliseconds) This method makes the thread sleep hence the thread's execution will pause
for milliseconds provided and after that, again the thread starts executing.
This help in synchronization of the threads.