You are on page 1of 32

JAVA

Section 1:

1. Introduction to Programming / Software.


2. Introduction to Java.
3. Environment setup.
4. Keywords, Variables and Identifiers.
5. Operators.
6. Methods / Functions.
7. Flow Control Statements
8. Arrays
9. Strings

1. Introduction to Software, Program, and Programming Language

Software: A set of programs which is developed to solve Business Problems.

Program: It is a set of instructions which are developed to perform a particular task.

Programming Language: It is a language to communicate with a computer from a programmer.

2. Introduction to Java.
Low level language or
Take a
Binary language
Take b
a = 10
Store 10, a
b = 20 0 1 0 1 0 1 0 CPU
Complier Store 20, b Assembler
c=a+b
Take c
print c
Add a,b

Store c
High level Languages
Print c
C, C++, Java, Python, SQL, JS
Assembly level language
8086 8085
Compiler: converts high-level language to assembly language.
Assembler: converts assembly level language to Binary language.
3. Environment Setup
JDK (Java Development Kit)

Demo.java
Javac ( Java
Byte Code JVM
Compiler)

Demo.class

Demo.java

Create java program using, CodeEditors: sublimeText, Notepad++, EditPlus etc...

IDE: NetBeans, Eclipse, Intellij, JCreater.

Javac (java compiler):

 Check the syntax of the program


 If syntax mistake
o Throw compile time error
 Else
o Convert java code to byte code and save it (class file).

JVM (Java Virtual Machine):

 Read a line of code.


 Understand a line of code.
 Execute a line of code.
 If code is not understandable then
o Throw Run time error or exception
 Else
o Execute the code.
4. Keywords, Variables and Identifiers
A. Keyword:
 Keywords are those which has reserved words and predefined meaning defined in programming
language.
 Keywords should always written in lowercase.

Keywords available in Java


abstract default goto package synchronized
assert do if private this
boolean double implements protected throw
break else import public throws
case enum**** instanceof return transient
catch extend int short try
char final interface static void
class finally long strictfp** volatile
const** float native super while
continue for new switch

B. Variables:
 Variable is a named memory location which used to store the value of program to perform the
operation by the program at the run-time.

 Memory is divided into block.


 Each block has unique memory address.

To use variable we have to follow 3 steps:

1. Declaration
2. Initialization
3. Utilization
Data Types

Input
How many

Calculation
Program
Process
Comparison

Output Statement
1. Declaration:

Declaration is a statement which written to specify the type of data to be stored in the given
variable.

Syntax: datatype varName; Example: int a;

DataType Type of Data Example Capacity Default


Can be Stored Value
byte integer 10 8 bits (1 bytes) 0
short integer 20 16 bits (2bytes) 0
int integer 50 32 bits (4 bytes) 0
long integer 9876543210 64 bits (8 bytes) 01
float floating point 10.0f 32 bits (4 bytes) 0.0f
double floating point 35.50 64 bits (8 bytes) 0.0
char single character ‘p’ 16 bits (2 byte) Space
boolean logic value true or false 8 bits (1 byte) false

 The Data Type of a variable can be of following types


Data Types

Primitive Non – Primitive

Data Type Data Type

byte
class interface
int

short

long Concrete class Abstract class

float

double

char

boolean
2. Initialization

Initialization is a statement which is written to store the data within a variable using assignment

Operator ( = ).

Syntax: varName = value; Example: a =23;

Note: ( = ) : Assignment operator.

( == ): equals operator.

3. Utilization

Utilization is one or group of statement which is written to use the value in the variable to
perform the operation.

C. Identifiers
Identifiers are the names which are used to identify class, methods and variables n a java program.
Rules of Identifiers:
a. Identifiers can be alpha – numeric.
b. Identifiers should not start with numeric.
c. ‘$’ and ‘_ (underscore)’ are the only 2 special characters that can be used with identifiers.
d. Identifiers can start with $ or _ (underscore).
e. Single _ (underscore) is an invalid identifier in java.
f. Keywords cannot be used as identifiers.

