0% found this document useful (0 votes)
36 views

Java

The document discusses various concepts in Java programming including identifiers, literals, separators, operators, and data types. Identifiers name classes, methods, and variables and have specific naming rules. Literals represent constant values like integers and strings. Separators divide code blocks. Operators perform operations on variables and expressions. Java has primitive data types like integers and floating-point numbers, as well as reference types for objects.

Uploaded by

M Usmitha
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Java

The document discusses various concepts in Java programming including identifiers, literals, separators, operators, and data types. Identifiers name classes, methods, and variables and have specific naming rules. Literals represent constant values like integers and strings. Separators divide code blocks. Operators perform operations on variables and expressions. Java has primitive data types like integers and floating-point numbers, as well as reference types for objects.

Uploaded by

M Usmitha
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 41

Identifiers

The purpose of identifier is for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.

Rules

1. They must not begin with a digit.


1. Uppercase and lowercase letters are different.
2. They can be of any length.
3. They can have alphabets, digits and the underscore and dollar sign

characters. Various naming conventions have to follow when declaring identifiers.

1. Names of all public methods and instance variables start with a lowercase letter.
1. When more than one word is used in a name, the second and subsequent words are
marked with uppercase letters.
2. All private and local variables use only lowercase letters combined with underscore.
2. All classes and interfaces start with uppercase letter.
3. Variables that represent constant values use uppercase letters.
Literals or constants in java

Literals in Java are sequence of characters that represent constant values to be stores
in variables. Java specifies 5 major types of literals.

 Integer literal.
 Floating point literal.
 Character literal.
 String literal.
 Boolean literal.

Ex: final int x=10; final float pi=3.14f;

Separators

Separators are symbols used to indicate where groups of code are divided and
arranged.

Name Use

It is used in method and expression and surrounding


Parenthesis ( )
cast types.

It is used to automatically initialize values of an array,


Braces { }
define block of code for classes and methods.

Square brackets [ ] It is used to declare array type and values.

Semicolon ; Used to separate statements

Used to separate consecutive identifiers in variable


Comma ,
declaration.

Period . Used to separate package name from sub packages.

Operators

Operator is a symbol that takes one or more arguments and operates on them to
produce a result. Java supports a rich set of operators like arithmetic operators, relational
operators, logical operators, and bitwise operators.

Arithmetic operators

These operators are used to perform arithmetic operations on variables and to


construct mathematical expressions.

Operator Meaning

+ Addition

- Subtraction

* Multiplication
/ Division

% Modulo division (remainder)


Mixed Mode

When one of the operand is real and other is integer then the operation is called
mixed mode arithmetic expression.

Ex: 15 / 10.0 = 1.5 where as 15/10 = 1

Relational operators

These are used to test for equality of expressions. These result either true or false
value.

Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to
Logical operators

Logical operators are used to form compound conditions by combining two or more
relational expressions.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT
Assignment operators

Assignment operator is used to assign the value of an expression to a variable. Java


has a set of shorthand assignment operators which are used in the form:

Variable op=exp;

Simple assignment operator is = (equal to). The general syntax of simple assignment
operator is

Variable = constant or expression;

Increment and decrement operators

Java has two very useful operators not generally found in many other languages.
These are increment (++) and decrement (--) operators. The operators ++ adds 1 to the
operand while – subtracts 1 from the operand. Both are unary operators and are used in the
following form:
Conditional operator

The ? : is a ternary operator available in Java. The operator is used to construct


conditional expression in Java.

Syntax: exp1 ? exp2 : exp3;

The exp1 is evaluated first. If it returns true, the exp2 is evaluated, else the exp3 is
evaluated.

Ex: c = (a>b? a : b );

Bitwise operators

Java has set of bitwise operators to manipulate data at bit level. Bitwise operators
may not be applied for float or double.

Operator Meaning

& Bitwise AND

! Bitwise OR

^ Bitwise exclusive OR

~ Bitwise one’s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill


Special operators

Java supports special operators such as instanceof operator and member selection
operator.

Instanceof:

It is an object reference operator and returns true if the object on the left side is the
instance of the class given on right side otherwise it returns false.

Ex: sai instanceof student;

The statement is true if the object sai belongs to the class student.

DOT operator:

The dot (.) operator is used to access the instance variables and methods of class
objects.

Ex: sai.age; sai.total_marks ();


q)Explain Operators and their precedence ?

Priority Operator Associativity

