chap_2
chap_2
- The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about the
variable, method, class or any statement. It can also be used to hide program code for
specific time.
Syntax:
Example:
class CommentExample1 {
public static void main(String[] args) {
int id=10; // Here, id is a variable
System.out.println(id);
}
}
Output:
10
/*
This
is
multi line
comment
*/
Example:
class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int id=10;
System.out.println(id); // 10
}
}
Syntax:
/**
* This
* is
* documentation
* comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b) {
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b) {
return a-b;
}
}
1) Keywords
- Java keywords are also known as reserved words. Keywords are particular words which acts
as a key to a code. These are predefined words by Java so it cannot be used as a variable or
object name.
- Keywords are words that have already been defined for Java compiler. They have special
meaning for the compiler. Java Keywords must be in your information because you cannot use
them as a variable, class or a method name.
- You can't use keyword as identifier in your Java programs, its reserved words in Java library
and used to perform an internal operation. A list of Java keywords or reserved words are given
below:
true, false and null are not reserved words but cannot be used as identifiers, because it is
literals of built-in types.
B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]
2) identifiers
class Test
int a = 20;
}
In the above java code, we have 5 identifiers name :
Test : class name.
main : method name.
String : predefined class name.
args : variable name.
a : variable name.
There are certain rules for declaring an identifier. We need to follow these rules otherwise we
will get a compile-time error.
1. A valid identifier has characters [A-Z],[a-z] or numbers [0-9], $ (dollar sign)
and _ (underscore). For example, @dataflair is not a valid identifier, because it contains @
which is a special character.
2. We can’t declare a variable with space. For example, data flair is invalid.
3. We can’t start an identifier with a number. For example, 222dataflair is not a valid
identifier.
4. As there is no limit on the length of an identifier but it is 4 – 15 letters only appropriate to
use.
5. It is not recommended to use Reserved words as an identifier. For example, int float=5; is
not a valid statement.
6. The variable name should be meaningful which easily depicts the logic.
- Literals are constant in java program and their value does not change throughout the
program.
int id=10;
String name="Ravi";
float salary=10000.50;
Types of Literals :
1. Integer Literals
2. Real Literals
3. Character Literals
4. String Literals
5. Boolean Literals
6. Null Literals
a) Arithmetic Operators
b) Assignment Operators
c) Relational Operators
d) Logical Operators
e) Unary Operators
a) Arithmetic Operators
- Arithmetic operators are used to perform arithmetic operations on variables and data.
For example,
c=a+b;
- Here, the + operator is used to addition of two variables a and b. Similarly, there are
various other arithmetic operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
class ArithmeticOperators {
int a = 12, b = 5;
b) Assignment Operators
- Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
class AssignmentOperatorExample {
int id=10;
id+=5;
Example:
class AssignmentOperators {
int a = 4;
int var;
var = a;
var += a;
var *= a;
- Relational operators are used to check the relationship between two operands. For example,
a < b;
Here, < operator is the relational operator. It checks if a is less than b or not.
Example:
class RelationalOperators {
int a = 7, b = 11;
- Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Example:
class LogicalOperators {
// && operator
// || operator
// ! operator
- Java also provides increment and decrement operators: ++ and -- respectively. ++ increases
the value of the operand by 1, while -- decrease it by 1. For example,
int num = 5;
// increase num by 1
num++;
Here, the value of num gets increased to 6 from its initial value of 5.
Example
class UnaryOperator {
int num = 5;
num++;
class Main {
// declare variables
// original value
// increment operator
result1 = ++a;
// decrement operator
result2 = --b;
In the above program, we have used the ++ and -- operator as prefixes (++a, --b). We can also
use these operators as postfix (a++, b++).
- They are the special characters in java, which are used to separate variables or the
characters.
Example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. char values are surrounded by single
quotes
boolean - stores values with two states: true or false
Variable Declaration:
- To declare a variable, you must specify the data type & give the variable a unique name.
int a, b, c ;
float pi ;
double d ;
char a;
Example:
float pi=3.14f;
double do=20.22d;
char a= 'V';
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. Memory
allocation for static variable happens only once when the class is loaded in the memory.
class Demo {
void method() {
class Test {
- Constants in java are fixed values those are not changed during the execution of
program. A literal is a constant value that can be classified as integer literals, string
literals and boolean literals. To make a static field constant in Java, make a variable as
both static and final. java supports several types of Constants those are
Integer Constants 3
- A constant in Java is used to map an exact and unchanging value to a variable name.
- If you make any variable as final, you cannot change the value of final variable(It will be
constant).
- What the final keyword means is that once the value has been assigned, it cannot be re-
assigned.
- Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before
its use. That is why we need to declare variable's type and name.
It occupies 1 bit of memory. The Boolean data type is used to store only two possible values:
true and false. The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
It occupies 1 byte of memory .Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
It occupies 2 bytes of memory. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
It Occupies 4 bytes of memory. its value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its default value is
0.0F.
It occupies 8 bytes of memory. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.
It occupies 2 bytes of memory. The char data type is used to store characters.
- An array is an 'n' number of fixed collection of homogeneous data elements storing into
the single variable is called an array.
- In array we can store multiple values into the single variable, data type must be same.
- The main advantage of array is we can represent huge number of variables by using
single variable so that readability of code will be improved but the main disadvantage of
array is fixed in size that is once we create an array there is no chance of increasing or
decreasing the size based on our requirement hence to use array concept compulsory
we should know the size in advance which may not possible always.
- Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically
int[] x; (or)
int []x; (or)
int x[];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
class TestArray {
public static void main(String args[]) {
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for (int i=0; i<a.length; i++) //length is the property of array
System.out.println (a[i]);
}
}
We can declare, instantiate and initialize the java array together by:
class Testarray1 {
public static void main(String[] args) {
int array[]={10,20,30,40}; // declaration, instantiation and initialization
for(int i=0;i<array.length;i++) // length is the property of array
System.out.println(array[i]);
}
}
Output:
10
20
30
40
int[][] x; (or)
int [][]x; (or)
int x[][];
- Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
class MultiDiArray {
public static void main(String args[]) {
//declaring and initializing 2D array
int arr[][]={{10,20},{30,40}};
//printing 2D array
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
System.out.print (arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
10 20
30 40
class MultiDiArray2 {
System.out.println();
- Type casting is when you assign a value of one primitive data type to another type.
- In Java, there are two types of casting:
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Widening Casting
- Widening casting is done automatically when passing a smaller size type to a larger size
type.
Example
int i = 100;
int myInt = 9;
System.out.println(myInt); // Outputs 9
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the
value:
Example :
System.out.println(myInt); // Outputs 9
- The Scanner class is used to get user input, and it is found in the java.util package.
- To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:
Example 1:
class ScannerExample {
System.out.println("Enter username");
Example 2:
class ScannerExample {
System.out.print("Enter Number");
int no=myObj.nextInt();
} }
- In the example above, we used the nextLine() method, which is used to read Strings. To
read other types, look at the table below:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
In the example below, we use different methods to read data of various types:
Example:
import java.util.Scanner;
class ScannerExample {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// Numerical input
int age = myObj.nextInt();
System.out.println("Enter Age : ");
}
}
- Java decision-making statements allow you to make a decision, based upon the result of
a condition. All the programs in Java have set of statements, which are executed
sequentially in the order in which they appear.
- Following are Decision Making Statements in Java -
if statement
if-else statement
if-else-if ladder statement
nested if statement
switch statement
- if statements in Java is used to control the program flow based on some condition.
- The Java if statement test the condition. It executes the if block if condition is true.
otherwise, it will get skipped.
Syntax:
if (condition) {
//code to be executed
}
Figure - Flowchart of if Statement:
Example 1:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>=18) {
System.out.print("Age is greater than 18");
}
System.out.println("This statement is out of if block");
}
}
Output:
if (b>a)
System.out.println("b is greater");
}
}
Example 3:
Example 4:
import java.util.Scanner;
public class IfExample
{
public static void main(String []args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age: ");
int age=sc.nextInt();
//Determine whether the person is eligible to vote or not
if (age>=18)
{
System.out.println("The person is eligible for vote");
}
System.out.println("This statement is outof if block");
}
}
- The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
Syntax:
if (condition) {
//code if condition is true
}
else {
//code if condition is false
}
int number=15;
if(number%2==0) {
System.out.println("even number");
else {
System.out.println("odd number");
Output:
odd number
import java.util.Scanner;
int age=sc.nextInt();
if (age>=18)
else {
- In this statement based upon the condition corresponding statement block will be
execute .
Syntax:
if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
Example 2:
Output:
NEGATIVE
- The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
Syntax:
if (condition) {
//code to be executed
if (condition) {
//code to be executed
}
}
Output:
Example 2:
Output:
- We can also use ternary operator (? :) to perform the task of if...else statement. It is a
shorthand way to check the condition. If the condition is true, the result of ? is returned.
But, if the condition is false, the result of : is returned.
Example:
class Operator {
String result;
System.out.println(result);
- The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement. The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and Long.
- In other words, the switch statement tests the equality of a variable against multiple
values.
Syntax:
switch(expression) {
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Output:
20
Example:
// Get day.
day = sc.nextInt();
switch (day)
case 1 :
System.out.println("Sunday");
break;
case 2 :
System.out.println("Monday");
break;
System.out.println("Tuesday");
break;
case 4 :
System.out.println("Wednesday");
break;
case 5 :
System.out.println("Thursday");
break;
case 6 :
System.out.println("Friday");
break;
case 7 :
System.out.println("Saturday");
break;
default :
System.out.println("Invalid input");
o for loop
o while loop
o do-while loop
for loop
- A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value. It consists of four parts:
1. initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable.
2. Condition: It is the condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value
either true or false.
3. Statement: The statement of the loop is executed each time until the condition is false.
4. Increment/Decrement: It increments or decrements the variable value.
Syntax:
Example:
1
2
3
4
5
6
7
8
9
10
while loop :
- The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false, the
loop automatically stops.
- The Java while loop is used to iterate a part of the program several times. If the number
of iteration is not fixed, it is recommended to use while loop.
Syntax:
while (condition) {
//code to be executed
Increment / decrement statement
}
Output:
1
2
3
4
5
6
7
8
9
10
Example:
- The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a do-while loop.
- Java do-while loop is called an exit control loop. Therefore, unlike while loop and for
loop, the do-while check the condition at the end of loop body. The Java do-while loop is
executed at least once because condition is checked after loop body.
Syntax:
do {
//code to be executed
} while (condition);
Output:
1
2
3
4
5
6
7
8
9
10
Example :
- The jumping statements are the control statements which transfer the program
execution control to a specific statements.
- Java has three types of jumping statements they are break, continue, and return. These
statements transfer execution control to another part of the program.
if (i == 4) {
break;
System.out.println(i);
- The continue statement is used when you need to jump to the next iteration of the loop
immediately. (in the loop), if a specified condition occurs, and continues with the next
iteration in the loop.
if (i == 4) {
continue;
System.out.println(i);
- The return statement is used to explicitly return from a method. That is, it causes a
program control to transfer back to the caller of the method.
Example:
if (i == 5) {
return;
System.out.println(i);