5. Operators
Operators perform operation on the operands and produce result.
Types of Operators:
a. Arithmetic operator (+, - , *, /, %).
b. Increment (++) and Decrement (--) operator.
c. Comparison operator (>, <, <=, >=, ! =).
d. Logical operator (&&, ||, ^).
e. Bitwise operator (&, |, ^).
a. Arithmetic operator: Example Program.

class ArithmeticOpr
{
public static void main(String[] args)
{
int a; //initialization
int b;
int sum = 0, subtraction = 0, product = 0, div = 0, mod = 0;
a = 20; // declaration
b = 10;
sum = a + b;
subtraction = a - b;
product = a * b;
div = a / b;
mod = a % b;
System.out.println("Addition: " + sum);
System.out.println("Subtraction: " + subtraction);
System.out.println("Mutiplication: " + product);
System.out.println("Division: " + div);
System.out.println("Modules: " + mod);
}
}

b. Increment and Decrement Operator (++, --)

Increment (++) Operator: Increment operator will increase the value of variable by 1 unit

Increment operator are of two types:


1. Pre – Increment.
2. Post – Increment.

Order of Pre – Increment Order of Post – Increment

1. Increment 1. Substitute
2. Substitute 2. Perform operation
3. Perform operation 3. Increment

Note: This order also applies for same Pre – Decrement and Post – Decrement.

 Whenever Pre – Increment and Post – Increment is used without any mathematical
expressions both operators will show same behaviours.
 Whenever the increment operator is used with a character will be increased and its
corresponding character will be stored in the given variable.
 Boolean variable cannot be used with increment operator.
 Values cannot be directly used with increment operator.

Example Program:

class IncrementOpr
{
public static void main(String[] args)
{
int a = 15, b =15;
int res1 = 0, res2 = 0;

System.out.println("Before Pre - Increment a = " +a);


res1 = ++a + 10;
System.out.println("After Performing operation res1 = " +res1);
System.out.println("After Pre - Incrementing a = " +a);

System.out.println("___________________________________ \n");

System.out.println("Before Post - Increment b = " +b);


res2 = b++ + 10;
System.out.println("After Performing Operation res2 = " +res2);
System.out.println("After Post - Incrementing b = " +b);
}
}

Decrement Operator (--): Decrement Operator will decrease the value of a variable by 1 unit.

Decrement Operator are of two types:

1. Pre – Decrement.
2. Post – Decrement.

Order of Pre – Decrement Order of Post – Decrement


4. Increment 4. Substitute
5. Substitute 5. Perform operation
6. Perform operation 6. Increment

 Whenever Pre – Decrement and Post – Decrement used without any mathematical
expressions both operators will show same behaviours.
 Whenever the Decrement operator is used with a character variable then the Unicode value
of the character will be decreased and its corresponding character will be stored in the given
variable.
 Boolean variable cannot be used with Decrement operator
 Values cannot be directly used with Decrement operator.
Example Program:

class DecrementOpr
{
public static void main(String[] args)
{
int a = 15, b = 15;
int res1 = 0, res2 = 0;

System.out.println("Before Pre - Decrementing a = " +a);


res1 = --a + 1;
System.out.println("After Performing Operation a = " +res1);
System.out.println("After Pre - Decrementing a = " +a);

System.out.println("___________________________________ \n");

System.out.println("Before Post - Decrementing a = " +b);


res2 = b-- + 1;
System.out.println("After Performing Operation a = " +res2);
System.out.println("After Post - Decrementing a = " +b);
}
}
c. Comparison operator (==, <=, >=, != )
Comparison operator will compare given two values and produce Boolean result.
Example Program:

class ComparisionOpr
{
public static void main(String[] args)
{
int a = 10, b = 8, c = 10;
boolean result;

System.out.println("a = " +a);


System.out.println("b = " +b);
System.out.println("c = " +c);

result = a > b;
System.out.println("a > b: " +result);

result = a < b;
System.out.println("a < b: " +result);

result = a == c;
System.out.println("a == c: " +result);

result = a != c;
System.out.println("a != c: " +result);

result = a >= b;
System.out.println("a >= b:" +result);

result = a <= c;
System.out.println("a <= c: " +result);
}}

d. Logical operator (&&, || , ^ )


 Logical operator are used to combine multiple Boolean conditions into one single condition
to get one single result.
 Logical operator available in JAVA are.
o && – Logical AND
o || – Logical OR
o ^ – Logical X-OR
 Logical operator should be used only between two Boolean expressions or between two
Boolean variables.
1. Logical AND (&&)
 Logical AND (&&) operator will return TRUE if and only if the result of both the
Boolean conditions result is TRUE and in all other cases it returns FALSE.
 TRUTH TABLE for LOGICAL AND (&&)
CONDITIONS 1 CONDITIONS 2 RESULT
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

Example Program:

class LogicalAND
{
public static void main(String[] args)
{
int a = 15, b = 7, c = 2;
boolean res;
res = a > b && a > c ;
System.out.println(res);
res = a > b && a < c ;
System.out.println(res);

res = a < b && a > c ;


System.out.println(res);

res = a < b && a < c ;


System.out.println(res);

res = b > c && b < a ;


System.out.println(res);
}
}
2. Logical OR (||)
 Logical operator (||) will return FALSE if and only if the result of both Boolean
conditions result is FALSE and in all other cases it returns TRUE.
 TRUTH TABLE for LOGICAL OR (||)
CONDITIONS 1 CONDITIONS 2 RESULT
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

Example Program:

class LogicalOR
{
public static void main(String[] args)
{
int a = 15, b = 7, c = 2;
boolean res;
res = a > b || a > c ;
System.out.println(res);
res = a > b || a < c ;
System.out.println(res);
res = a < b || a > c ;
System.out.println(res);
res = a < b || a < c ;
System.out.println(res);
res = b > c || b < a ;
System.out.println(res);
}
}
3. Logical X-OR (^)
 Logical X-OR (^) operator returns TRUE whenever result of both the Boolean
conditions results are different and in other cases it returns FALSE.
 TRUTH TABLE for LOGICAL X-OR
CONDITIONS 1 CONDITIONS 2 RESULT
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE TRUE

Example Program:

class LogicalXor
{
public static void main(String[] args)
{
int a = 15, b = 7, c = 2;
boolean res;
res = a > b ^ a > c ; // T ^ T = F
System.out.println(res);
res = a > b ^ a < c ; // T ^ F = T
System.out.println(res);
res = a < b ^ a > c ; // F ^ T = T
System.out.println(res);
res = a < b ^ a < c ; // F ^ F = F
System.out.println(res);
}
}

e. Bitwise operator ( &, |, ^)


Bitwise operator will perform bitwise operations on every bit of given value and produce results
as 0 or 1. 25: 100:

2 | 12 – 1 2 | 50 – 0

2|6–0 2 | 25 – 0

2|3–0 2 | 12 – 1

2|1–1 2|6–0

Result: 11001 2|3–0

2|1–1

Result: 1100100
& (Bit - wise AND): & (Bit - wise AND):

25 – 0011001 0000000: 0*264 + 0*232 + 0*216 + 0*28 + 0*24 + 0*22 + 0*21 = 0

100 – 1100100 (&)

0000000 = 0

| (Bit – wise OR): | (Bit - wise OR):

25 – 0011001 0000000: 1*264 + 1*232 + 1*216 + 1*28 + 1*24 + 0*22 + 1*21 = 125

100 – 1100100 (|)

1111101 = 125

| (Bit – wise X-OR): ^ (Bit - wise X-OR):


25 – 0011001 0000000: 1*264 + 1*232 + 1*216 + 1*28 + 1*24 + 0*22 + 1*21 = 125
100 – 1100100 (^)