1 . () L to R

2 -, ++, --, !, ~, (type) R to L

3 *, /,% L to R

4 +,- L to R

5 << , >> , >>> L to R

6 <, <=, >, >=, instanceof L to R

7 ==, != L to R

8 to 10 &, ^, | L to R

11 , 12 && and || L to R

13 ?: R to L

14 = R to L

Q. Explain different data types available in Java?

A data type defines the set of values that an expression produced or a variable can
contain. The data type of variable or expression also defines the operation that can be
performed on the variable or expression. The type of variable is established by the variable
declaration while the type of an expression is determined by the definitions of its operations
and the type of their operands.

Conceptually there are two types of data types in Java program primitive
types

4 DATA TYPES

Primitive (Intrinsic)
JAVA
Data
types

Non- Primitive (Derived)

Numeric
Non - numeric

Classes Interface Arrays

Floating point
Integer
Character Boolean

24 | P a g
Figure 7: Data Types in Java.
Primitive type

It is also called as built-in types or intrinsic data types. A primitive data type
represents a single value such as a number or character or a Boolean value. Java has
primitive types for arithmetic and Boolean.

Arithmetic

There are two types of arithmetic type’s integer and floating point.

Integer types are byte, short, int, long and char. Floating point types are float and double.

Floating point types Java provides two sizes of floating point number single precision,
double precision.

Normally non-zero float values are represented as:

Sign mantissa 2 ^exp, where sign is +1 or -1. Mantissa is a +ve integer less than 224 and
exponent is an integer in the inclusive range -149 to 104.

Non-zero double values are represented as:

Sign mantissa 2^exp, where sign is +1 or -1, mantissa is a +ve integer less than 253 and
exponent is an integer inclusive range -1045 to 1000.

The representation of primitive types and its ranges as follows.

Data type Representation size range

Byte 8 bit signed -128 to 127

Short 16 bit signed 132768 to 32767

Int 32 bit signed -2147483648 to 2147483647

-9223372036854775808 to
Long 64 bit signed
9223372036854775807

Char 16 bit unsigned Unicode Holds a single character

-38 +38
Float 32 bit 3.4 e to 3.4 e
-308 +308
Double 64 bit 1.7 e to 1.7 e

Boolean type

The Boolean data type represents two values true or false. These values are key
words in Java. Java provides the following kinds of operators for Boolean values.

1. Equality and inequality operations


1. Boolean logical
operators. 3.

Character type
Java provides a character data type called char. The char occupies two b y2 t5e|
P a g
s b u t basically it can hold only a single character.
Constants

Constants in java refer to fixed values that do not change during the program execution
of a program. Java supports several types of constants.

1. Numerical constants.
a. Integer constants.
b. Real constants.
2. Character constants.
a. Single character constants
b. String constants

Integer constants refer to a sequence of digits. There are three types of integer’s namely
decimal, octal and hexadecimal integers.

Ex: 123, -321, O37 (octal), Ox2, Ox9f (hexadecimal).

Real constants used to represent the numbers containing fractional parts. A real number
may also be expressed in exponential notation also.

Ex: 215.65, 0.65e4, 12e-2

Single Character constants contain a single character enclosed within a pair of single
quotation marks.

Ex: ‘a’. ‘5’, ‘\n’

Backslash character constants

Java supports some special backslash character constants that are used in output
methods. These characters combinations are known as escape sequences.

Constant Meaning
\b backspace
\fform feed
\n new line
\r carriage return
\t horizontal tab
\’ single quote
\” double quote
\\ backslash

String constant is a sequence of characters enclosed between double quotes. The


characters may be alphabets, digits, special characters, and blank spaces.

Ex: “sai”, “2010”, “5+3”

Symbolic Constants

The constants may appear repeatedly in a number of places in the program. A


constant is declared as follows.

Ex: final float pi=3.14f;

Variables
The variables are the names of storage locations. A variable must be declared before
it is used in the program. A variable can be used to store a value of any data type. The
declaration statement defines the type of variable. The declaration of variable is:
Type variable1, variable2, ……., variable N;
26 | P a g
Scope of variables

Java variables are generally classified into three types.

 Instance Variables
 Class variables
 Local variables

) Local Variables

Local Variables are a variable that are declared inside the body of a method.

2) Instance Variables

Instance variables are defined without the STATIC keyword .They are defined Outside a method
declaration. They are Object specific and are known as instance variables.

