Java Notes
Java Notes
CLASSES
SUBJECT: JAVA
1
Class
1)Class is the collection of object
2)Class is not a real world Entity.it is just a templet or blue print.
3)class does not occupy the memory.
Syntax:
Example:
public class Demo {
2
Method
Syntax:
Statments
}
Example:
public void pqr() {
-------------------------------------------------------------------------------------------
3
Object
4
Data types
Data type is a classification of the type of data that a variable or object can hold in a
computer programming
Syntax :
example:
int a;
or
int a=100;
1) byte(8 bit)
ex:
byte a=10;
2) short(16 bits)
ex:
short a=87;
3) int(32 bits)
Ex
int a=10000;
4) long(64 bit)
ex:long d=1000000
5
Rational data type
5) float(32 bit)
ex
float a = 1.2;
6) double(64 bit)
ex
double b = 19.656565
Characters
7) char(16 bit)
ex
char a ='z';
Conditional
8)Boolean(1
bit)
ex
boolean
a=true;
boolean
b=false;
6
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
Types of Variables
o local variable
o instance variable
o static variable
7
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
8
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Output:
20
9
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
10
Understanding Java Access Modifiers
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
11
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
12
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
13
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
14
Non Access Modifier
static
static is the non-access modifier , use to make class variable and method as static.
If we make variable as a static this variable can use in static method, we can use it in normal
method also.
But if we make any vaiable without static , this can not accessible in static method.
If we make any class method as a static so for call this method not need to create an object ,
direct on class name we can call this method .
Example:
package nonAccessModifiers;
}
public static void main(String[] args) {
StaticDemo sd = new StaticDemo();
sd.abc();//10
StaticDemo.abc();//10
sd.pqr();//10
15
final :
Adding the final modifier to a variable declaration makes that variable unchangeable once
it's initialized.
package nonAccessModifiers;
int a;
int b;
final int c=0 ;
a=2;
b=4;
//c=5; compile time error
System.out.println(a);//2
System.out.println(b);//4
System.out.println(c);//0
abstract
abstract is non-access modifier which is use to create abstract classes and abstract methods.
We can make method as abstract , when we make any method as an abstract then we need to
make this class as a abstract.
abstract method do not having body, in next concrete class we extend the abstract class and in
that we can provide body to this abstract method.
16
abstract Class A
{
abstract void start(){
}
}
Class B extends A{
void start(){
System.out.println(“Hello Java”)
}
}
public static void main(String[] args) {
B obj = new B();
obj.start();
}
17
Java Operator
Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operator
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly, there are various other
arithmetic operators in Java.
Operation
Operator
+ Addition
- Subtraction
* Multiplication
/ Division
18
% Modulo Operation (Remainder after division)
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2
Assignment operators are used in Java to assign values to variables. For example,
int age;
19
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
Let's see some more assignment operators available in Java.
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
class Main {
public static void main(String[] args) {
// create variables
int a = 4;
int var;
20
}
Output
var using =: 4
var using +=: 8
var using *=: 32
Relational operators are used to check the relationship between two operands. For example,
Here, > operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.
Operator Description Example
class Main {
public static void main(String[] args) {
// create variables
int a = 7, b = 11;
// value of a and b
21
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Operator Example Meaning
22
! (Logical NOT) !expression true if expression is false and vice versa
class Main {
public static void main(String[] args) {
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Working of Program
(5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
(5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.
(5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.
(5 > 3) && (8 > 5) returns true because the expression (5 > 3) is true.
(5 > 3) && (8 > 5) returns false because both (5 < 3) and (8 < 5) are false.
!(5 == 3) returns true because 5 == 3 is false.
!(5 > 3) returns false because 5 > 3 is true.
23
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
Output:
Age is greater than 18
24
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
Output:
odd number
25
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
26
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
Output:
NEGATIVE
import java.util.Scanner;
27
public class IfDemo {
//int a=60;
// int number=0;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:1
28
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}
Output:
Example 2:
29
Output:
Example 3:
package Statment;
30
Java Switch-Case Statement with Example
We all use switches regularly in our lives. Yes, I am talking about electrical switches we use
for our lights and fans.
As you see from the below picture, each switch is assigned to operate for particular electrical
equipment.
For example, in the picture, the first switch is for a fan, next for light and so on.
Thus, we can see that each switch can activate/deactivate only 1 item.
Similarly, switch in Java is a type of conditional statement that activates only the matching
condition out of the given input.
Let us consider the example of a program where the user gives input as a numeric value (only
1 digit in this example), and the output should be the number of words.
The integer variable iSwitch, is the input for the switch to work.
The various available options (read cases) are then written as case <value>alongwith a colon
“:”
This will then have the statement to be executed if the case and the input to the switch match.
31
Java Switch Example
class SwitchBoard{
public static void main(String args[]){
int iSwitch=4;
switch(iSwitch){
case 0:
System.out.println("ZERO");
break;
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
case 4:
System.out.println("FOUR");
break;
default:
System.out.println("Not in the list");
break;
}
}
}
Output:
FOUR
package JavaTheory;
32
import java.util.Scanner;
switch(iSwitch){
case 0:
System.out.println("ZERO");
break;
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
case 4:
System.out.println("FOUR");
break;
default:
System.out.println("Not in the list");
break;
}
}
Output:
Enter the number::
2
TWO
33
Loops in Java
1)for loop
2)while loop
3)do while loop
4)Enhanced for loop
-------------------------------------------
1)for loop
Syntax:
for(datatype variable=value(initialization);condition;increment/decrement) {
statment;
}
Example:
package javaPrograms;
for(int i=0;i<=10;i++) {
System.out.println(i);
}
}
--------------------------------------------------------
34
2)while loop
Syntax:
int i= 10;
while(i>=0) {
System.out.println(i);
i--;
}
}
}
-----------------------------------------------------
35
3)do while loop
Syntax:
initialization
do {
statment
inctrement/decrement;
}while(condition);
Example:
package javaPrograms;
int i=0;
do {
System.out.println(i);
i++;
}while(i<=10);
}
}
----------------------------------------------------------------------------------
36
4)Enhanced for loop:-
Syntax:
for(datatype var:var){
Statment;
}
Example:
package javaPrograms;
for(String lang:language) {
System.out.println(lang);
}
}
37
Constructor
public ConstructorDemo() {
System.out.println("This is constructor demo");
}
}
-------------------------------------------------------------------
38
Types of constructor:
1)Default constructor
2)User defined constructor
a)No argument constructor
b)Parameterized constructor
1)Default constructor:
package javaPrograms;
}
-----------------------------------------------------------------------------------
2)User defined constructor
a)No argument constructor
b)Parameterized constructor
39
public ConstructorDemo() {
System.out.println("This is constructor demo");
}
public ConstructorDemo(int a ) {
40
public static void main(String[] args) {
41
Inheritance:
1)superclass----->subclasses
Types of Inheritance:
1)Single Inheritance
2)Multilevel inheritance
3)Hierarchical Inheritance
4)Multiple Inheritance
5)Hybrid Inheritance
1)Single Inheritance
Class 1
package Inheritance;
42
public static void main(String[] args) {
}
-----------------------------------------------------------
2)Multilevel Inheritance
3)Hierarchical Inheritance
The multiple subclasses access the properties from one superclass
4)Multiple Inheritance
In multiple inheritance when one subclass try to access the properties from multiple super
classes
so the compiler is confused from which superclass he need to access the properties.so here
diamond ambiguity problem is occuerd. so the Multiple inheritance is not possible in java.
5)Hybrid Inheritance
Hybrid Inheritance is the combination of Hierarchical and multiple inheritance .this is not
supported
in java
43
Interface:
Interface are similar to abstract class but having all the method of abstract name.
Methods:
public abstract void show();
(The method declared in interfaces that should be public abstract void methodname, we not
providing the body of that method).
Example:
Interface 1:
Program:
package InterfaceDemo;
public interface I1 {
}
----------------
44
Interface 2:
Program:
package InterfaceDemo;
public interface I2 {
@Override
public void display() {
System.out.println("1");
}
@Override
public void show() {
System.out.println("2");
}
45
t1.display();
}
=====
Output
2
1
46
Abstraction
An abstraction means showing only essential features of application and hiding the details.
If we are taking abstract method then we should make this class as abstract class.
In next class we extends the abstract class then we can access the abstract methods in this
class and can
provide body to this method.
---------------------------------
First class:(abstract class/method should be abstract)
Example:
package Abstraction;
}
------
In Second class we just extends the abstract class and adding unimplemented
method of abstract class or providing body to them.
Example:
package Abstraction;
47
@Override
void start() {
System.out.println("Start with Key");
}
}
-------------
next class we just extends the abstract class and adding unimplemented
method of abstract class or providing body to them.
and also taking main method and in that call the method of respective classes by creating
object of that particular class.
Example:
package Abstraction;
@Override
void start() {
System.out.println("Start with Kick");
48
Polymorphism
Types of Polymorphism
1)compile time polymorphism
--static polymorphism
--method overloading
-----------------------------------------------------------
1)Method Overloading
-Multiple methods with same name but different parameter
-same class
-parameters should be different
(no of parameter,type of parameter)
package Polymorphism;
49
}
public void show(int a) {
System.out.println("2");
}
public void show(char a) {
System.out.println("3");
}
public void show(int a ,char b) {
System.out.println("4");
}
}
------------------------------------------------------------------
2)Method Overriding
-one class having one method and next class having method which is same as first class,
method name
are same as well as parameter are also same it is called as method overridding.
-different class
-parameters should be same
(no of parameter, type of parameter)
-Need to use the concept Inheritance
50
Program1:
package Polymorphism;
Program2:
package Polymorphism;
51
String Handling in Java
package StringHandling;
System.out.println(mytool);//Selenium
for(String tools:mytools) {
System.out.println(tools);
}
}
52
Concatenation of Strings:
Ex:
String str1 = "Selenium";
String str2 = "Testing";
System.out.println(str1+str2);//SeleniumTesting
----------------------------------------------------------------------------------
2)String +Number = Concatination
Ex:
System.out.println("Selenium"+1+1);//Selenium11
-----------------------------------------------------------------------------------
3)Number+String = Concatination
Ex:
System.out.println(1+1+"Selenium");//2Selenium
------------------------------------------------------------------------------
53
String Comparison:
Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1==str3);//true
System.out.println(str1==str2);//false
System.out.println(str1==str4);//false
System.out.println(str1!=str4);//true
------------------------------------------------------------------------------------
2)Using equals() method
Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1.equals(str2));//false
System.out.println(str1.equals(str3));//true
-------------------------------------------------------------------------------------
54
3)Using compareTo() method
Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1.compareTo(str2));//negative
System.out.println(str2.compareTo(str1));//positive
System.out.println(str1.compareTo(str3));//0
-------------------------------------------------------------------------------------
concats()
Program:
package StringHandling;
System.out.println(str1.concat(str2));//SeleniumTesting
55
-----------------------------------------------------------------------------------
charAt()
Program:
package StringHandling;
System.out.println(str1.charAt(3));//e
}
------------------------------------------------------------------------------
equalIgnoreCase()
In This method check two strings should be same then result will true otherwise
result will be false and ignoring there case .
Program:
package StringHandling;
56
public class StringMethod {
System.out.println(str1.equalsIgnoreCase(str2));//true
}
}
------------------------------------------------------------------------------------
toUppercase()
Program:
package StringHandling;
System.out.println(str1.toUpperCase());//SELENIUM
57
}
}
------------------------------------------------------------------------------------------
toLowercase()
Program:
package StringHandling;
System.out.println(str1.toLowerCase());//selenium
}
----------------------------------------------------------------------------------------
58
trim()
This method used for reduce the space available before the string.
Program:
package StringHandling;
System.out.println(str1.trim());//Selenium
}
--------------------------------------------------------------------------------------
subString()
This method is used to select the string from the index provided in the subString parameter.
Program:
package StringHandling;
59
public static void main(String[] args) {
}
------------------------------------------------------------------------------------------------------
endsWith()
This method is used to check the given string is ended with selected parameter value.
Program:
package StringHandling;
60
}
}
-------------------------------------------------------------------------------
length()
Program:
package StringHandling;
}
--------------------------------------------------------------------------------------------
61
Arrays
1)Java arrays is an object that holds a fixed number of values of a single data
Or
------------------------------------------------------------------------------
Declaration of Array:
Program:
package Array;
62
int abc[]=new int[4];
abc[0]=10;
abc[1]=20;
abc[2]=30;
abc[3]=40;
System.out.println(abc[0]);//10
System.out.println(abc[1]);//20
System.out.println(abc[2]);//30
System.out.println(abc[3]);//40
System.out.println(abc[0]+abc[1]);
System.out.println(abc[0]-abc[1]);
System.out.println(abc[0]*abc[1]);
System.out.println(abc[0]/abc[1]);
System.out.println(abc[0]>abc[1]);
System.out.println(abc[0]<abc[1]);
System.out.println(abc[0]==abc[1]);
System.out.println(abc[0]!=abc[1]);
}
}
-------------------------------------------------------------------------------------------
Program:
package Array;
63
public class ArrayDemo1 {
System.out.println(abc[0]);//10
System.out.println(abc[1]);//20
System.out.println(abc[2]);//30
System.out.println(abc[3]);//40
System.out.println(abc[0]+abc[1]);
System.out.println(abc[0]-abc[1]);
System.out.println(abc[0]*abc[1]);
System.out.println(abc[0]/abc[1]);
System.out.println(abc[0]>abc[1]);
System.out.println(abc[0]<abc[1]);
System.out.println(abc[0]==abc[1]);
System.out.println(abc[0]!=abc[1]);
}
}
----------------------------------------------------------------------------------
How many types of array we can declare
package Array;
64
public class ArrayDemo2{
System.out.println(abc[0]);//A
System.out.println(abc[1]);//B
System.out.println(abc[2]);//C
System.out.println(xyz[1]);//20
System.out.println(a[1]);//UFT
System.out.println(b[3]);//false
}
}
--------------------------------------------------------------------
Array Operations:
int array1[]={1,2,3,4,5};
65
int array2[]=array1;
System.out.println(array2.length);
for(int abc:array2) {
System.out.println(abc);
}
}
}
--------------------------------------------------------------
Printing array using Normal for loop
Program:
package Java_Programs;
int array1[]={1,2,3,4,5};
int array2[]=array1;
System.out.println(array2.length);
for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}
66
}
----------------------------------------------------------------
----------------------------------------------------------
1)Single Dimensional Array
int array1[]={1,2,3,4,5};
System.out.println(array1[1]);
---------------------------------------------------------
2)Multi Dimensional Array
Example1:
package Array;
67
System.out.println(abc[0][0]);//10
System.out.println(abc[0][1]);//20
System.out.println(abc[1][0]);//30
System.out.println(abc[1][1]);//40
System.out.println(abc[2][0]);//50
System.out.println(abc[2][1]);//60
}
------------------------
Example 2:
package Array;
System.out.println(abc[0][0]);//10
System.out.println(abc[0][1]);//20
System.out.println(abc[1][0]);//30
68
System.out.println(abc[1][1]);//40
System.out.println(abc[2][0]);//50
System.out.println(abc[2][1]);//60
---------------------------------------------------------------------------
Advantages:
69
Print Array
Program:
package Java_Programs;
int array1[]={1,2,3,4,5};
int array2[]=array1;
System.out.println(array2.length);
for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}
}
-----------------------------------------------------------------------
Program:
First way:
package Java_Programs;
70
public class ArrayOperation {
int array1[][]={{1,7,8,5},{5,8,9,4}};
System.out.println(array1[0][0]);//1
System.out.println(array1[0][1]);//7
System.out.println(array1[0][2]);//8
System.out.println(array1[0][3]);//5
System.out.println(array1[1][0]);//5
System.out.println(array1[1][1]);//8
System.out.println(array1[1][2]);//9
System.out.println(array1[1][3]);//4
}
}
------------------
Second way
Program:
package Java_Programs;
71
public static void main(String[] args) {
int array1[][]={{1,7,8,5},{5,8,9,4}};
for(int i=0;i<=3;i++) {
for(int j=0;j<=3;j++) {
System.out.println(array1[i][j]);
}
}
}
}
--------------------------------------------------------------------
Copy One Dimensional Array
Program:
package Java_Programs;
int array1[]={1,2,3,4,5};
int array2[]=array1;
System.out.println(array2.length);
72
for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}
}
--------------------------------------------------------------------
Program:
package Java_Programs;
int array1[][]={{1,7,8,5},{5,8,9,4}};
int array2[][]=array1;
for(int i=0;i<=3;i++) {
for(int j=0;j<=3;j++) {
System.out.println(array2[i][j]);
}
}
}}
73
Java Array List
Java Array is Static data structure , and ArrayList is Dynamic Data Structure
Array vs ArrayList
74
//Add element to ArrayList
a.add(100);
a.add(200);
a.add(300);
System.out.println(a.get(2));//300
System.out.println(a.size());//3
//Remove an Element
System.out.println(a.get(1));//200
System.out.println(a.get(2));//300
a.remove(1);
System.out.println(a.get(1));//300
//System.out.println(a.get(2));//Run time error "Array out of bound"
75
System.out.println(a.contains(100));true
System.out.println(a.contains(400));false
System.out.println(a.size());//2
a.add(400);
a.add(500);
System.out.println(a.size());//4
a.clear();
System.out.println(a.size);//0
--------------------------------------------
Syntax:
ArrayList<type of ArrayList> ArrayList Name =new ArrayList <>();
Example:
----------------------------------------------------------------------
76
3.Create Character type ArrayList and perform some operation
xyz.add('A');
xyz.add('b');
xyz.add('r');
xyz.add('t');
System.out.println(xyz.size());//4
System.out.println(xyz.get(2));//r
77
Java StringBuffer class
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
class StringBufferExample{
The insert() method inserts the given string with this string at the given position.
78
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
}
}
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"ABC");
System.out.println(sb);//prints HABClo
}
}
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
79
sb.reverse();
System.out.println(sb);//prints olleH
}
}
The capacity() method of 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.
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
}
}
80
Java StringBuilder class:
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
The StringBuilder append() method concatenates the given argument with this string.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
The StringBuilder insert() method inserts the given string with this string at the given position.
81
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuilder reverse() method
82
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder 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.
class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
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
}
}
There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:
83
No. String StringBuffer
2) String is slow and consumes more memory when StringBuffer is fast and consumes
you concat too many strings because every time it less memory when you cancat
creates new instance. strings.
Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.
StringBuffer Example
84
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
hellojava
StringBuilder Example
85
Java Data Type Conversion
Example:
//Integer to Byte
public class TypeCasting {
System.out.println(d);//30
}
}
Example:
// Byte to Integer
byte a=10;
int b=a;
System.out.println(b);//10
int a=10;
byte b=(byte) a;
System.out.println(b);//10
//long to long
long a=1000000;
long b= a;
System.out.println(b);//10
//long to int
long a=100;
int b= (int)a;
System.out.println(b);//100
86
//String to int
String a="10";
String b= "20";
System.out.println(a+b);//1020
int num1 =Integer.parseInt(a);
int num2 =Integer.parseInt(b);
System.out.println(num1+num2);//30
//String to double
String a="10.234";
double val= Double.parseDouble(a);
System.out.println(val);
//Integer to double
int a=10;
double b= a;
System.out.println(b);
//double to Integer
double a=17.34;
int b= (int) a;
System.out.println(b);//17
87