1111101 = 125

Example Program:

class BitwiseOpr
{
public static void main(String[] args)
{
int a = 25;
int b = 100;
int c;
c = a & b;
System.out.println("Bitwise AND: " + c);
c = a | b;
System.out.println("Bitwise OR: " + c);
c = a ^ b;
System.out.println("Bitwise X-OR: " + c);
}
}
6. Methods / Functions
 Methods are used to eliminate duplicate line of code.

METHOD / FUNCTION

MAIN BLOCK SOLUTION BLOCK

1. Declare output variables. 3. Receive input value and initialize


the input variables
2. Pass the input value to
4. Declare output variable.
solution block.
JVM 5. Process input variable and
7. Receive output value and
initialize output value to output
initialize output variable.
variable.
8. Execute output statement.
6. Return output value in output
variable to previous block.

 Methods are names blocks of codes which will perform a specific task.
 Syntax:

access-specifier access-modifier return type name(arguments)

{
Statement…..

Statement….

 Access – Modifier: static


 Access – Specifier: public, protected, pakage-level, private.
 Return type: depends on the data type of the value returned from the method.
 A method which calling another method is known as calling method.
 A method which called by another method is known as called method.
 A return statement which is used returns the output value and execution control from called method
back to calling method.
 Void is return type of the method which is used whenever the method do not return any value and
only return execution control.
 A programmer can skip the return statement only if the return type of the method is void.
Example Program:

class MethodProg
{
public static void findAc(double r) //user-defined method
{
double opVar=0.0;
opVar=3.141*r*r;
System.out.println( "AREA OF CIRCLE IS :" +opVar);
return;
}
public static void findCc(double r)
{
double opVar;
opVar = 2 * 3.141*r;
System.out.println("Area of Circum of Circle: " + opVar);
return;
}
public static void main(String[] args)
{
System.out.println("Program Starts");
findAc(5);
findCc(6);
System.out.println("Program Ends");
}
}

7. Flow Control Statements


 Flow Control Statements are used to control the execution flow of the program at the runtime.
 Flow Control Statements are of Two types
1. Decision Making Statement
2. Looping Statement
1. Decision Making Statement:
 Decision Making Statement are used to execute one or more group of statements based on
a condition.
 Decision Making Statements are of FOUR type.
1. If Statement.
2. If else Statement.
3. If else if Statement.
4. Switch Statement.
1. if Statement: It is a type of decision making statement where one or group of
statement written within the if body will be executed if and only if result of Boolean
Condition is true.

Syntax: if (Boolean Condition)


{
Statement...
Statement...
}

Example:
class IfStatement
{
public static void test(int number)
{
if ( number > 0)
{
System.out.println(number + " is positive number");
}
}
public static void main(String[] args)
{
test(23);
}
}

2. if else Statement: It is a type of decision making statement where statement of if


body are executed if result of Boolean condition is true else the statement of else
body are executed.

Syntax: if(Boolean Condition)


{
Statement...
Statement...
}
else
{
Statement...
Statement...
}
Example:

class IfElseStatement
{
public static void test(int number)
{
if ( number > 0)
{
System.out.println(number + " is positive number");
}
else
{
System.out.println(number + " is negative number");
}
}
public static void main(String[] args)
{
test(23);
test(-12);
}
}

3. if else if Statement: It is type of decision making statement which is used whenever


there are multiple Boolean condition to evaluated to execute different set of
statements

Syntax: if(Boolean Condition)


{
Statement...
Statement...
}
else if(Boolean Condition)
{
Statement...
Statement...
}
else
{
Statement...
Statement...
}

Example:

class IfElseIfStatement
{
public static void test(int num)
{
System.out.println("Number:" + num);
if(num > 10 )
{
System.out.println(num + " is greater than 10");
}
else if(num < 10)
{
System.out.println(num + " is lesser than 10");}
else
{
System.out.println(num + " is equals to 10");
}
}

public static void main(String[] args)


{
test(50);
test(5);
test(10);
}
}

4. switch Statement: It is a type of decision making statement which is used whenever


there are only equals conditions to be evaluated to execute different set of
statement.

Syntax: switch(option)
{
case choice 1: statement...
break;
case choice 2: statement...
break;
...
...
default: statement...
}

Example:

class SwitchCase
{
public static void test(int option)
{
switch(option)
{
case 1 : System.out.println("Game Stars..");
break;
case 2 : System.out.println("Show Game Scores...");
break;
case 3 : System.out.println("Exit");
break;
default : System.out.println("Invalid option");}}
public static void main(String[] args)
{
test(1);
test(2);
test(3);
test(5);} }

2. Looping Statements:
 Looping statements are used to execute one or multiple statements repeatedly.
 Looping statements are of FOUR types.
1. for loop.
2. while loop.
3. do while loop.
4. for – each loop.

1. for loop: for loop used whenever logical start and logical end is very defined.
Syntax:
Start Check did you reach the end

for(initialization; stop-condition; counter)


{
statement...
statement...
}
Example:
public class ForLoop
{
public static void print5()
{
for(int i = 1; i <= 5; i++)
{
System.out.print(i+" ");
}
}
public static void print5Reverse()
{
for(int i = 5; i >= 1; i--)
{
System.out.print(i+" ");
}
}
public static void charIncrement1()
{
for(char i = 'A'; i <= 'E'; i++)
{
System.out.print(i+" ");
}
}

public static void charIncrement2()


{
for(int i = 'A'; i <='E'; i++)
{
System.out.print(i+" ");
}
}
public static void hello()
{
for (int i = 1; i <= 5; i++ )
{
System.out.println();
System.out.println("HELLO");
}
}
public static void main(String[] args)
{ OUTPUT:
print5();
1 2 3 4 5
System.out.println(); 5 4 3 2 1
print5Reverse(); A B C D E
65 66 67 68 69
System.out.println();
charIncrement1(); HELLO

System.out.println(); HELLO
charIncrement2();
HELLO
System.out.println();
hello(); HELLO

} HELLO
}

2. while loop: while loop is looping statement where statement within the loop
executed repeatedly until the Boolean condition becomes false.
Syntax: while(Boolean Condition)
{
statement...
statement...
}
Example:
Program 01:
// Write a Program to find whether the given number is PALINDROME or NOT

class WhileLoop
{
public static void palindromeNum(int num)
{
int last = 0, res = 0;
int orgl = num;
System.out.println("Original Number : " + orgl);
while(num!=0)
{
last = num % 10;
num = num / 10;
res = res * 10 + last;
}
if (orgl == res)
{
System.out.println(res + " is palindrome");
}
else
{
System.out.println(res + " is not palidrome");
}
}
public static void main(String[] args)
{
palindromeNum(121);
System.out.println();
palindromeNum(123);
}
}
Program 02:
// Write a Program to return sum of smallest and largest Digit in given
number.
class SumSmlLar
{
public static void smallLarge(int num)
{
int small = 0,large = 0, last = 0, sum = 0;
System.out.println("Given Number: " + num);
small = num % 10;
while(num!=0)
{
last = num % 10;
num = num / 10;
if(last < small)
{
small = last;
}
else
{
large = last;
}
}
sum = small + large;
System.out.println("Smallest number: " + small);
System.out.println("Largest number: " + large);
System.out.println("sum of " + small + " + " + large + " = "
+ sum + "\n");
}
public static void main(String[] args)
{
smallLarge(123);
smallLarge(958);
}
}
Program 03:
// Write a function that returns smallest digit from the given number

class SmallestDigit
{
public static int smallNumDigit(int num)
{
int last = 0, small = 0;
small = num % 10;
System.out.println("Given Number is: " +num);
while(num!=0)
{
last = num % 10;
num = num / 10;
if(last < small)
{
small = last;
}
}
return small;}
public static void main(String[] args)
{
int opVar;
opVar = smallNumDigit(235);
System.out.println("Smallest number is: " + opVar);
}
}

Program 04:
/* Write a function that returns true if the given number is a special
number.
Example: num = 59
product: 5 * 9 = 45
sum: 5 + 9 = 14

45 + 14 = 59
*/
class SpecialNumber
{
public static boolean specialNumber(int num)
{
int last = 0, sum = 0, product = 1, special = 0;
int original = num;
System.out.println("Given Number is : " + original);
while(num!=0)
{
last = num % 10;
num = num / 10;
sum = sum + last;
product = product * last;
special = sum + product;
}
System.out.println("Product of all Digits: " + product);
System.out.println("Sum of all Digit: " + sum);
System.out.println("Sum of " + product + " + " + sum + " = "
+ special);
if(original == special)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
boolean opVar;

opVar = specialNumber(59);
System.out.println(opVar + "\n");

opVar = specialNumber(958);
System.out.println(opVar + "\n");

opVar = specialNumber(49);
System.out.println(opVar + "\n");
}
}

Program 05:
/* Write a Function that returns true if the given number is 'NEON'
number.
Example: 9 -> 9^2 = 81
= 8 + 1
= 9
*/
class NeonNumber
{
public static boolean neonNumber(int num)
{
int last = 0, sum = 0, original = 0;
original = num;
System.out.println("Given number is: " +num);
num = num * num;
System.out.println("9^2 : " + original + " * "
+ original + " = " + num );
while(num!=0)
{
last = num % 10;
num = num / 10;
sum = sum + last;
}
if(original == sum)
{
return true;
}
else
{
return false;}}
public static void main(String[] args)
{
boolean opVar;
opVar = neonNumber(9);
System.out.println(opVar + "\n");

opVar = neonNumber(19);
System.out.println(opVar + "\n");

opVar = neonNumber(1);
System.out.println(opVar + "\n");

opVar = neonNumber(0);
System.out.println(opVar + "\n");
}
}

Program 06:
/* Write a function that returns true if the given number is Spy number
Example: num = 1124
sum = 1 + 1 + 2 + 4 = 8
product = 1 * 1 * 2 * 4 = 8
*/
class SpyNumber
{
public static boolean spyNumber(int num)
{
int last = 0;
int sum = 0, product = 1;
//int original = num;
System.out.println("Given Number: " + num);
while(num!=0)
{
last = num % 10;
num = num / 10;
sum = sum + last;
product = product * last;
}
//System.out.println("Sum of all the Digit in given "
+ original + " is: " + sum);
//System.out.println("Product of all the Digit in given "
+ original + " is: " + product);
if(sum == product)
{
return true;}
else
{
return false;
}
}
public static void main(String[] args)
{
boolean opVar;

opVar = spyNumber(1124);
System.out.println("Result: " + opVar +"\n");

opVar = spyNumber(1123);
System.out.println("Result: " + opVar);
}
}