3) Static Variables

Static variables are initialized only once, at the start of the program execution. These variables
should be initialized first, before the initialization of any instance variables.

Type casting

Type casting means represent a value of type into a variable of another type. Casting
into a smaller type may result in a loss of data. For some types java does the conversion of
the assigned value automatically; there is no need of cast. This is known as automatic type
conversion. Automatic type conversion is possible only if we are assigning values into higher
precision types.

Syntax: type variable = (type) value; Ex:

int m=60; byte n=(byte) m;

Q. Explain Command Line arguments in Java?

Command line arguments are parameters that are supplied to the application program
at the time of invoking it for execution. It is also known as command line arguments.

/**example of command line arguments */


class ComLine
{
public static void main(String args[])
{
int count,i=0;
count=args.length;
System.out.println("number of arguments = " +count);
while(i<count)
{
System.out.println(argument " + i + " = " + args[i]);
i++;
}
}
}
27 | P a g
In the above program, args declared as a array of strings, each individual element is
accessed by using an index like args[i], the index starts from 0.
Q. Explain different types of variables?

Depending on the content hold by the variable, the variables are divided into two
types.

1. Reference variable
1. Primitive variable.

Reference variable:

String s=”java”;

Here s is a string object.

Primitive can be used to hold primitive values.

int i=10;

Depending on the position at which the variable is declared, are divided into 3 types.

1. Instance variable
1. Static variable
2. Local variable

Instance variable:

1. If the value of variables is varied from instance to instance, such type of variables is
called instance variables.
2. We can declare instance variables within a block, but outside of any method or block.
1. These are also known as attributes / properties / member variables.
3. The instance variable will create whenever an object is created and destroyed
whenever garbage collector destroys the object.
4. Instance variables will get default values and no need to perform explicit initialization.

Ex:

class Test
{
int a;
public static void main(String args[])
{
Test obj=new Test();
System.out.println(obj.a);
}
}

Static variable:

1. A single copy of the static variable will maintain and shared by all instances.
1. The value of the static variable is the same for all instances.
2. The static variables will create whenever the class loaded into memory and destroy
whenever the class is unloaded from memory.
3. These variables are also known as fields.
4. Static variables will get default values and no need to perform explicit initialization.
5. Static variables we can access by using either class name or by using the object
reference.
Local variables:

1. The variables which are declared inside a method or block or as method arguments
are called local variables.
2. Also known as temporary variables.
1. The local variables will create as the part of the method execution and will destroy
whenever the method termination.
2. The local variables never get default values and must be initialized before using those
local variables.

Q. What are the ways to scan the data from the standard input device?

1. System.in.read()
1. Scanner class
2. Command line arguments
3. Stream classes

System.in.read()

It behaves like a getch() in C language, which reads a single character only. It doesn’t
read a group of characters.

Ex:
Char ch;
Ch=(char)System.read();

Scanner Class

Scanner class is defined in java.util package. It is used to scan the primitive types
from input resources (jdk 1.5).

int nextInt()
float nextFloat()
boolean nextBoolean()
char nextChar()
String next()
string nextLine()
double nextDouble()
Long nextLong()
byte nextByte()
Short nextShort()

Ex:
Scanner sc= new Scanner(System.in); int a =sc.nextInt();

Example:

import java.util.*; class UserInputDemo [


public static void main(String[] args)
{

29 | P a g
Scanner sc= new Scanner(System.in); //System.in is a standard input
stream System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
int c=a+b;
System.out.println("Total= " +c);
}
}
Example2:
import java.util.*;
class UserInputDemo1
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string
System.out.print("You have entered: "+str);
}
}
Stream class

A stream is a sequence of data. A program uses an input stream to read data from a
source, one item at a time. The DataInputStream available in java.io package is used to read
data from input stream and also from the file streams.

Ex:
DataInputStream in = new DataInputStream(System.in);
int x=Integer.parseInt(in.readLine());

Another method of using Stream classes to read input from the keyboard are using
the classes InputStreamReader and BufferedReader.

Ex:
import java.io.*;
class InputExample
{
public static void main(String args[]) throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
int x;
x= Integer.parseInt(br.readLine()); System.out.println(“x value = “ + x);
30 | P a g
}
}

Q) How to display formatted output with string format()?

public class FormatExample3


