Java
Java
The purpose of identifier is for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
Rules
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.
Separators
Separators are symbols used to indicate where groups of code are divided and
arranged.
Name Use
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
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
When one of the operand is real and other is integer then the operation is called
mixed mode arithmetic expression.
Relational operators
These are used to test for equality of expressions. These result either true or false
value.
Operator Meaning
== 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 OR
! Logical NOT
Assignment operators
Variable op=exp;
Simple assignment operator is = (equal to). The general syntax of simple assignment
operator is
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 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 OR
^ Bitwise exclusive OR
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.
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.
1 . () L to R
3 *, /,% L to R
4 +,- 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
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
Numeric
Non - numeric
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.
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.
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.
-9223372036854775808 to
Long 64 bit signed
9223372036854775807
-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.
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.
Real constants used to represent the numbers containing fractional parts. A real number
may also be expressed in exponential notation also.
Single Character constants contain a single character enclosed within a pair of single
quotation marks.
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
Symbolic Constants
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
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.
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.
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”;
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:
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
}
}
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();
The various functions available with the Math class are listed below.
Function Action
sin(x) Returns the sine of the single x in radians
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:
if (condition)
{
True statement block;
}
Statement –x;
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;
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.
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;
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:
Looping statement:
While statement:
Do statement or Do-loop:
do
{
block of statements;
} while (condition); statement-x;
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:
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.
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 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, 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:
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.
E.g:
E.g:
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?
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
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.
A list of items given by one name using only one subscript and such variable is called
one-dimensional array.
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.
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:
After declaring the array, we need to create it in the memory. Java allows you to
create array using new operator as shown below.
Initialization of Array:
The final step is to put values into the array created. This process is known as
initialization.
Syntax:
ex: num[1]=20;
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.
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);
}
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
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.
Like one-dimensional arrays, two dimensional arrays may be initialized by following their
declaration with a list of initial values as follows.
The above declaration automatically initializes the elements into 3 rows and 2 columns in
each row starting index with 0 for row and column.
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++;
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’);
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.
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
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
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