3. do while loop:
 The do keyword is used together with while to create a do-while loop.
 The while loop loops through a block of code as along as a specified condition
is true
 The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.
 Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end.
 Syntax: do
{
statement...
statement...
} while(Boolean Condition);
Example:
class DoWhile
{
public static void main(String[] args)
{
int i;
i = 3;
do
{
System.out.println(i+3);
i--;
}while(i!=0);
}
}

8. Arrays
Array is a group of same type of a data which has a fixed length and index to identify every bucket uniquely.

1 2 3 4 5 6 7 8 9

Value 7 11 16 65 20 35 99 77 88
0 1 2 3 4 5 6 7 8

Lower Upper
Bound Bound

Array Length = 9
 Array Declaration
[ ] -> Subscript

Syntax: datatype[ ] arrayVarname; Example: int [ ] arr;

or or

datatype arrayVarname[ ]; int arr[ ];

 Array Creation

Syntax: arrayVarname = new datatype[size];

Example: arr = new int[10];

 Array Declaration and Creation


 Syntax: datatype[ ] arrayVarname = new datatype[size];

Example: int[ ] arr = new int[10];

 Syntax: datatype[ ] arrayVarName = {v1, v2, v3…};


Example: int[ ] arr = {20,40,12};

 Once the array is created all the buckets will be filled with default values depending on the data type