{
public static void main(String[] args)
{
String str1 = String.format("%d", 101);
String str2 = String.format("|%10d|", 101); // Specifying length of integer
String str3 = String.format("|%-10d|", 101); // Left-
justifying within the specified width
String str4 = String.format("|% d|", 101);
String str5 = String.format("|%010d|", 101); // Filling with zeroes
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}
101

101
101

101
0000000101
Q. Explain various Mathematical functions available in Java?

Mathematical functions such as cos, sqrt, log etc. are frequently used in analysis of
real life problems. Java supports these basic math functions through Math class defined in
the java.lang package. These functions should be used as follows.

Math.function_name();

Ex: double y= Math.sqrt();

The various functions available with the Math class are listed below.

Function Action
sin(x) Returns the sine of the single x in radians

cos(x) Returns the cosine of the angle x in radians


Function Action

tan(x) Returns the tangent of the angle x in radians

asin(y) Returns the angle whose sine is y

acos(y) Returns the angle whose cosine is y

atan(y) Returns the angle whose tangent is y

pow(x,y) Returns x raised to y (xy)

exp(x) Returns e raised to x (ex)

log(x) Returns the natural logarithm of x

sqrt(x) Returns the square root of x (double precision)

abs(x) Returns the absolute value of x

max(a,b) Returns the maximum of a and b

min(a,b) Returns the minimum of a and b


Returns the smallest whole number greater than or equal
ceil(x)
to x.
floor(x) Returns the largest whole number less than or equal to x.

rint(x) Returns the truncated value of x.

round(x) Returns the integer closest to the argument.

Decision Making and Branching

Q. Explain different branching statements available in Java?

In the term software or computer programming, it has a set of instructions called


program. These instructions are also called statements, which occurs sequentially or in either
conditional way or in the iterative way. To handle such types of statements, some flow of
controls required. These flow controls are called control statements.

In other words, the control statements are used to control the cursor in a program
according to the condition or according to the requirement in a loop. Further we can say,
changing the order of flow controls, these are required. There are mainly three types of
control statements or flow controls. These are illustrated as below:

1. Branching
1. Looping
2. Jumping

Branching statements

It is also called decision making statement. These are used when a condition arises in
1. If statement
1. If statement
1. Switch statement
2. Conditional operator

If statement:

The if statement is a powerful decision making statement which can handle a single
condition or group of statements. These have either true or false action. There are mainly
four types of if statements used in java are as:

1. Simple if statement
1. If else statement
2. Nested if statement
3. Else – if statement or multi condition if statement.

Simple if statement:

When only one condition occurs in a


statement then simple if statement is used having one block. The general syntax of
simple if statement is:

if (condition)
{
True statement block;
}
Statement –x;

Here first of all condition will be


checked. If condition is true, then the
true statement block will be executed
and after execution, statement –x will be
executed. Note that both the times
statement –x will be executed.

If – else statement:

This statement also has a single condition with two different blocks. One is true block
and the other is false block. The general syntax is used as:
if (condition)
{

}
else
{

}
True statement block;

False statement block;


Statement –x;

In this statement block, first of all condition will be checked. If condition is true then true
statement block will be executed and after execution of the block, statement – x will be executed.
If the condition is

33 | P a g
false then the false statement block is executed followed by statement –x. note that in both
the cases statement –x will be executed.
Nested – if statement:

When an if statement occurs within another if statement, then such type of statement
is called nested if statement. The general syntax of this statement is as:

if(condition1)
{
if(condition2)
St – 1;

}
else
{
else

St – 2;
if (condition3)
St – 3;
else

St – 4;
Statement – x;

First of all condition1 will be executed. If it is true, then further condition2 will be checked. If
condition2 is true, then st-1 will be executed and after execution of st-1, statement-x will be
executed. But if condition2 is false, then st-2 is executed. Similarly if condition1 is false, the
else block of condition1 is executed, in that first condition3 is executed, if it is true then st-3
otherwise st-4 is executed. In any case, after the execution of block, the statement-x is
followed.

Ladder if statement of if else if statement:

In a complex problem, no. of conditions arise in a sequence, then we can use ladder if
or else if statement to solve the problem in a simple manner. In this statement 1 st condition
will be checked, if it is true then action will be taken, otherwise further next condition will be
checked and this process will continue till the end of the conditions. The general syntax is as:

If(condition1)
St-1;
Else if
(condition2)
St-2;
Else if
(condition3)
St-3;
.
.
.
.
Else if (condition n)
St – n;
Else
False statement;
Statement-x;
Switch statement:

When no. of conditions occurs in a problem and it is very difficult to solve such type of
complex problem with the help of ladder if statement. Then there is need of such type of
statement which should have different alternatives or different cases to solve the problem in
simple and easy way. For this purpose switch statement is used. It is also called case
statement because it has different cases and different blocks. It is also called multi decision
statement having multiple blocks. The float type of values is not accepted in switch
statements. The general syntax of the switch statement is:

switch(e or v)
{
case value1: block1;
break;
case value2: block2;
break;
…………………….
case value n: block n;
break;
default: block n+1;
}
Statement –x;

Where e is an arithmetic expression and v is a variable.


Conditional operator (?:):

Conditional operator or also called as ?: operator or ternary operator. This operator is


used instead of block if statement. The general syntax of conditional operator is as:

expr1? expr2: expr3;

Here first of all expr1 is computed, which is a conditional expression. If expr1 is true,
then expr2 will be executed. But if expr1 is false, then expr3 will be executed. Note that
expr2 and expr3 are either a single constant value or a single variable or an arithmetic
expression. For example, below is an if statement having a and b two variables as:

a=10; b=5;
if (a>b)
c=a-b;
else
c=b-a;

The above if statement can be write by using the conditional operator in a single statement
as:

c= (a>b)? a-b: b-a;


ecision Making and Looping

Q. Explain different looping statements available in Java?

( or) iterative stetments?

Looping statement:

When a single statement or group of


statements will be executed again and again
in a program (in an iterative way), then such
type of processing is called loop.

Entry Control Loop:

In entry control loop first of all


condition is checked, if it is true, then body of
loop is executed, otherwise the control is
moved out of the loop i.e. we can exit from
the loop, when the condition becomes false.
The while loop and for loops are the example
of the entry controlled loop. The flow symbol for entry control loop is as:

Exit Control loop:

In the exit control loop, first body of


loop is executed and then condition is
checked. If condition is true, then again
body of the loop is executed. If the
condition is false, then control will move out
from the loop. Example of exit control loop
is do statement. The general flow symbol is:

While statement:

While statement or while loop is an


entry control loop. In this, first of all
condition is checked and if it is true, then
group of statements or body of loop is
executed. It will execute again and again till condition becomes false. The general syntax is:
while (test condition)
{
block of statements;
}
statement-x;

Do statement or Do-loop:

Do statement is exit control loop. It is also called do-while statement. In this


statement, first body of the loop is executed and then the condition is checked. If condition is
true, then the body of the loop is executed. When condition becomes false, then it will exit
from the loop. The syntax of do-loop is as follows:

do
{
block of statements;
} while (condition); statement-x;

Note that semicolon must be at the end of the while condition.


37 | P a g
c) For statement or for loop:

It a-looping statement, which repeat again and again till it satisfies the defined
condition. It is one step loop, which initialize, check the condition and increment decrement
the step in the loop in a single statement. The general syntax is as:

for (initial value; test condition; increment/ decrement)


{
body of the loop;
}
statement-x;

It is also entry controlled loop, where first condition is checked and the body of the
loop be executed. In this case, first we initialize the value, then in the loop we apply the
condition and further we increment or decrement the loop according to requirement. After
execution or completion of the body of the loop when the condition becomes false, the
statement-x will be executed.

d) Nested for statement:

When a for statement is executed within another for statement, then it is called
nested for statement. We can apply number of nested for statements. The general syntax is:

for (initial value1; test condition1; increment1/decrement1)


{
for (initial value2; test condition2; increment2 /decrement2)
{
inner- body of the loop;
}
outer-body of the loop;
}
statement-X;

For one value of outer loop, inner loop will repeat n times. So inner loop will be
completed first and then outer loop will be completed. After completion of inner and outer
loop, statement-x will be executed.

The Enhanced For Loop

The enhanced for loop, also called for each loop, is an extended language future
introduced with the J2SE 5.0. This for loop used to retrieve the array of elements efficiently
rather than using array indexes. The syntax is as follows:
for ( type identifier : expression)
{
Statements;
}
Where type represents the data type or object used; identifier refers to the name of a
variable; and expression is an array.
Consider the following the example
int a[3]={10, 20, 30};
for (int k=0;k<3;k++)
{ System.out.println(a[k]); } Which is
equivalent to the following code:
int array[3]={10, 20, 30};
for (int k:array)
{
System.out.println(k);
}
38 | P a g
Q) What are the Jumping Statements:

Sometimes, when executing a loop it


becomes want to skip a part of the loop or to leave the loop as soon as a certain condition
occurs. For example, consider the case of searching for a particular number in a list
containing, say, 100 numbers. A program loop written for reading and testing the numbers a
100 times must be terminated as soon as the desire number is found. Java permits a jump
from one statement to the end or beginning of a loop as well as a jump out of a loop.

When the break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop. When the loops
are nested, the break would only exit from the loop containing it. That is, the break will exit
only a single loop.

Skipping a part of a Loop


During the loop operations, it may be necessary to skip a part of the body of the loop
under certain conditions. Unlike the break which causes the loop termination, the continue,
as the name implies, cause the loop to be continued with the next iteration (repetition) after
skipping any statement in between.

The continue statement is written simply as

Labeled break and continue


In Java, we can give a label to a block of statements. A label is any valid Java variable
name. To give a label to a loop, place it before the loop with a colon at the end.
39 | P a g
The label: can be anywhere in the program either before or after the goto label;
statement. During running of a program when a statement like goto label; is met, the flow
of control will jump to the statement immediately following the label;. This happens
unconditionally.

E.g:

outer: for(int m=1; m<11; m++)


{
for(int n=1; n<11; n++)
{
System.out.print(“ ”+
m*n); if(n == m)
continue outer;
}
}
Here, the continue statement terminates the inner loop when n=m and continues
with the next iteration of the outer loop (counting m).

E.g:

loop1:for(int i=0; i<10; i++)


{
loop2: while(x<100)
{
Y = i*x; if(y>500)
break loop1;
………………
………………
}

Jumping out
………………
}
of both loops
………………

Here, the continue statement terminates the inner loop when n=m and continues
with the next iteration of the outer loop (counting m).
40 | P a g
Q) Explain about stream?

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a


stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Q. Explain about Arrays?

An array is a group of contiguous or related data items that share a common name. A
particular value is indicated by the number called index or subscript in brackets after the
array name.

One dimensional Arrays

A list of items given by one name using only one subscript and such variable is called
one-dimensional array.

In Java, single subscripted variable xi can be expressed as

X[0], X[1], X[2],…..The subscript begins with 0.

Ex: if we want to represent set of 5 numbers say (10, 20, 30, 40, 50) by an array variable
num, then we may create the variable num as follows.

int num[] = new int [5];

And the computer reserves 5 storage locations as shown


below.

points
nowhere
int num[];

num [0]
num = new int [5];
num [1]
num [2]

num[3]

num [4]

4 1| P
This would cause the array num to store the values as shown below. The elements m ay
a g
b e used in programs just like any other variable in Java.
num[0]=10, num[1]=20, num[2]=30, num[3]=40m and num[4]=50.

Like a variable, arrays must be declared and created in the memory before they are used.
The creation of array involves the following steps.

1. Declaration of Array
1. Creation of Array
2. Putting values into the memory locations.

Declaration of Array:

In Java Arrays are declared in two forms.

1. Type <array name>[];


1. Type []<array name>;

Ex: int a[]; or int

[]a; Creation of Array:

After declaring the array, we need to create it in the memory. Java allows you to
create array using new operator as shown below.

Syntax: array_name = new type [size];

Ex: a = new int [5];

Initialization of Array:

The final step is to put values into the array created. This process is known as
initialization.

Syntax:

Arrayname [subscript] = value;

ex: num[1]=20;

Type array_name []= {list of values};

Ex: int a[]={10, 20, 30, 40, 50};

Which stores the values as a[0]=10, a[1]=20, a[2]=30, a[3]=40, and a[4]=50.

In Java, the array index starts with 0 and ends with a value one less than the size
specified. In Java trying to access an array beyond its boundaries, it will generate an error
message.

Array Length:

In Java, all arrays store the allocated size in a variable named length. We can obtain
the length of the array a using a.length.

Ex: int asize=a.length;

This information is useful in the manipulation of arrays when their sizes are not known.

Pa
ssing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.

class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}

public static void main(String args[])


{
int a[]={9,8,3,1};//declaring and initializing an array
min(a);//passing array to method
}
}

Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.

public class TestAnonymousArray


{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){ for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{1,2,3,4});//passing anonymous array to method
}
}
43 | P a g
Two Dimensional Arrays