of the array.
 Length is an in-built variable which contains the count of no. of buckets in the given array.
 First index : 0 (lower bound)
 Last index: arr.length – 1 = 9-1 = 8 (upper bound).
 Mid index: (arr.length - 1)/2 = (9 – 1)/2 = 4(middle bound)

Example:

Program 01:
//Write a Program to give sum of all given number.
class ArrayProg1
{
public static void test(int[] num)
{
int i,add,sum = 0;
for(i = 0; i < num.length; i++)
{
sum = sum + num[i];
}
System.out.println("sum of all given elements: " +sum);
}
public static void main(String[] args)
{
int n[] = {1,2,3,4,5};
test(n);
}
}

Program 02:
/*
Write a Program which returns true if 6 appears as either the first or last
in the array. The array will be length 1 or more.

*/
class ArrayProg2
{
public static boolean test(int[] num)
{
if(num[0] == 6 || num[num.length-1] == 6)
return true;
else
return false;
}
public static void main(String[] args)
{
int arr1[] = {1,2,3,4,6};
System.out.println(test(arr1));
int[] arr2 = {1,3,4,5};
System.out.println(test(arr2)); }}
Program 03:
import java.util.Arrays;
class ArrayProg3
{
public static void main(String args[])
{
int arr[]; // array declaration
int arr2[]={1,2,3,4}; // array creation
System.out.println("at the index of 0: " + arr2[0]);
System.out.println("at the index of 1: " + arr2[1]);
System.out.println("at the index of 2: " + arr2[2]);
System.out.println("at the index of 3: " + arr2[3]);
System.out.println(Arrays.toString(arr2));
System.out.println("Length of an array: " + arr2.length);
char[] arr3 = new char[5]; //array declaration and creation
arr3[0] = 'A';
arr3[1] = 'B';
arr3[2] = 'C';
arr3[3] = 'D';
arr3[4] = 'E';
System.out.println("elements of 'character array' are: " + Arrays.toString(arr3));
System.out.println("Length of an 'character array': " +arr3.length);
}
OUTPUT
}
at the index of 0: 1
at the index of 1: 2
at the index of 2: 3
at the index of 3: 4
[1, 2, 3, 4]
Length of an array: 4
elements of 'character array' are: [A, B, C, D, E]
Length of an 'character array': 5
9. Strings
 String value is a group of characters which is written in the double quotes( “ ” ).
 We can access the characters or perform any operations on the string only by using the