Java supports two dimensional arrays, the array consisting of two subscripts which
the first one represents the rows and the second subscript represents column to represent a
table of items. The two dimensional arrays are created in the following manner.

Type array_name [][];

array_name= new type [row_size]

[col_size]; Ex: int x[][] = new int [3][2];

Like one-dimensional arrays, two dimensional arrays may be initialized by following their
declaration with a list of initial values as follows.

Type array_name[][] = {list of values};

int x[][]= {{1,2},{3,4},{5,6});

The above declaration automatically initializes the elements into 3 rows and 2 columns in
each row starting index with 0 for row and column.

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In
other words, it is an array of arrays with different number of columns.

class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){ System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
44 | P a g
}
}
output
012
345
678
Variable sized Arrays

Java treats multidimensional array as “array of arrays”. It is possible to declare a two


dimensional array as follows.

int x[][] = new int [3][];


x[0]= new int[2];
x[1]= new int[4];
x[2]= new int[3];
These statements create a
two-dimensional array as having different lengths for each row as shown in below:

x[0] x[0][1]
x[1] x[1][3]
x[2] x[2][2]

Strings
String manipulating is the most common part of many Java programs. Strings
represent the sequence of characters. The easiest way to represent a sequence of characters
in Java is using a character array.

Ex:
char name[]= new char[3];
name[0] = ‘s’;
name[1] = ‘a’;
name[2] = ‘i’;

In Java, strings are class objects and implemented using two classes, String and
StringBuffer; both are available in java.lang package. A Java string is an instantiated object
of the String class. A Java string is not a character array and is not terminated by NULL
character. In Java strings are declared and created as follows.

String <string_name>;
String_name= new String (“string constant”);

Ex:
String name;
name = new String (“yugandhar”);
or
String name = new String (“yugandhar”);

Note: The contents of the string instance cannot be changed after it has been 4c5re|aPteadg.
However, a variable declared as a string reference can be changed to point to another string
object at any time.
We can copy the character array into the string object, in that way also we can create a
string object.

Ex:

char

name[]={‘s’,’a’,’I’,’r’,’a’,’m’);

String S = new String(name);

Now that String object ‘S’ contains he string ‘sairam’. You can copy the particular
character sequence from the array into the String object in the following method of
declaration.

String S = new String(name, 3,3);

Here, starting from 3rd character, a total of three characters are copied into the String S.

String Arrays:

We can also create and use arrays that contain strings. The statement

String nameArray[]= new String[5];

Will creae an nameArray of size 5 to hold 5 string constants. We can assign the strings to the
array by using the indexes.

String Methods:

The String class defines a number of methods that allow us to accomplish a variety of
string manipulation tasks. Some most commonly used are as follows.

Function Action

S1.toLowerCase() Converts the string s1 to lowercase

S1.toUpperCase() Converts the string s1 to uppercase

S1.length() Gives the length of string s1.

S1.charAt(n) Gives nth character of s1.


Gives the position of the first occurrence of ‘x’ in
S1.index(‘x’)
the string s1.
Gives the position of ‘x’ that occurs after nth
S1.index(‘x’, n)
position in the string s1.
S1.equals(s2) Returns ‘true’ if s1 is equals to s2.
Returns ‘true’ if s1=s2, ignoring the case of
S1.equalsIgnoreCase(s2)
characters.
Returns –ve if s1<s2, +ve if s1>s2 and 0 if
S1.compareTo(s2)
s1=s2.
Compares the strings by ignoring the case and
S1.compareToIgnoreCase(s2)
returns above values.
S1.concat(s2) Concatenates s1 and s2, returns new string.s

S1.subString(n) Gives substring from nth character.


46
Gives substring from nth character, upto mth
S1.subString(n,m)
character.
Function Action

S1.replace(‘x’,’y’) Replaces all appearances of x with y.


Remove white spaces at beginning and end of
S1.trim()
the s1.
p.toString() Creates a string representation of object p.
Converts the parameter value p
String.valueOf(p)
to string representation.

Q) Explain Immutability of strings?

A String is an unavoidable type of variable while writing any application


program. String references are used to store various attributes like
username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a
new String object is created.

Let's try to understand the concept of immutability by the example given below:

class Testimmutablestring{
public static void
main(String args[])
{ String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:

Sachin

Now it can be understood by the diagram given below. Here Sachin is


not changed but a new object is created with Sachin Tendulkar. That is
why String is known as immutable.

You might also like