methods of strings.
 Internally string value is stores as a character array by the JVM.
 By default string class is final in java.
 String is a non-primitive-data type.
 In Java we have three final classes.
1. String

2. StringBuffer

3. StringBuilder

 In two ways we can declare a String


1. without using new keyword
Syntax: String objectName;

Example: String str = "someone";

2. Using new keyword.

Syntax: String objectName = new String();

Example: String str = new String("someone");

 Example program:
public class StringProg1
{
public static void main(String[] args)
{
String str1 = "someone";
System.out.println("String1: " + str1);

String str2 = new String("unknown");


System.out.println("String2: " + str2);
}
}
 Methods of String
1. Length(): It returns the count of numbers of characters present in the given string.
Example:
class StringProg2 OUTPUT:
{
Given Str1: Hello World
public static void main(String[] args)
Length of 'str1': 11
{
String str1 = "Hello World";
System.out.println("Given str1: " + str1);
System.out.println("Length of 'str1': " + str1.length());
}
}

2. charAt(index): It returns the character at the given index from the given string.
Example:
class StringProg2 OUTPUT:
{ Given str1: Hello World
public static void main(String[] args) charAt(6): W
{
String str1 = "Hello World";
System.out.println("Given string: " + str1);
System.out.println("charAt(6): " + str1.charAt(6));
}
}

3. indexOf(char): It returns the index of the given character from the given String. It returns negative value if
the character do not exist.
Example:
OUTPUT:
class StringProg2
{ Given string: Hello World

public static void main(String[] args) indexOf(o): 4

{
String str1 = "Hello World";
System.out.println("Given string: " + str1);
System.out.println("indexOf(o): " + str1.indexOf('o'));
}
}
4. indexOf(char,startIndex): It returns the index of the given character from the given String by starting the
search from the given startIndex. OUTPUT:
Example: Given string: Hello World

class StringProg2 indexOf('o',0): 4

{
public static void main(String[] args) indexOf('o',5): 7
{
String str1 = "Hello World"; indexOf('W',4): 6
System.out.println("Given string: " + str1 + "\n");
//System.out.println("Syntax: indexOf(char,startIndex) \n");
System.out.println("indexOf('o',0): " + str1.indexOf('o',0) + "\n");
System.out.println("indexOf('o',5): " + str1.indexOf('o',5) + "\n");
System.out.println("indexOf('W',4): "+ str1.indexOf('W',4) + "\n");
}
}

5. equals(string): It compares characters of given two strings and returns true if they are exactly same else it
returns false.
OUTPUT:
Example:
Given str1: Hello World
class StringProg2
Given str2: Hello World
{
Given str3: Hello
public static void main(String[] args)
Is str1 equals to str2: true
{
Is str1 equals to str3: false
String str1 = "Hello World";
String str2 = "Hello World";
String str3 = "Hello";
System.out.println("Given str1: " + str1);
System.out.println("Given str2: " + str2);
System.out.println("Given str3: " + str3);
System.out.println("Is str1 equals to str2: " + str1.equals(str2));
System.out.println("Is str1 equals to str3: " + str1.equals(str3));
}
}

6. equalsIgnoreCase(string): It compares characters of given two strings by ignoring the case and returns true if
they are exactly same else it returns false. OUTPUT:

Example: Syntax:
equalsIgnoreCase(objectName)
class StringProg2
{
Given str1: Hello
public static void main(String[] args)
Given str2: hello
{
Given str3: Hell@
String str1 = "Hello";
str1 and str2: true
String str2 = "hello";
str1 and str3: false
String str3 = "Hell@";
System.out.println("Syntax: equalsIgnoreCase(objectName) \n");
System.out.println("Given str1: " + str1);
System.out.println("Given str2: " + str2);
System.out.println("Given str3: " + str3);
System.out.println("str1 and str2: " + str1.equalsIgnoreCase(str2));
System.out.println("str1 and str3: " + str1.equalsIgnoreCase(str3));
//System.out.println("Comparing Between '" + str1 +"' and '" + str2
+ "': " + str1.equalsIgnoreCase(str2));
//System.out.println("Comparing Between '" + str1 +"' and '" + str3
+ "': " + str1.equalsIgnoreCase(str3));
}
}

7. substring(startIndex, endLength): It creates a String from the given startIndex and given end-1 index no. of
characters and returns the string.
Example:
class StringProg2
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "hello";
String str3 = "Hell@";
System.out.println("Syntax: substring(startIndex, endLength) \n");
System.out.println("Given String: " + str1);
System.out.println("Length of a Given string: " + str1.length());
System.out.println("str1.substring(1,4): " + str1.substring(1, 4));
System.out.println("str1.substring(str1.length()-2,str1.length()): "
+ str1.substring(str1.length()-2,str1.length()));
}
} OUTPUT:
Syntax: substring(startIndex, endLength)

Given String: Hello


Length of a Given string: 5
str1.substring(1,4): ell
str1.substring(str1.length()-2,str1.length()): lo

NOTE: length: variable used in array.


Length (): method of string.

You might also like