Java Notes
Java Notes
===========================================
In java, uppercase letters will consider as different and lowercase letters consider as different.Hence we
consider java is a case sensitive programming language.
As java is a case sensitive, we must and should follow naming conventions for following things.
ex:
classes
interfaces
variables
methods
keywords
packages
constants
classes
--------
In java, a class name must and should starts with uppercase letter and if it contains multiple words then each
inner word must starts with initcap.
ex:
Predefined classes Userdefined classes
----------------- -------------------
System Test
Date ExampleApp
StringBuffer EmployeeInfo
FileWriter Department
and etvkjkmc. and etc.
interfaces
----------
In java, an interface name must and should starts with uppercase letter and if it contains multiple words then
each inner word starts with initcap.
ex:
keywords
----------
In java, all keywords we need to declare under lowercase letters.
ex: predefined keywords
------------------
if, else, while, do , public , static , void , for and etc.
packages
---------
In java, all packages we need to declare under lowercase letters only.
ex:
predefined packages userdefined packages
---------------- --------------------
java.lang com.ihub.www
java.io com.google.www
java.util and etc.
java.util.stream
java.text
java.time
and etc.
constants
----------
In java, all constants we need to declare under uppercase letters only.
ex: predefined constants userdefined constants
--------------- -------------------
MAX_PRIORITY LIMIT
MIN_PRIORITY N=10
NORM_PRIORITY
MAX_VALUE
MIN_VALUE
and etc.
Assignment
===========
1) class : QualityThought
2) interface : IQualityThought
3) variable : qualityThought
4) method : qualityThought()
5) package : com.qualitythought.www
6) constant : QUALITY_THOUGHT
Interview Questions
===================
Q) What is package?
A package is a collection of classes and interfaces.
Q) Which package consider as a default package in java?
java.lang package
Diagram: java1.1
History of Java
======================
In 1990, Sun Micro System company took one project to develop a software called consumer electronic device
which can be controlled by a remote like setup box. That time project was called Stealth project and later it is
renamed to Green project.
James Gosling, Mike sheradin and Patrick Naughton were there to develop the project and they have met in a
place called Aspan/Colarado to start the work with Graphic System.James Gosling decided to use C and C++
languages to develop the project.But the problem what they have faced is C and C++ languages are system
dependent.Then James Gosling decided why don't we create our own programming language which is system
independent.
In 1991, they have developed a programming language called and OAK.OAK means strength , itself is a
coffee seed name and it is a national tree for many countries like Germany,France, USA and etc.
Later in 1995, they have renamed OAK to Java.Java is a Island of an Indonasia where first coffee of seed was
produced and during the development of project they were consuming lot of coffee's.Hence the symbol of java
is a cup of coffee with saucer.
Identifiers
===========
A name in java is called identifier.
It can be class name, variable name, method name or label name.
ex:
class Test
{
public static void main(String[] args)
{
int x = 10;
System.out.println(x);
}
}
Here Test, main , args, x , String , System are identifiers.
Rules to declare an identifiers
-------------------------------
Rule1:
-----
Identifier will accept following characters.
ex:
A-Z
a-z
0-9
_
$
Rule2:
-----
If we take other characters then we will get compile time error.
ex:
int emp_id; //valid
int emp#id; //invalid
int emp$alary; //valid
Rule3:
-----
Identifier must and should starts with alphabet,underscore or dollar symbol
but not with digit.
ex:
int emp123; //valid
int _emp; //valid
int $emp; //valid
int 1abcd; //invalid
Rule4:
-----
Every identifier is a case sensitive.
ex:
int number;
int NUMBER;
int NuMbEr;
Rule5:
-----
We can't take reserved words as an identifiers.
ex:
int if;
int else;
int do;
int for;
Rule6:
------
There is no length limit for an identifier but is not recommanded to take more then
15 characters.
Interview Questions
===================
Q) Who is the creator of Java ?
James Gosling
Q) In which year java was developed ?
In 1995
Q) Java originally known as ___ ?
OAK
Q) Is java platform independent or not ?
Java is a platform independent
Diagram: java2.1
}
step5:
------ Save java program with same name as class name inside "javaprog" folder.
step6:
----- Open the command prompt from "javaprog" location.
step7:
------ Compile the java program by using below command.
ex:
javaprog> javac Test.java
|
filename
step8:
------
Run the java program by using below command.
ex: javaprog> java Test
z |
classname
Reserved words
===============
There are some identifiers which are reserved to associate some functionality or meaning such type of
identifiers are called reserved words.
Java supports 53 reserved words.
In java , reserved words are divided into two types.
Diagram: java3.1
Datatypes
================
Datatype describes what type of value we want to store inside a variable.
Datatype also tells how much memory has to be created for a variable.
In java , datatypes are divided into two types.
Diagram: java5.1
Byte
-----
It is smallest datatype in java.
Size : 1 byte (8 bits)
Range : -128 to 127 (-2^7 to 2^7-1)
ex:
1) byte b=10;
System.out.println(b); // 10
2) byte b=130;
System.out.println(b); // C.T.E
3) byte b=10.5;
System.out.println(b); // C.T.E
short
------
It is rarely used datatype in java.
Size : 2 bytes (16 bits)
Range : -32768 to 32767 (-2^15 to 2^15-1)
ex:
1) byte b=10;
short s=b;
System.out.println(s); //10
2) short s=10.5;
System.out.println(s); // C.T.E
3) short s=true;
System.out.println(s); // C.T.E
int
----
It is widely used datatype in java.
Size : 4 bytes (32 bits)
Range : -2147483648 to 2147483647 (-2^31 to 2^31-1)
ex:
1) int i="hi";
System.out.println(i); // C.T.E
2) int i=false;
System.out.println(i); // C.T.E
3) int i='a';
System.out.println(i); // 97
Note:
-----
In java for every character we have universal unicode value.
ex:
A ---- 65
a ---- 97
long
-----
If int datatype is not enough to large value then we need to use long datatype.
Size : 8 bytes (64 bits)
Range : (-2^63 to 2^63-1)
ex:
1) long l="true";
System.out.println(l); // C.T.E
2) long l='A';
System.out.println(l); // 65
3) long l=false;
System.out.println(l); // C.T.E
4) long l=10.5;
System.out.println(l); // C.T.E
float double
----------- ------------
If we need 4 to 6 decimal point of accuracy If we need 14 to 16 decimal point of accuracy
then we need to use float. then we need to use double.
Size : 4 bytes (32 bits) Size : 8 bytes (64 bits)
Range : -3.4e38 to 3.4e38 Range : -1.7e308 to 1.7e308
To declare a float value we need to To declare a double value we need to suffix
suffix with 'f' or 'F'. with 'd' or 'D'.
ex: ex:
10.5f 10.5d
ex:
1) float f=10.5f;
System.out.println(f); // 10.5
2) float f=10;
System.out.println(f); // 10.0
3) float f='a';
System.out.println(f); // 97.0
4) float f="hi";
System.out.println(f); // C.T.E
5) float f=true;
System.out.println(f); // C.T.E
ex:
1) double d=10.5d;
System.out.println(d); // 10.5
2) double d=10;
System.out.println(d); // 10.0
3) double d='a';
System.out.println(d); // 97.0
4) double d="hi"
System.out.println(d); // C.T.E
5) double d=true;
System.out.println(d); // C.T.E
boolean
--------
It is used to represent boolean values either true or false.
Size : (Not Applicable) (1-bit)
Range : (Not Applicable)
ex:
1) boolean b="true";
System.out.println(b); // C.T.E
2) boolean b=TRUE;
System.out.println(b); // C.T.E
3) boolean b=true;
System.out.println(b); // true
char
-----
It is a single character which is enclosed in a single quotation.
Size : 2 bytes (16 bits)
Range : 0 to 65535
ex:
1) char ch='a';
System.out.println(ch); // a
2) char ch=65;
System.out.println(ch); // A
3) char ch="d";
System.out.println(ch); // C.T.E
Diagram: java5.2
h
Q) Write a java program to display range of int datatype?
int range : -2147483648 to 2147483647
ex:
class Test
{
public static void main(String[] args)
{
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
}
}
Types of variables
==============================
A name which is given to a memory location is called variable.
Purpose of variable is used to store the data.
In java, we have two types of variables.
1) Primitive variables
--------------------
Primitive variables are used to represent primitive values.
2) Reference variables
-----------------------
Reference variables are used to represent object reference.
ex:
Student s=new Student();
|
reference variable
Based on the position and execution these variables are divided into three types.
1) Instance variables / Non-static variables
2) Static variables / Global variables
3) Local variables / Temperory variables / Automatic variables
1) Instance variables
-----------------------
A value of a variable which is varied(changes) from object to object is called instance variable.
Instance variable will be created at the time of object creation and it will destroy at the time of object
destruction.Hence scope of instance variable is same as scope of an object.
Instance variable will store in heap area as a part of an object.
Instance variable must and should declare immediately after the class but not inside methods,blocks and
constructors.
Instance variables we can access directly from instance but we can't access from static area.
To access instance variable from static area we need to create object reference.
ex:1
-----
class Test
{
//instance variableh
int i=10;
public static void main(String[] args)
{
System.out.println(i);
}
}
o/p:
C.T.E : non-static variable i cannot be referenced from a static context
ex:2
-----
class Test
{
//instance variable
int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i);//10
}
}
Note:
-----
If we won't initialize any value to instance variable then JVM will initialize default values.
ex:3
----
class Test
{
//instance variable
boolean b;
}
}
ex:5
-----
class Test
{
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
//non-static method
public void m1()
{
System.out.println("instance-method");
}
}
2) Static variables
--------------------
A value of a variable which is not varied from object to object is called static variable.
Static variable will be created at the time of classloading and it will destroy at the time of classunloading.Hence
scope of static variable is same as scope of a .class file.
Static variable will store in Method area.
Static variable must and should declare immediately after the class using static keyword but not inside
methods, blocks and constructors.
Static variable we can access directly from instance area and static area.
Static variable we can access by using object reference and class name.
ex:1
-----
class Test
{
//static variable
static int i=10;
public static void main(String[] args)
{
System.out.println(i);//10
Test t=new Test();
System.out.println(t.i);//10
System.out.println(Test.i);//10
}
}
Note:
-----
If we won't initialize any value to static variable then JVM will initialize default values.
ex:2
----
class Test
{
//static variable
static String s;
public static void main(String[] args)
{
System.out.println(s);//null
Test t=new Test();
System.out.println(t.s);//null
System.out.println(Test.s);//null
}
}
ex:3
----
class Test
{
//static variable
static int i=10;
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
System.out.println(t1.i);//10
System.out.println(t2.i);//10
t1.i=20;
System.out.println(t1.i);//20
System.out.println(t2.i);//20
}
}
ex:4
-----
class Test
{
public static void main(String[] args)
{
m1();
Test t=new Test();
t.m1();
Test.m1();
}
//static method
public static void m1()
{
System.out.println("static-method");
}
}
3) Local variables
==================
To meet temperory requirements a programmer will declare some variables inside methods, blocks and
constructors. Such type of variables are called local variables.
Local variable will be created at the time of execution block and it will destroy when execution block is
executed.Hence scope of local variable is same as scope of an execution block where it is declare.
Local variable will store in java stack.
ex:1
---
class Test
{
public static void main(String[] args)
{
//local variable
int i=10;
System.out.println(i); //10
}
}
Note:
----
If we won't initialize any value to local variable then JVM will not initialize default values.
ex:2
---
class Test
{
public static void main(String[] args)
{
//local variable
int i;
System.out.println(i);
}
}
o/p:
C.T.E :variable i might not have been initialized
A local variable will accept only one modifier i.e final.
ex:3
----
class Test
{
public static void main(String[] args)
{
//local variable
final int i=10;
System.out.println(i);//10 m
}
}
Interview Questions
===================
Q) Is java purely object oriented or not?
No, java will not consider as purely object oriented programming language because java does not supports
many OOPS concepts like multiple inheritance, operator overloading and more ever we depends upon
primitive datatypes which are non-objects.
Q) What is literal?
A value which is assign to a variable is called literal.
A value which is not change during the program execution is called literal.
ex:
int i = 10;
| | |___ value of a variable / Literal
| |________ variable / identifier
|____________ Datatype / Keyword
Import Statements
==================
Whenever we use import statements we should not use fully qualified name.
Using short name also we can achieve.
We have three types of import statements in java.
1) Explicit class import
2) Implicit class import
3) Static import
3) Static import
----------------
Using static import we can access static members directly.
Often use of static import makes our program complex and unreadable.
ex:1
-----
import static java.lang.System.*;
class Test
{
public static void main(String[] args)
{
out.println("stmt1");
out.println("stmt2");
out.println("stmt3");
}
}
ex:
---
import static java.lang.System.*;
class Test
{
public static void main(String[] args)
{
out.println("stmt1");
exit(0);
out.println("stmt2");
}
}
Editplus Editorn
===============
Download link: https://www.editplus.com/download.html
output:
25
ex:
import java.util.Scanner;
class Example3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
//logic
int square=n*n;
System.out.println("Square of a given number is ="+square);
}
}
Q) Write a java program to find out cube of a given number?
input:
5
output:
125
import java.util.Scanner;
class Example4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
//logic
int cube=n*n*n;
System.out.println("Cube of a given number is ="+cube);
}
}
Q) Write a java program to find out area of a circle?
import java.util.Scanner;
class Example5
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();
//logic
float area=3.14f*r*r;
System.out.println("Area of a circle is ="+area);
}
}
Q) Write a java program to find out perimeter of a circle?
import java.util.Scanner;
class Example6
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();
//logic
float perimeter=2*3.14f*r;
System.out.println("Perimeter of a circle is ="+perimeter);
}
}
Q) Write a java program to display swapping of two numbers?
import java.util.Scanner;
class Example7
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();//10
System.out.println("Enter the second number :");
int b=sc.nextInt();//20
System.out.println("Before swapping a="+a+" and b="+b);
//logic
int temp=a;
a=b;
b=temp;
System.out.println("After swapping a="+a+" and b="+b);
}
}
Q) Write a java program to perform swapping of two numbers without using third variable?
import java.util.Scanner;
class Example7
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();//10
System.out.println("Enter the second number :");
int b=sc.nextInt();//20
System.out.println("Before swapping a="+a+" and b="+b);
//logic
a=a+b;
b=a-b;
a=a-b;
Typecasting in java
===================
The process of converting from one datatype to another datatype is called typecasting.
In java, typecasting can be done in two ways.
1) Implicit typecasting
2) Explicit typecasting
1) Implicit typecasting
-----------------------
If we want to store small value into a bigger variable then we need to use implicit typecasting.
A compiler is responsible to perform implicit typecasting.
There is no possibility to loss the information.
It is also known as Widening or Upcasting.
We can perform implicit typecasting as follow.
ex:
byte ---> short
--->
int ---> long ---> float ---> double
--->
char
ex:
---
class Test
{
public static void main(String[] args)
{
byte b=10;
int i=b;
System.out.println(i); // 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
char ch='a';
long l=ch;
System.out.println(l); // 97
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
double d=i;
System.out.println(d); // 10.0
}
}l
2) Explicit typecasting
-----------------------
If we want to store bigger value into a smaller variable then we need to use explicit typecasting.
A programmer is responsible to perform explicit typecasting.
There is a possibility to loss the information.
It is also known as Narrowing or Downcasting.
We can perform explicit typecasting as follow.
ex:
byte <--- short
<---
int <--- long <--- float <--- double
<---
char
ex:
---
class Test
{
public static void main(String[] args)
{
double d=10.56d;
int i=(int)d;
System.out.println(i); //10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=65;
char ch=(char)i;
iSystem.out.println(ch); //A
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=130;
byte b=(byte)i;
System.out.println(b); // -126
}
}
1) Instance block
-------------------------------------
Instance block is used to initialize the values to instance variables.
Instance block must and should declare immediately after the class but not inside methods and constructors.f
Instance block will execute at the time of object creation.
We can declare instance block as follow.
syntax:
------
//instance block
{
-
- //set of statements
-
}
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}
instance-block
main-method
instance-block
ex:
---
class Test
{
//instance variable
int i;
//instance block
{
i=100;
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i); //100
}
}
2) Static block
----------------
Static block is used to initialize the static variables.
Static block must and should declare immediately after the class using static keyword but not inside methods
and constructors.
Static block will execute the time of classloading.
We can declare static block as follow.
syntax:
-------
//static block
static
{
-
- //set of statements
-
}
ex:
----
class Test
{
//static block
static
{
System.out.println("static-block");
}
public static void main(String[] args)
{
System.out.println("main-method");
}
}
o/p:
static-block
main-method
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}
//static block
static
{
System.out.println("static-block");
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println("main-method");
}
}
o/p:
static-block
instance-block
main-method
ex:
----
class Test
{
//static variable
static int i;
//static block
static
{
i=200;
}
3) Local block
--------------
Local block is used to initialize the local variables.
Local block will execute just like normal statement.
Local block must and should declare inside methods and constructors.
We can declare local block as follow.
syntaX:
------
//local block
{
-
- //set of statements
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
//local block
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
o/p:
stmt1
stmt2
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
//local variable
int i;
//local block
{
i=300;
}
System.out.println(i); //300
}
}
Interview Question
==================
Q) Can we execute java program without main method?
Yes , till 1.6 version it is possible to execute java program without main method using static block. But from 1.7
version onwards it is not possible to execute java program without main method.
ex:
---
class Test
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
Operators
==========
Operator is a symbol which is used to perform some operations on operands.
ex:
c=a+b;
Here = and + are operators
Here a,b and c are operands
It can be arithmetic operation, logical operation, bitwise operation and etc.
We have following list of operators in java.
1) Assignment operators
2) Ternary/Conditional operators
3) Logical operators
4) Bitwise operators
5) Arithmetic operators
6) Relational operators
7) Shift operators
8) Unary operators
1) Assignment operators
-----------------------
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i=20;
i=30;
System.out.println(i); // 30
}
}
Note:
-----
Variable reinitialization is possible in java.
ex:
---
class Test
{
public static void main(String[] args)
{
final int i=10;
i=20;
i=30;
System.out.println(i); // C.T.E
}
}
o/p:
C.T.E : cannot assign a value to final variable
ex
---
class Test
{
public static void main(String[] args)
{
int i=1,2,3,4,5;
System.out.println(i); //C.T.E
}
}
o/p:
C.T.E : Identifier expected
ex:
---
class Test
{
public static void main(String[] args)
{
int i,j;
i=j=1,2;
System.out.println(i+" "+j); // C.T.E
}
}
o/p:
C.T.E : semicolon expected
ex:
---
class Test
{
//global variable
static int i=10;
public static void main(String[] args)
{
//local variable
int i=20;
System.out.println(i); // 20
}
}
Note:
----
Here priority goes to local variable.
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i+=4; // i = i + 4
System.out.println(i); //14
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i-=45; // i = i - 45
System.out.println(i); // -35
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i*=6;
System.out.println(i); // 60
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i/=4;
System.out.println(i); // 2
int j=10;
j/=20;
System.out.println(j); // 0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i%=4;
System.out.println(i); // 2
int j=10;
j%=20;
System.out.println(j); // 10
}
}
2) Ternary/Conditional operators
-------------------------------
syntax:
------
(condition)?value1:value2;
ex:
---
class Test
{
public static void main(String[] args)
{
int i=(true)?1:0;
System.out.println(i);//1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String s=(false)?"It is true":"It is false";
System.out.println(s);//It is false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>2)?true:false;
System.out.println(b);//
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
char ch=(5>20)?'t':'f';
System.out.println(ch);// f
}
}
Q) Write a java program to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int max=(a>b)?((a>c)?a:c):((b>c)?b:c);
3) Logical operators
---------------------
Logical AND operator (&&)
-------------------------
Logical AND operator deals with boolean values either true or false.
Truth table
-----------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true && true); //true
System.out.println(true && false);//false
System.out.println(false && true);//false
System.out.println(false && false); //false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5>2) && (6<10);
System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5>20) && (6<1);
System.out.println(b); // false
}
}
Logical OR operator (||)
------------------------
Logical OR operator deals with boolean values either true or false.
truth table
-----------
T T =T
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true || true); //true
System.out.println(true || false); //true
System.out.println(false || true); //true
System.out.println(false || false); //false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>2) || (6<1);
System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>10) || (7<3);
System.out.println(b); // false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = (5>2) && (6<3) || (67>5);
System.out.println(b);// true
}
}
Logical NOT operator (!)
------------------------
Logical NOT operator deals with boolean values either true or false.
ex:
---
class Test d
{
public static void main(String[] args)
{
boolean b = !(5>2);
System.out.println(b);//false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = !(5>20);
System.out.println(b);//true
}
}
How to convert decimal to binary number
========================================
10 - decimal number
1010 - binary number
2|10
--- 0
2|5
--- 1
2|2
--- 0 ^
1 |
-----------------
1010
How to convert binary to decimal number
========================================
1010
<----
0 + 2 + 0 + 8 = 10
4) Bitwise operators
=====================
Bitwise AND operator (&)
-------------------------
Bitwise AND operator deals with binary numbers.
Truth table
-----------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=15;
int c = a & b;
System.out.println(c); //10
}
}
/*
10 - 1010
15 - 1111
----------
& - 1010
<---
0*1 + 1*2 + 0*4 + 1*8
0 + 2 + 0 + 8 =10
*/
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=5;
int c = a & b;
System.out.println(c); //0
}
}
/*
10 - 1010
5 - 0101
----------
& - 000
*/
Bitwise OR operator (|)
------------------------
Bitwise OR operator deals with binary numbers.
Truth table
------------
T T =T
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=5;
int c = a | b;
System.out.println(c); // 15
}
}
/*
10 - 1010
5 - 0101
----------
| - 1111
<---
1*1 + 1*2 + 1*4 + 1*8
1 + 2 + 4 + 8 = 15
*/
Bitwise XOR operator (^)
-----------------------
Bitwise XOR operator deals with binary numbers.
Truth table
-----------
T T =F
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=15;
int c = a ^ b;
System.out.println(c); // 5
}
}
/*
10 - 1010
15 - 1111
----------
^ - 0101
<---
1*1 + 0*2 + 1*4 + 0*8
1+0+4+0=5
*/
Bitwise NOT operator (~)
------------------------
ex:
---
class Test
{
public static void main(String[] args)
{
int i= ~10;
System.out.println(i); // -11
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i= ~24;
System.out.println(i); // -25
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i= ~(-10);
. System.out.println(i); // 9
}
}
5) Arithmetic operators
=======================
% - modules
/ - division
* - multiplication
+ - addition
- - subtraction
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 5+6%3+7*2+10%30+7/2+8+10/40+6-20;
System.out.println(i); // 26
}
}
/*
5 + 6%3 + 7*2 + 10%30 + 7/2 + 8 + 10/40 + 6 - 20
5 + 0 + 14 + 10 + 3 + 8 + 0 + 6 - 20
46 - 20
26
*/
6) Relational operators
-----------------------
class Test
{
public static void main(String[] args)
{
System.out.println(10 > 20); // false
System.out.println(10 >= 20); // false
System.out.println(10 < 20); // true
System.out.println(10 <= 10); // true
System.out.println(10 == 10); // true
System.out.println(10 == 20); // false
System.out.println( 10 != 10); // false
System.out.println(10 != 20); //true
}
}
7) Shift operators
====================
Right shift operator (>>)
-------------------------
10 >> 1 = 10/2
10 >> 2 = 10/4
10 >> 3 = 10/8
10 >> 4 = 10/16
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 >> 3;
System.out.println(i); // 1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 >> 5;
System.out.println(i); // 100/32 = 3
}
}
Left shift operator (<<)
-------------------------
10 << 1 = 10*2
10 << 2 = 10*4
10 << 3 = 10*8
10 << 4 = 10*16
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 << 4;
System.out.println(i); // 10 * 16 = 160
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 << 2;
System.out.println(i); // 100 << 4 = 400
}
}
8) Unary operators
==================
Increment/Decrement operators(++/--)
------------------------------------
We have two types of increment operators.
1) post increment
ex:
i++;
2) pre increment
ex:
++i;
We have two types of decrement operators.
1) post decrement
ex:
i--;
2) pre decrement
ex:
--i;
POST Increment/Decrement operators
----------------------------------
Rule1 : First Take
Rule2 : Then Change
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
i++;
System.out.println(i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
System.out.println(i++); // 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j = i++;
System.out.println(i+" "+j); // 11 10
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
System.out.println(i+" "+j); // 12 21
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i = 10;
int j = i-- + i--; // 10 + 9
System.out.println(i+" "+j); // 8 19
}
}
PRE Increment/Decrement operators
----------------------------------
Rule1 : First Change
Rule2 : Then Take
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;h
++i;
System.out.println(i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
System.out.println(++i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= ++i;
System.out.println(i+" "+j); // 11 11
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= ++i + ++i; // 11 + 12
System.out.println(i+" "+j); // 12 23
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= --i + --i + --i; // 9 + 8 + 7
System.out.println(i+" "+j); // 7 24
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
byte b=127;
b++;
System.out.println(b);// - 128
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int g=5;
g++;
System.out.println(10 * g++);// 10 * 6
}
}
ex:
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(++(i++));// C.T.E
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(i++ + ++i);// 10 + 12 = 22
}
}
Control Statements
==================
Control statement enables the programmer to control flow of the program.
Control statement allows us to make decisions, to jump from one section of code to another section and to
execute the code repeatedly.
In java, we have four types of control statements.
1) Decision Making Statement
2) Selection Statement
3) Iteration Statement
4) Jump Statement
1) Decision Making Statement
-----------------------------
It is used to declare the conditions in our program.
Decision making statement is possible by using following ways.
i) if stmt
ii) if else stmt
iii) if else if ladder
iv) nested if stmt
i) if stmt
------------
It will execute the source code only if our condition is true.
syntax:
-----
if(condition)
{e
-
- //code to be execute
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(5>2)
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
o/p:
stmt1
stmt2
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(!(5>2))
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
o/p:
stmt1
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
if((5>2) && (6<1))
System.out.println("stmt1");
System.out.println("stmt2");
System.out.println("stmt3");
}
}
o/p:
stmt2
stmt3
Q) Write a java program to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
if(a>b)d
System.out.println(a+" is greatest");
if(b>a)
System.out.println(b+" is greatest");
}
}
Q) Write a java program to find out greatest of three numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
System.out.println("Enter the third number :");
int c=sc.nextInt();
if((a>b) && (a>c))
System.out.println(a+" is greatest");
if((b>a) && (b>c))
System.out.println(b+" is greatest");
if((c>a) && (c>b))
System.out.println(c+" is greatest");
}
}
ii) if else stmt
-----------------
It will execute the source code either our condition is true or false.
syntax:
------
if(condition)
{
- //code to be execute if cond is true
}
else
{
- //code to be execute if cond is false
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(10 == 10)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}
o/p:
stmt1
stmt2
stmt4
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(10 != 10)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}
o/p:
stmt1
stmt3
stmt4
Q) Write a java program to check given age is eligible to vote or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age :");
int age=sc.nextInt();
if(age>=18)
System.out.println("U r eligible to vote");
else
System.out.println("U r not eligible to vote");
}
}
}
}
Q) Write a java program to find out given number is odd or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
if(n%2!=0)
System.out.println("It is odd number");
else
System.out.println("It is not odd number");
}
}
Q) Write a java program to find out given number is positive or negative?
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(n==0)
{
System.out.println("It is not a positive or negative number");
System.exit(0);
}
if(n>0)
System.out.println("It is positive number");
else
System.out.println("It is negative number");
}
}
Q) Write a java program to find out given year is a leap year or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the year :");
int year=sc.nextInt();
}
}
iii) if else if ladder
------------------------
It will execute the source code based on multiple conditions.
syntaX:
-----
if(cond1)
{
- //code to be execute if cond1 is true
}
else if(cond2)
{
- //code to be execute if cond2 is true
}
else if(cond3)
{
- //code to be execute if cond3 is true
}
else
{
- //code to be execute if all conditions are false.
}
kex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the option :");
int option=sc.nextInt();
if(option==100)
System.out.println("It is police number");
else if(option==103)
System.out.println("It is enquiry number");
else if(option==108)
System.out.println("It is emergency number");
else
System.out.println("Invalid option");
}
}
Q) Write a java program to find out given alphabet is a vowel or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the alphabet :");
char ch=sc.next().charAt(0);
if(ch=='a' || ch=='A')
System.out.println("It is a vowel");
else if(ch=='e' || ch=='E')
System.out.println("It is a vowel");
else if(ch=='i' || ch=='I')
System.out.println("It is a vowel");
else if(ch=='o' || ch=='O')
System.out.println("It is a vowel");
else if(ch=='u' || ch=='U')
System.out.println("It is a vowel");
else
System.out.println("It is not a vowel");
}
}
Q) Write a java program to find out given alphabet is a uppercase letter, lowercase letter , digit
or special symbol?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
while(i<=10)
{
System.out.print(i+" "); // infinite 1
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
while(i<=10)
{
System.out.print(i+" "); // nothing
}
}
}
Q) Write a java program to display 100 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=100)
{
System.out.print(i+" "); //1 2 3 4 5 .... 100
i++;
}
}
}
Q) Write a java program to perform sum of 10 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
while(i<=10)
{
sum+=i;
i++;
}
System.out.println(sum);
}
}
Q) Write a java program to find out factorial of a given number?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //5
int i=n,fact=1;
while(i>=1)
{
fact*=i;
i--;
}
System.out.println(fact);
}
}
Q) Write a java program to display multiplication table of a given number?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //5
int i=1;
while(i<=10)
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
}
}
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
System.out.println(sum);
}
}
Q) Write a java program to find out given number is Armstrong or not?
Input:
153 (1*1*1+5*5*5+3*3*3)(1+125+27)(153)
Output:
It is a armstrong number
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
input:
121
output:
It is a palindrome number
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int temp=n;
int rem,rev=0;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(temp==rev)
System.out.println("It is a palindrome number");
else
System.out.println("It is not a palindrome number");
}
}
syntax:
------
for(initialization;condition;incrementation/decrementation)
{
-
- //code to be execute
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+" ");//1 2 3 4 5 6 7 8 9 10
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=10;i>=1;i--)
{
System.out.print(i+" ");//10 9 8 7 6 5 4 3 2 1
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
sum+=i;
}
System.out.println(sum);//55
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
if(i%2==0) //2 4 6 8 10
{
sum+=i;
}
}
System.out.println(sum);//30
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int even=0;
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
even++;
}
}
System.out.println(even);//5
}
}
ex:
--
class Test
{
public static void main(String[] args)
{
for(;;)
{
System.out.print("Hello ");
}
}
}
prime numbers :
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.println("It is prime number");
else
System.out.println("It is not prime number");
}
}
eclass Test
{
public static void main(String[] args)
{
for(int n=2;n<=100;n++)
{
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.print(n+" ");
}
}
}
Input:
6
Output:
It is a perfect number
ex:
--
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(n==sum)
System.out.println("It is perfect number");
else
System.out.println("It is not perfect number");
}
}
Q) Write a java program to find out GCD (Greatest Common Divisor) of two numbers?
Input:
12 18
Output:
class Test
{
public static void main(String[] args)
{
int a=12,b=18,gcd=0;
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //6
int a=0,b=1,c;
System.out.print(a+" "+b+" ");
for(int i=2;i<=n;i++)
{
c = a + b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
Loop Patterns
==============
1)
1111
2222
3333
4444
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
2)
1234
1234
1234
1234
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
3)
****
****
****
****
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}
4)
4444
3333
2222
1111
class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
5)
AAAA
BBBB
CCCC
DDDD
class Test
{
public static void main(String[] args)
{
//rows
for(char i='A';i<='D';i++)
{
//cols
for(char j='A';j<='D';j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
6)
DDDD
CCCC
BBBB
AAAA
class Test
{
public static void main(String[] args)
{
//rows
for(char i='D';i>='A';i--)
{
//cols
for(char j='A';j<='D';j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
7)
****
* *
* *
****
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
if(i==1 || i==4 || j==1 || j==4)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}
}
}
8)
*---
-*--
--*-
---*
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
if(i==j)
System.out.print("* ");
else
System.out.print("- ");
}
//new line
System.out.println();
}
}
}
9)
*---*
-*-*-
--*--
-*-*-
*---*
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=5;i++)
{
//cols
for(int j=1;j<=5;j++)
{
if(i==j || i+j==6)
System.out.print("* ");
else
System.out.print("- ");
}
//new line
System.out.println();
}
}
}
Mock Test
=========
for loop
--------
1) Write a java program to check given number is prime or not ?
2) Write a java program to display prime numbers from 1 to 100?
3) Write a java program to find out GCD of two numbers?
4) Write a java program to find out fibonacci series of a given number?
5) Write a java program to find out factorial of a given number?
while loop
---------
6) Write a java program to display sum of digits of a give number?
7) Write a java program to find out given number is armstrong or not?
8) Write a java program to display reverse of a given number?
9) Write a java program to find out given number is palindrome or not?
Loop Pattern
------------
10)
*---*
-*-*-
--*--
-*-*-
*---*
Left Side Loop Patterns
=======================
1)
1
22
333
4444
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//columns
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println("");
}
}
}
2)
4444
333
22
1
class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
3)
*
**
***
****
***
**
*
class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
//descending
//rows
for(int i=3;i>=1;i--)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}
4)
1
23
456
7890
class Test
{
public static void main(String[] args)
{
int k=1;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
if(k<=9)
System.out.print(k++ +" ");
else
System.out.print("0 ");
}
//new line
System.out.println();
}
}
}
5)
2
4 6
8 10 12
14 16 18 20
class Test
{
public static void main(String[] args)
{
int k=2;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(k+" ");
k+=2;
}
//new line
System.out.println();
}
}
}
6)
1
3 5
7 9 11
13 15 17 19
ex:
---
class Test
{
public static void main(String[] args)
{
int k=1;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(k+" ");
k+=2;
}
//new line
System.out.println();
}
}
}
7)
2
3 5
7 11 13
17 19 23 29
ex:
class Test
{
public static void main(String[] args)
{
int n=2;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
while(true)
{
boolean flag=true;
for(int k=2;k<=n/2;k++)
{
if(n%k==0)
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.print(n+" ");
n++;
break;
}
else
{
n++;
}
}
}
//new line
System.out.println();
}
}
}
1
22
333
4444
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
}
}
4)
4444
333
22
1
ex:
---
class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
}
}
5)
*
**
***
****
***
**
*
class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
}
}
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
2)
1234321
12321
121
1
ex:
---
class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
3)
*
***
*****
*******
*****
***
*
ex:
class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print("* ");
}
//new line
System.out.println();
}
//descending
//rows
for(int i=3;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}
4)
*
* *
* *
* *
* *
* *
*
ex:
class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}
//descending
//rows
for(int i=3;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}
}
}
Interview Questions
==================
Q) Write a java program to display below loop pattern?
*
*
*****
*
*
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=5;i++)
{
//cols
for(int j=1;j<=5;j++)
{
if(i==3 || j==3)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}
}
}
1 1
12 21
123 321
12344321
class Test
{
public static void main(String[] args)
{
int rows=4;
//rows
for(int i=1;i<=rows;i++)
{
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//space
for(int j=1;j<=(rows-i)*2;j++)
{
System.out.print(" ");
}
//right side elements
for(int j=i;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
1
11
121
1331
14641
ex:
class Test
{
public static void main(String[] args)
{
//rows
for(int i=0;i<5;i++)
{
//space
for(int j=1;j<5-i;j++)
{
System.out.print(" ");
}
int number=1;
for(int k=0;k<=i;k++)
{
System.out.print(number+" ");
number = number * (i-k)/(k+1);
}
//new line
System.out.println();
}
}
}
Note:
-----
If number of iterations are known by the user then we need to use for loop.
If number of iterations are not known by the user then we need to use while loop.
If number of iterations are not known by the user but code must execute atleast for one time then we need to
use do while loop.
4) Jump Statement
==================
Jump statement is used to jump from one section of code to another section.
We have two types of jump statements.
1) break stmt
2) continue stmt
1) break stmt
--------------
It is used to break the execution of loops and switch case.
For conditional statements we can use if condition.
syntax:
------
break;
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
break;
System.out.println("stmt2");
}
}
o/p:
C.T.E : break outside switch or loop
ex:
----
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(true)
{
break;
}
System.out.println("stmt2");
}
}
o/p:
C.T.E : break outside switch or loop
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.print(i+" "); // 1 2 3 4
}
}
}
2) continue stmt
-----------------
It is used to continue the execution of loops.
For conditional statement we can use if condition.
hsyntax:
continue;
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
continue;
System.out.println("stmt2");
}
}
o/p:
continue outside of loop
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(true)
{
continue;
}
System.out.println("stmt2");
}
}
o/p:
C.T.E continue outside of loop
ex:
----
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.print(i+" "); //1 2 3 4 6 7 8 9 10
}
}
}
Assignment program
=================
Input:
123
Output:
ThreeTwoOne
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//123
while(n>0)
{
switch(n%10)
{
case 0 : System.out.print("Zero");break;
case 1 : System.out.print("One");break;
case 2 : System.out.print("Two");break;
case 3 : System.out.print("Three");break;
case 4 : System.out.print("Four");break;
case 5 : System.out.print("Five");break;
case 6 : System.out.print("Six");break;
case 7 : System.out.print("Seven");break;
case 8 : System.out.print("Eight");break;
case 9 : System.out.print("Nine");break;
}
n=n/10;
}
}
}
Q) Write a java program to perform factorial of a given number using no returntype with no argument method ?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
factorial();
}
//callie method
public static void factorial()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //5
int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
System.out.println("Factorial of a given number is ="+fact);
}
}
//caller method
sum(a,b);
}
//callie method
public static void sum(int a,int b)
{
int c=a+b;
System.out.println("sum of two numbers is ="+c);
}
}
Q) Write a java program to perform cube of a given number using no returntype with argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//5
//caller method
cube(n);
}
//callie method
public static void cube(int n)
{
int result=n*n*n;
System.out.println("cube of a given number is ="+result);
}
}
3) With returntype with No argument method
------------------------------------------
Returntype is completely depends on output datatype.
Q) Write a java program to perform sum of two numbers using with returntype with no argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
int k=sum();
System.out.println("sum of two numbers is ="+k);
}
//callie method
public static int sum()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
int c=a+b;
return c;
}
}
Q) Write a java program to perform area of a circle using with return with no argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
float k=circle();
System.out.println("Area of a circle is "+k);
}
//callie method
public static float circle()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();
float area=3.14f*r*r;
return area;
}
}
4) With returntype with argument method
--------------------------------------
Q) Write a java program to perform sum of two numbers using with returntype with argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
//caller method
System.out.println("sum of two numbers is ="+sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
int c=a+b;
return c;
}
}
Q) Write a java program to check given number is even or odd using with returntype with argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//4
//caller method
if(find(n))
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
//callie method
public static boolean find(int n)
{
if(n%2==0)
return true;
else
return false;
}
}
Assignment
==========
Recursion
===========
A method which call itself for many number of times is called recursion.
Recursion is similar to loopings.
Whenever we use recursion then we should not use loops.
class Test
{
public static void main(String[] args)
{
//caller method
display(1);
}
//callie method
public static void display(int i)
{
if(i<=10)
{
System.out.print(i+" ");
display(i+1);
}
}
}
Q) Write a java program to perform sum of two numbers without using arithmetic operator ?
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//caller method
System.out.println(sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
if(a==0)
return b;
return sum(--a,++b);
}
}
Q) Write a java program to find out factorial of a given number using recursion?
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//caller method
System.out.println(factorial(n));
}
//callie method
public static int factorial(int n)
{
if(n<0)
return -1;
if(n==0)
return 1;
return n*factorial(n-1);
}
}
Q) Write a java program to find out N-th element of fibonacci series?
fibonacci sequence : 0 1 1 2 3 5 8
Input:
4
Output:
2
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
}
//callie method
public static int fib(int n)
{
if(n==0 || n==1)
return 0;
if(n==2)
return 1;
return fib(n-1)+fib(n-2);
}
}
Arrays
=======
Array is a collection of homogeneous data elements.
The main advantages of arrays are
1) We can represent multiple elements using single variable name.
ex:
int[] arr={10,20,30};
2) To use array concept in advanced we should known what is the size of an array which is always not
possible.
In java, arrays are divided into three types.
1) Single Dimensional Array
2) Double Dimensional Array
3) Multi Dimensional Array
Array Declaration
------------------
At the time of array declaration we should not specify array size.
ex:
Array
|---------------------------------|--------------------------|
Single Dimensional Array Double Dimensional Array MultiDimensional Array
Array Creation
--------------
In java , every array consider as an object.Hence we will use new operator to create an array.
ex:
int[] arr=new int[3];
Diagram: class18.1
Rule2:
------
It is legal to have an array size with zero.
ex:
int[] arr=new int[0];
System.out.println(arr.length);//0
Rule3:
------
We can't give negative number as an array size otherwise we will get
NegativeArraySizeException.
ex:
int[] arr=new int[-3]; //R.E NegativeArraySizeException
Rule4:
-----
The allowed datatype for an array size is byte,short,int and char.
If we take other datatypes then we will get compile time error.
ex:
byte b=10;
int[] arr=new int[b];
Rule5:
-----
The maximum size we can take for an array size is maximum length of int.
ex:
int[] arr=new int[2147483647];
Array Initialization
--------------------
Whenever we create an array , every array element will be initialized with default values.
If we are not happy with default values then we can change those values with customized values.
Diagram: java18.2
Array Declaration , Creation and Initialization using single line
-------------------------------------------------------------------
int[] arr;
arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30; ==> int[] arr={10,20,30};
char[] carr={'a','b','c'};
String[] sarr={"hi","hello","bye"};
length length()
------------ -----------
It is a final variable which is applicable It is a final method which is applicable
only for arrays. only for String objects.
ex: ex:
-- ---
int[] arr=new int[3]; String str="bhaskar";
System.out.println(arr.length);//3 System.out.println(str.length());//7
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30;
}
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30};
Note:
------
For each loop is used to iterate the elements from array.
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30};
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
t
Q) Write a java program to insert some array element and display them?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array size :");
int size=sc.nextInt();//5
//inserting elements
for(int i=0;i<arr.length;i++)
{
System.out.println("Enter the element :");
arr[i]=sc.nextInt();
}
//display elements
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
output:
531926
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};
//reading reverse
for(int i=arr.length-1;i>=0;i--)
{
System.out.print(arr[i]+" ");
}
}
}
input:
629135
output:
26
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};
int sum=0;
for(int i:arr)
{
sum+=i;
}
System.out.println(sum);
}
}
input:
629135
output:
62
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};
for(int i:arr)
{
if(i%2==0)
{
System.out.print(i+" ");
}
}
}
}
input:
629135
output:
Even elements : 2
Odd elements : 4
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};
int even=0,odd=0;
for(int i:arr)
{
if(i%2==0)
{
even++;
}
else
{
odd++;
}
}
System.out.println("Even elements :"+even);
System.out.println("odd elements :"+odd);
}
}
Q) Write a java program to display prime elements from given array?
input:
4 2 8 7 9 11 21 12
output:
2 7 11
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,2,8,7,9,11,21,12};
for(int n:arr)
{
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.print(n+" ");
}
}
}
output:
124569
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
Arrays.sort(arr);
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
Q) Write a java program to display array elements in sorting order without using sort() method?
input:
629154
output:
124569
ex:
--
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
//ascending logic
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
if(arr[i]<arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
input:
629154
output:
965421
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
Arrays.sort(arr);//1 2 4 5 6 9
//reading reverse
for(int i=arr.length-1;i>=0;i--)
{
System.out.print(arr[i]+" ");
}
}
}
Q) Write a java program to display array elements in descending order without using sort() method ?
input:
629154
output:
965421
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
//descending order
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//reading elements
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
input:
629154
output:
9
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
Arrays.sort(arr);//1 2 4 5 6 9
System.out.println(arr[arr.length-1]);
}
}
Q) Write a java program to display highest element from given array without using sort() method?
input:
629154
output:
9
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
int big=arr[0];
for(int i:arr)
{
if(i>big)
{
big=i;
}
}
System.out.println("Highest element is ="+big);
}
}
Q) Write a java program to display least element from given array ?
input:
629154
output:
1
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
Arrays.sort(arr);//1 2 4 5 6 9
System.out.println(arr[0]);
}
}
Q) Write a java program to display least element from given array without using sort() method ?
input:
629154
output:
1
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};
int small=arr[0];
for(int i:arr)
{
if(i<small)
{
small=i;
}
}
System.out.println(small);
}
}
Q) Write a java program to display three highest elements from given array?
input:
47196283
output:
987
class Test
{
public static void main(String[] args)
{
int[] arr={4,7,1,9,6,2,8,3};
int firstElement=Integer.MIN_VALUE;
int secondElement=Integer.MIN_VALUE;
int thirdElement=Integer.MIN_VALUE;
for(int i:arr)
{
if(i>firstElement)
{
thirdElement=secondElement;
secondElement=firstElement;
firstElement=i;
}
else if(i>secondElement)
{
thirdElement=secondElement;
secondElement=i;
}
else if(i>thirdElement)
{
thirdElement=i;
}
}
System.out.println(firstElement+" "+secondElement+" "+thirdElement);
}
}
input:
1010011010
output:
0000011111
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={1,0,1,0,0,1,1,0,1,0};
//inserting '0'
int j=0;
for(int i:arr)
{
if(i==0)
{
resArr[j++]=i;
}
}
//inserting '1'
while(j<arr.length)
{
resArr[j++]=1;
}
//display elements
for(int i:resArr)
{
System.out.print(i+" ");
}
}
}
Q) Write a java to add two array elements and store them in third array?
input:
arr1 = 1 6 9 4 2
arr2 = 8 2 7 3 6
output:
9 8 16 7 8
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr1 ={1,6,9,4,2};
int[] arr2 ={8,2,7,3,6};
}
}
Q) Write a java program to merge two array and display them in sorting order?
input:
arr1 = 5 1 3 4 2
arr2 = 9 6 8 7 10
output:
1 2 3 4 5 6 7 8 9 10
ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr1 ={5,1,3,4,2};
int[] arr2 ={9,6,8,7,10};
int size1=arr1.length;
int size2=arr2.length;
arr1=Arrays.copyOf(arr1,size1+size2);
int j=0;
for(int i=size1;i<arr1.length;i++)
{
arr1[i]=arr2[j++];
}
Arrays.sort(arr1);
}
}
Q) Write a java program to find out missing element from given array?
input:
157263
output:
4
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={1,5,7,2,6,3};
int sum_of_arr_ele=arr.length+1;
for(int i:arr)
{
sum=sum-i;
}
System.out.println(sum);
}
}
input:
571395372
output:
573
class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,5,3,7,2};
//duplicates
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
System.out.print(arr[i]+" ");
}
}
}
}
}
input:
571395372
output:
192
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,5,3,7,2};
//uniques
for(int i=0;i<arr.length;i++)
{
int cnt=0;
for(int j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
cnt++;
}
}
if(cnt==1)
System.out.print(arr[i]+" ");
}
}
}
Q) Write a java program to find out most repeating element from given array?
input:
528921627247
output:
2 is repeating for 4 times
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={5,2,8,9,2,1,6,2,7,2,4,7};
int element=0;
int maxCount=0;
for(int i=0;i<arr.length;i++)
{
int cnt=0;
for(int j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
cnt++;
}
}
if(maxCount<cnt)
{
maxCount=cnt;
element=arr[i];
}
}
Q) Write a java program to find out leader element from given array?
input:
4 9 34 5 12 1 9
output:
9 12 34
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,9,34,5,12,1,9};
int max=arr[arr.length-1];
System.out.print(max+" ");
for(int i=arr.length-2;i>=0;i--)
{
if(arr[i]>max)
{
max=arr[i];
System.out.print(max+" ");
}
}
}
}
input:
arr = 3 6 1 4 9 2 7
sum = 10
output:
37
64
19
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={3,6,1,4,9,2,7};
int sum=10;
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]+arr[j]==sum)
{
System.out.println(arr[i]+" "+arr[j]);
}
}
}
}
}
input:
arr = 3 6 1 4 9 2 7
sum = 10
output:
361
127
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={3,6,1,4,9,2,7};
int sum=10;
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
for(int k=j+1;k<arr.length;k++)
{
if(arr[i]+arr[j]+arr[k]==sum)
{
System.out.println(arr[i]+" "+arr[j]+" "+arr[k]);
}
}
}
}
}
}
input:
arr = 5 2 9 1 2 6 7 2
element = 2
output:
5912672
class Test
{
public static void main(String[] args)
{
int[] arr ={5,2,9,1,2,6,7,2};
int element=2;
int cnt=0;
for(int i:arr)
{
if(i==element && cnt==0)
{
cnt=1;
continue;
}
System.out.print(i+" ");
}
}
}
input:
arr = 6 2 9 1 4 3 7
index = 3
element = 10
output:
6 2 9 10 1 4 3 7
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr ={6,2,9,1,4,3,7};
int index = 3;
int element=10;
arr=Arrays.copyOf(arr,arr.length+1);
for(int i=arr.length-1;i>=index;i--)
{
arr[i]=arr[i-1];
}
arr[index]=element;
//display
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
Q) Write a java program to identify and print all elements in an array that are greater
than both their immediate predecessors and successors, considering the first and
last elements as having only one neighbor?
Input:
1 3 20 4 75 0 90
Output:
20 75 90
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={1,3,20,4,75,0,90};
//first element
if(arr[0]>arr[1])
{
System.out.print(arr[0]+" ");
}
//middle elements
for(int i=1;i<arr.length-1;i++)
{
if(arr[i]>arr[i-1] && arr[i]>arr[i+1])
{
System.out.print(arr[i]+" ");
}
}
//last element
if(arr[arr.length-1]>arr[arr.length-2])
{
System.out.print(arr[arr.length-1]);
}
}
}
Q)
Write a java program to determine the smallest number of coins needed to total
86 rupees. Use the denominations provided in the array {1,2,5,10}?
Output:
1 coin(s) of 1 rupee(s)
1 coin(s) of 5 rupee(s)
8 coin(s) of 10 rupee(s)
ex:
class Test
{
public static void main(String[] args)
{
int[] denominations={1,2,5,10};
int amount=86;
//caller method
int[] result=findMinimumCoins(denominations,amount);
for(int i=0;i<result.length;i++)
{
if(result[i]>0)
{
System.out.println(result[i]+" coin(s) of "+denominations[i]+" rupee(s)");
}
}
}
//callie method
public static int[] findMinimumCoins(int[] denominations,int amount)
{
int[] coinsCount=new int[denominations.length];
for(int i=denominations.length-1;i>=0;i--)
{
coinsCount[i]=amount/denominations[i];
amount%=denominations[i];
}
return coinsCount;
}
}
Double dimensional array is implemented based on array or arrays approach but not matrix form.F
Double dimensional array is used to develop matrix type of applications, gaming applications , business
oriented applications and etc.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the rows :");
int rows=sc.nextInt();
//insert elements
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.println("Enter the element :");
arr[i][j]=sc.nextInt();
}
}
//display elements
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.print(arr[i][j]+" ");
}
//new line
System.out.println();
}
}
}
input:
123
456
789
output:
1 4 9
16 25 36
49 64 81
ex:
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
System.out.print(arr[i][j] * arr[i][j]+" ");
}
//new line
System.out.println();
}
}
}
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i==j)
{
sum+=arr[i][j];
}
}
}
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i<j)
{
sum+=arr[i][j];
}
}
}
int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i>j)
{
sum+=arr[i][j];
}
}
}
input:
123
456
789
output:
123698745
ex:
class Test
{
public static void main(String[] args)
{
int[][] matrix={
{1,2,3},
{4,5,6},
{7,8,9}
};
int rows=matrix.length;
int cols=matrix[0].length;
int top=0;
int bottom=rows-1;
int left=0;
int right=cols-1;
while(true)
{
if(left>right)
{
break;
}
for(int i=left;i<=right;i++)
{
System.out.print(matrix[top][i]+" ");
}
top++;
if(top>bottom)
{
break;
}
for(int i=top;i<=bottom;i++)
{
System.out.print(matrix[i][right]+" ");
}
right--;
if(left>right)
{
break;
}
for(int i=right;i>=left;i--)
{
System.out.print(matrix[bottom][i]+" ");
}
bottom--;
if(top>bottom)
{
break;
}
for(int i=bottom;i>=top;i--)
{
System.out.print(matrix[i][left]+" ");
}
left++;
}
}
}
Anonymous Array
===============
Sometimes we will declare an array without name such type of nameless array is called anonymous array.
ex:
new int[]{10,20,30};
new int[][]{{10,20,30},{40,50,60}};
ex:
---
class Test
{
public static void main(String[] args)
{
//caller method
sum(new int[]{10,20,30});
}
//callie method
public static void sum(int[] arr)
{
int sum=0;
for(int i:arr)
{
sum+=i;
}
System.out.println(sum);
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
//caller method
System.out.println(sum(new int[]{10,20,30}));
}
//callie method
public static int sum(int[] arr)
{
int sum=0;
for(int i:arr)
{
sum+=i;
}
return sum;
}
}
input:
47139
output:
13479
class Test
{
public static void main(String[] args)
{
//code here
}
//callie method
public static int[] sort(int[] arr)
{
//code here
}
}
solution
----------
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={4,7,1,3,9};
//caller method
int[] result=sort(arr);
return arr;
}
}
Assignment
==========
Q) Write a java program to find out second highest element from given array?
Input:
6 9 1 4 7 5 2
output:
7
class Test
{
public static void main(String[] args)
{
//code here
}
//callie method
public static int sort(int[] arr,int size)
{
//code here
return secondElement;
}
}
OOPS
=====
OOPS stands for Object Oriented Programming System/Structure.
OOPS are used to deal with real world entities using programming language.
OOPS contains following features.
ex:
class
object
Abstraction
Encapsulation
Inheritance
Polymorphism
Object oriented technology
--------------------------
A technology which provides very good environment to represent our data in the form of objects is called
object oriented technology.
class
======
A class is a blue print of an object.
A class is a collection of objects.
A class is a logical entity.
We can declare a class as follow.
syntax:
optional
|
modifier class class_name <extends> Parent_classname
<implements> Interface_name
{
-
- // variables
- // methods
-
}
If we declare any class default then we If we declare any class as public then we
can access that class within the package. can access that class within the package and
outside the package.
Q) What is the difference between final class and abstract class?
final class abstract class
------------- ---------------
To declare final class we will use final To declare abstract class we will use abstract
modifier. modifier.
ex: ex:
final class A abstract class A
{ {
} }
Child creation is not possible. Child creation is possible.
Object creation is possible. Object creation is not possible.
object
======
It is a outcome of a blue print.
It is a instance of a class.
Here instance means allocating memory of our data members.
It is a collection of properties and behaviours.
It is a physical entity.
realtime example
---------------
Dog (object)
|
|----------------------------------------------|
properties behaviours
Name barking
Breed bitting
Color eating
Age running
Height sleeping
Weight and etc.
and etc
ex:
----
class Test
{
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
System.out.println(t3.hashCode());
System.out.println(t1); //Test@Hexadecimanumber
System.out.println(t2.toString());
System.out.println(t3.toString());
}
}
Q) What is hash code in java?
For every object, JVM will create a unique identification number i.e hash code.
In order to read hash code of an object we need to use hashCode() method of Object class.
Diagram: java23.1
Q) What is toString() method?
A toString() method present in Object class.
Whenever we are trying to display any object reference , directly or indirectly toString() method will be
executed.
Q) What is Object class?
Object class consider as parent class for every java class.
Object class present in java.lang package.
Object class contains following methods.
ex:
cmd> javap java.lang.Object
hashCode()
toString()
wait()
notify()
notifyAll()
getClass()
and etc.
Q) What is the difference between class and object?
class object
---------- ---------
It is a blue print of an object. It is a instance of a class.
It is a logical entity. It is a physical entity.
It does not allocate memory. It allocates memory.
It does not manipulate. It manipulates.
It declares only once. It declares many times.
To declare a class we will use class keyword. To declare object we will use new keyword.
Data Hiding
===========
The process of hiding object data from the outsider is called data hiding.
The main objective of data hiding is to provide security.
Using "private" modifier we can implements data hiding concept.
ex:
---
class Account
{
private double balance=5000d;
}
class Test
{
public static void main(String[] args)
{
Account account=new Account();
System.out.println(account.balance);
}
}
Abstraction
============
Hiding internal implementation and highlighting the set of services is called abstraction.
Using abstract classes and interfaces we can implements abstraction.
The best example of abstraction is GUI ATM machine where bank people will hide internal implementation and
highlights the set of services like banking, withdrawl, mini statement and etc.
The main advatages of abstraction are
1) It gives security because it will hide internal implementation from outsider.
2) Enhancement becomes more easy without effecting enduser they can perform any changes in our internal
system.
3) It provides flexibility to the enduser to use the system.
4) It improves maintainability of an application.
In realtime we will use abstraction to hide the data.
Encapsulation
==============
The process of encapsulating or grouping variables and it's associate methods in a single unit is called
encapsulation.
Diagram: java24.1
//setter methods
public void setStudId(int studId)
{
this.studId=studId;
}
public void setStudName(String studName)
{
this.studName=studName;
}
public void setStudFee(double studFee)
{
this.studFee=studFee;
}
//getter methods
public int getStudId()
{
return studId;
}
public String getStudName()
{
return studName;
}
public double getStudFee()
{
return studFee;
}
class Test
{
public static void main(String[] args)
{
Student s=new Student();
s.setStudId(101);
s.setStudName("Alan");
s.setStudFee(1000d);
System.out.println("Student Id :"+s.getStudId());
System.out.println("Student Name :"+s.getStudName());
System.out.println("Student Fee :"+s.getStudFee());
}
}
Q) What is the difference between Abstraction and Encapsulation?
Abstraction Encapsulation
----------- ----------------
Hiding internal implementation and highlighting The process of encapsulating or grouping variables
the set of services is called abstraction. and its associate methods in a single unit is
called encapsulation.
It is used to hide the data. It is used to protect the data.
Using abstract classes and interfaces we can Using access modifiers we can implements
implements abstraction. encapsulation.
//zero-argument constructor
Student()
{
System.out.println("0-arg const");
}
//setter methods
public void setStudId(int studId)
{
this.studId=studId;
}
public void setStudName(String studName)
{
this.studName=studName;
}
public void setStudFee(double studFee)
{
this.studFee=studFee;
}
//getter methods
Is-A relationship
=================
Is-A relationship is also known as inheritance.
Using "extends" keyword we can implements Is-A relationship.
The main objective of Is-A relationship is to provide reusability.
ex:
---
class Honda
{
public void price()
{
System.out.println("Honda-price method");
}
}
class HondaAmaze extends Honda
{
public void model()
{
System.out.println("HondaAmaze-Model method");
}
}
class Customer
{
public static void main(String[] args)
{
Honda h=new Honda();
h.price(); //Honda-price method
Inheritance
============
Inheritance is a mechanism in which we derived a class in the presence of existing class.
Inheritance is a mechanism in which one class will inherit the properties of another class.
The main object of inheritance is to achieve reusability.
Diagram: java25.1
B b=new B();
b.m1();
b.m2();
}
}
ex:
---
class A
{
int i=10;
}
class B extends A
{
int j=20;
}
class Test
{
public static void main(String[] args)
{
A a=new A();
System.out.println(a.i); //10
B b=new B();
System.out.println(b.i+" "+b.j);//10 20
}
}
2) Multi level inheritance
---------------------------
If we derived a class in the presence of one base class and that class is derived from another base class is
called multi level inheritance.
Diag:
A
|
|
|
B
|
|
|
C
Ex class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class C extends B
{
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();
B b=new B();
b.m1();
b.m2();
C c=new C();
c.m1();
c.m2();
c.m3();
}
}
3) Multiple inheritance
-----------------------
In java, we can't extends more then one class simulteneously because java does not support multiple
inheritance.
ex:
class A
{
}
class B
{
}
class C extends A,B --> invalid
{
}
Interface can extends more then one interface.Hence we can achieve multiple inheritance concept through
interfaces.
ex:
interface A
{
}
interface B
{
}
interface C extends A,B
{
}
If our class does not extends any other class then it is a direct child class of Object class.
ex: diag:
class A Object
{ |
|
} A
If our class extends some other class then our class is a indirect child class of Object class.
ex: diag:
class A Object
{ |
|
} |
class B extends A A
{ |
|
} |
B
4) Hierarchical inheritance
---------------------------
If we derived multiple classes by using one base class is called hierarchical inheritance.
Diag:
A
|
|-------------------------------|
B C
ex:
---
class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class C extends A
{
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();
B b=new B();
b.m1();
b.m2();
C c=new C();
c.m1();
c.m3();
}
}
5) Hybrid inheritance
------------------------
Hybrid inheritance is a combination of more then one inheritance.
Java does not support hybrid inheritance.
Diag:
A
|
|-------------------------------|
B C
|-------------------------------|
|
D
Has-A relationship
===================
Has-A relationship is also known as composition and aggregation.
There is no specific keyword to implements Has-A relationship but mostly we will use new operator.
The main objective of Has-A relationship is to provide reusability.
Has-A relationship will increase dependency between two components.
ex:
----
class Engine
{
-
- //engine specific functionality
-
}
class Car
{
Engine e=new Engine();
-
-
}
ex:
---
class Ihub
{
public String courseName()
{
return "Full Stack Java Development";
}
public double courseFee()
{
return 30000d;
}
public String trainerName()
{
return "Niyaz Sir";
}
}
class Usha
{
public void getCourseDetails()
{
Ihub i=new Ihub();
System.out.println("Course Name :"+i.courseName());
System.out.println("Course Fee :"+i.courseFee());
System.out.println("Trainer Name :"+i.trainerName());
}
}
class Student
{
public static void main(String[] args)
{
Usha u=new Usha();
u.getCourseDetails();
}
Composition
===========
Without existing container object there is no chance of having contained object then the relationship between
container and contained object is called composition which is strongly association.
Diagram: java25.2
Aggregation
===========
Without existing container object there is a chance of having contained object then the relationship between
container and contained object is called aggregation which is loosely association.
Diagram: java25.3
Method Overloading
===================
Having same method name with different parameters/signatures in a single class is called method overloading.
Methods which are present in a class are called overloaded methods.
Method overloading will reduce complexity of the programming.
ex:
---
class MeeSeva
{
//overloaded methods
public void search(int voterId)
{
System.out.println("Details Found via voterId");
}
public void search(String houseNo)
{
System.out.println("Details Found via houseNo");
}
public void search(long aadharNo)
{
System.out.println("Details Found via aadharNo");
}
}
class Test
{
public static void main(String[] args)
{
MeeSeva ms=new MeeSeva();
ms.search(1001);
ms.search("1-4-76/A/1");
ms.search(22222L);
}
}
Q) Can we overload main method in java?
Yes, we can overload main method in java but JVM always execute main method with String[] parameter only.
ex:
class Test
{
public static void main(int[] iargs)
{
System.out.println("int arg method");
}
public static void main(String[] args)
{
System.out.println("String arg method");
}
}
Method Overriding
=================
Having same method name with same argument in two different classes is called method overriding.
Methods which are present in parent class are called overridden methods.
Methods which are present in child class are called overriding methods.
ex:
----
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
//overridden methods
public void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
//overriding methods
public void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi
o/p:
C.T.E
Method Hiding
==============
Method hiding is exactly same as method overriding with following differences.
Method overriding Method hiding
----------------- ----------------
Methods present in method overriding must Methods present in method hiding must be
be non-static. static.
Method resolution will taken care by Method resolution will taken care by compiler
JVM based on runtime object. based on reference type.
ex:
---
class Parent
{
public static void property()
{
System.out.println("cash+gold+land");
}
public static void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
public static void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi
Polymorphism
=============
Polymorphism has taken from Greek Word.
Here poly means many and morphism means forms.
The ability to represent in different forms is called polymorphism.
Diagram: java26.1
The main objective of polymorphism is to provide flexibility.
In java, polymorphism is divided into two types.
1) Compile time Polymorphism / Static Polymorphism / Early Binding
2) Runtime Polymorphism / Dynamic Polymorphism / Late Binding
Method resolution taken care by compiler based Method resolution taken care by JVM based on
on reference type. runtime object.
Private and final methods can be overloaded. Private and final methods can’t be overridden.
Summary Diagram: java26.2
Constructors
=============
It is a special method which is used to create and initialize an object.
Having same name as class name is called constructor.
It does not allow any returntype.
It will execute when we create an object.
A constructor a will accept following modifiers.
ex:
default
public
private
protected
We can declare a constructor as follow.
ex:
Test t=new Test();
|
constructor
In java, constructors are divided into two types.
1) Userdefined constructor
2) Default constructor
1) Userdefined constructor
--------------------------
A constructor which is created by the user based on the application requirement is called userdefined
constructor.
User defined constructor is classified into two types.
i) Zero-Argument constructor
ii) Parameterized constructor
i) Zero-Argument constructor
-----------------------------
Suppose if we are not passing any argument to userdefined constructor then that constructor is called 0-arg
constructor.
ex:
---
class Test
{
//constructor
Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
System.out.println("main-method");
}
}
ex:
--
class Test
{
//constructor
public Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println("main-method");
}
}
o/p:
constructor
main-method
ex:
---
class Test
{
//constructor
private Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t1=new Test();
System.out.println("main-method");
Test t2=new Test();
}
}
o/p:
constructor
main-method
constructor
ex:
---
class Test
{
//constructor
protected Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t1=new Test();
System.out.println("main-method");
Test t2=new Test();
}
}
o/p:
constructor
main-method
constructor
constructor overloading
=====================
Having same constructor name with different parameters in a single class is called constructor overloading.
ex:
---
class A
{
A()
{
System.out.println("0-arg const");
}
A(int i)
{
System.out.println("int-arg const");
}
A(double d)
{
System.out.println("double-arg const");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A(10);
A a3=new A(10.5d);
}
}
this keyword
============
A "this" keyword is a java keyword which is used to refer current class object reference.
super keyword
==============
A "super" keyword is a java keyword which is used to refer super class object reference.
interface
==========
Interface is a collection of zero or more abstract methods.
Abstract method is a incomplete method because it ends with semicolon and does not have any body.
ex:
void methodOne();
It is possible to create object for implementation class because it contains method with body.
syntax:
------
interface interface_name
{
-
- //abstract methods
- //constants
-
}
Note:
-----
If we know only service requirement specification then we need to use interface.
Diagram: java27.1
ex:1
---
interface A
{
//abstract method
public abstract void m1();
}
class B implements A
{
//override
public void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
}
}
ex:2
-----
interface A
{
//abstract method
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
A a=new A()
{
public void m1()
{
System.out.println("From M1 Method");
}
};
a.m1();
}
}
If interface contains four methods then we need to override all methods otherwise we will get compile time
error.
ex:
interface A
{
//abstract methods
public abstract void see();
public void show();
abstract void view();
void display();
}
class B implements A
{
public void see()
{
System.out.println("see-method");
}
public void show()
{
System.out.println("show-method");
}
public void view()
{
System.out.println("view-method");
}
public void display()
{
System.out.println("display-method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.see();
a.show();
a.view();
a.display();
}
}
A class can't extends more then one class but interface can extends more then one interface.
ex:
--
interface A
{
void m1();
}
interface B
{
void m2();
}
interface C extends A,B
{
void m3();
}
class D implements C
{
public void m1()
{
System.out.println("M1-Method");
}
public void m2()
{
System.out.println("M2-Method");
}
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
D d=new D();
d.m1();
d.m2();
d.m3();
}
}
ex:
---
interface Father
{
double HT=6.2d;
void height();
}
interface Mother
{
double HT=5.8d;
void height();
}
class Child implements Father,Mother
{
public void height()
{
double height=(Father.HT+Mother.HT)/2;
System.out.println("Child Height is ="+height);
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
c.height();
}
}
Note:
------
According to Java 8 , interface is a collection of abstract methods, default methods and static methods.
Abstract class
===============
Abstract class is a collection of zero or more abstract methods and concrete methods.
A abstract keyword is applicable for class and method but not for variables.
It is not possible to create object for abstract class.
syntax:
abstract class class_name
{
-
- //abstract methods
- //concrete methods
- //instance variables
-
}
Note:
-----
If we know partial implementation then we need to use abstract class.
ex:
----
abstract class Plan
{
protected double rate;
//abstract method
public abstract void getRate();
//concrete method
public void calculateBillAmt(int units)
{
System.out.println("Total Units :"+units);
System.out.println("Total Bill :"+(rate*units));
}
}
class DomesticPlan extends Plan
{
public void getRate()
{
rate=2.5d;
}
}
class CommercialPlan extends Plan
{
public void getRate()
{
rate=5.0d;
}
}
class Test
{
public static void main(String[] args)
{
DomesticPlan dp=new DomesticPlan();
dp.getRate();
dp.calculateBillAmt(250);
Abstraction example
====================
abstract class Animal
{
public abstract void makeSound();
}
class Dog extends Animal
{
public void makeSound()
{
System.out.println("Boow! Boow!");
}
}
class Test
{
public static void main(String[] args)
{
Dog d=new Dog();
d.makeSound();
}
}
If we know only specification then we need to If we know partial implementation then we need to
use interface. use abstract class.
Marker Interface
================
Interface which does not have any methods and constants is called marker interface.
ex:
Serializable
Cloneable
Remote
and etc.
ex:
---
class Item implements java.io.Serializable
{
private int itemId;
private String itemName;
private double itemPrice;
API
=====
API stands for Application Programming Interface.
1) Predefined API
-----------------
Built-In API is called predefined API.
ex:
https://docs.oracle.com/javase/8/docs/api/
2) Userdefined API
-----------------
API which is created by the user based on the application requirements.
package
=========
A package is a collection of a classes,interfaces, enums and annotations.
1) Predefined packages
2) Userdefined packages
1) Predefined packages
---------------------
Built-in packages are called predefined packages.
ex:
java.lang
java.io
java.util
java.sql
and etc.
2) Userdefined packages
-----------------------
A package which is created by the user based on the application requirement is called userdefined package.
syntax:
-----
package package_name;
ex:
----
package com.ihub.www;
import java.util.Calendar;
class Test
{
public static void main(String[] args)
{
Calendar c=Calendar.getInstance();
int h=c.get(Calendar.HOUR_OF_DAY);
if(h<12)
System.out.println("Good Morning");
else if(h<16)
System.out.println("Good Afternoon");
else if(h<20)
System.out.println("Good Evening");
else
System.out.println("Good Night");
}
}
current directory
|
javac -d . Test.java
|
destination location
A class which allows us to create only one object is called singleton class.
It is a design pattern that ensures that a class can only have one object.
Using a class if we call any method and that method returns same class object is called singleton class.
ex:
Calendar c=Calendar.getInstance();
LocalTime time=LocalTime.now();
LocalDate date=LocalDate.now();
and etc.
To create a singleton class, a class must have private constructor and static method.
ex:
----
class Singleton
{
static Singleton singleton=null;
private Singleton()
{
}
//static method
public static Singleton getInstance()
{
if(singleton==null)
{
singleton=new Singleton();
}
return singleton;
}
}
class Test
{
public static void main(String[] args)
{
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
Enum
=====
Enum is a group of named constants.
Using enum we can created our own datatype called enumerated datatype.
syntax:
--------
enum <type_name>
{
value1,value2,valu3,....,valueN
}
ex:
----
enum Months
{
JAN,FEB,MAR
}
ex:
class Test
{
public static void main(String[] args)
{
Months m=Months.JAN;
System.out.println(m);//JAN
}
}
ex:
---
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months m=Months.FEB;
switch(m)
{
case JAN: System.out.println("January"); break;
case FEB: System.out.println("February"); break;
case MAR: System.out.println("March"); break;
}
}
}
java.lang.Enum
---------------
The power to enum will be inherited from java.lang.Enum class.
1) values()
-----------
It will return group of constants from enum.
2) ordinal()
-----------
It will return ordinal numbers.
ex:
---
enum Week
{
MON,TUE,WED,THU,FRI,SAT,SUN
}
class Test
{
public static void main(String[] args)
{
Week[] week=Week.values();
for(Week w:week)
{
System.out.println(w+" --------------- "+w.ordinal());
}
}
}
When compare to old language enum, java enum is more powerful because in addition to constants we can
declare variables, methods and constructors.
ex:
---
enum Drinks
{
COLA,SPRITE,MAZAA,STING;
Drinks()
{
System.out.println("constructor");
}
}
class Test
{
public static void main(String[] args)
{
Drinks d=Drinks.COLA;
}
}
ex:
---
enum Cloths
{
COTTON,KHADI,SILK;
Inner classes
==============
Sometimes we will declare a class inside another class such concept is called inner class.
ex:
class Outer
{
class Inner
{
-
- //code to declare
-
}
}
But due to powerful features of inner classes , programmers started to use inner classes in regular
programming.
If we compile above program then we will get two .class files i.e
Outer.class and Outer$Inner.class.
ex:
---
class Outer
{
class Inner
{
public void m1()
{
System.out.println("Inner-M1 method");
}
}
Wrapper classes
===============
The main objective of wrapper classes are
ex:
Primitive type wrapper class
--------------- -------------
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
constructor
-------------
Every wrapper class contains two methods.One will take corresponding primitive as an argument and another
will take corresponding string as an argument.
ex:
Wrapper class constructor
------------------ --------------
Byte byte or String
Short short or String
Integer int or String
Long long or String
Float float or String
Double double or String
Boolean boolean or String
Character char
ex:
---
class Test
{
public static void main(String[] args)
{
Integer i1=new Integer(10);
System.out.println(i1);
ex:
---
class Test
{
public static void main(String[] args)
{
Character c=new Character('a');
System.out.println(c);//a
}
}
Utility methods
---------------
1) valueOf()
-----------
It is similar to constructor.
ex:
class Test
{
public static void main(String[] args)
{
Integer i1=Integer.valueOf(10);
System.out.println(i1);//10
Integer i2=Integer.valueOf("20");
System.out.println(i2);//20
}
}
2) xxxValue()
-------------
It is used to convert wrapper object to primitive type.
ex:
--
class Test
{
public static void main(String[] args)
{
Integer i=new Integer(10);
short s=i.shortValue();
System.out.println(s);//10
byte b=i.byteValue();
System.out.println(b);//10
}
}
3) parseXxx()
--------------
It is used to convert string type to primitive type.
ex:
---
class Test
{
public static void main(String[] args)
{
String str="10";
int i=Integer.parseInt(str);
System.out.println(i);
long l=Long.parseLong(str);
System.out.println(l);
float f=Float.parseFloat(str);
System.out.println(f);
}
}
4) toString()
---------------
It is used to convert wrapper object to string type.
ex:
---
class Test
{
public static void main(String[] args)
{
Integer i1=new Integer(10);
String str=i1.toString();
System.out.println(str);//10
}
}
input:
1010
0101
output:
1111
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int c=a+b;
1) System.gc()
2) Runtime.getRuntime().gc()
ex:
---
class Test
{
//instance variable
int i=10;
t=null;
//System.gc();
Runtime.getRuntime().gc();
}
1) Immutable object
2) Mutable object
1) Immutable object
--------------------
After object creation if we perform any changes then for every change a new object will be created such type
of object is called immutable object.
ex:
String and wrapper classes
2) Mutable object
--------------
After object creation if we perform any changes then all changes will be reflected to same object such type of
object is called mutable object.
ex:
StringBuffer and StringBuilder
String
========
It is a collection of characters which is enclosed in a double quotation.
case1:
------
Once if we create a String object we can't perform any changes.If we perform any changes then
for every change a new object will be created such type of behaviour is called immutability of an object.
Diagram: java30.1
case2:
-----
What is the difference between == and .equals() method?
==
----
It is used for reference comparision or address comparision.
ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1==s2);//false
}
.equals()
-------
It is used for content comparision and it is case sensitive.
case3:
------
Once if we create a String object. Two objects will be created one is on heap and another is on SCP(String
Constant Pool) area. But 's' always points to heap area.
Diagram: java30.2
Object creation in SCP arae is always optional.First JVM will check is there any object is created with same
content or not. If it is created then JVM simply refers to that object. If it is not created then JVM will create a
new object.Hence there is no chance of having duplicate objects in SCP area.
SCP objects do not have any object reference even though garbage collector can't access them.
Diagram: java30.3
Diagram: java30.4
String important methods
========================
input:
hello
output:
5
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";
System.out.println(str.length());
}
input:
HELLO
output:
hello
ex:
class Test
{
public static void main(String[] args)
{
String str="HELLO";
System.out.println(str.toLowerCase());
}
input:
hello
output:
HELLO
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";
System.out.println(str.toUpperCase());
}
input:
str = bhaskar
index = 3
output:
s
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
int index=3;
System.out.println(str.charAt(index));
}
input:
str = bhaskar
ch = 'a'
output:
2
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
System.out.println(str.indexOf(ch));
}
}
Q) Write a java program to display the last index of a given character?
input:
str = bhaskar
ch = 'a'
output:
5
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
System.out.println(str.lastIndexOf(ch));
}
input:
ihub
talent
output:
ihubtalent
ex:
---
class Test
{
public static void main(String[] args)
{
String str1="ihub";
String str2="talent";
System.out.println(str1.concat(str2));
}
input:
bhaskar
bhaskar
output:
Both are same
ex:
class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="bhaskar";
if(str1.equals(str2))
System.out.println("Both are same");
else
System.out.println("Both are not same");
}
output:
Both are same
ex:
class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="BHASKAR";
if(str1.equalsIgnoreCase(str2))
System.out.println("Both are same");
else
System.out.println("Both are not same");
}
input:
str= bhaskar
ch ='A'
output:
bhAskAr
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
System.out.println(str.replace('a','A'));
}
Input:
I_hub@Ta$len#t29
output:
IhubTalent29
ex:
---
class Test
{
public static void main(String[] args)
{
String str="I_hub@Ta$len#t29";
str=str.replaceAll("[^A-Za-z0-9]","");
System.out.println(str);
}
output:
IhubTalent
ex:
class Test
{
public static void main(String[] args)
{
String str="I hub Tal ent";
str=str.replaceAll("\\s","");
System.out.println(str);
}
input:
ihub23
talent17
output:
ihubtalent40
ex:
class Test
{
public static void main(String[] args)
{
String str1="ihub23";
String str2="talent17";
String word1=str1.replaceAll("[^A-Za-z]","");
int num1=Integer.parseInt(str1.replaceAll("[^0-9]",""));
String word2=str2.replaceAll("[^A-Za-z]","");
int num2=Integer.parseInt(str2.replaceAll("[^0-9]",""));
String word=word1+word2;
int num=num1+num2;
System.out.println(word+num);
}
Input:
ihubtalent
output:
talent
ex:
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
System.out.println(str.substring(4));
}
}
Input:
ihubtalent
output:
tale
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
System.out.println(str.substring(4,8));
}
input:
str = ihubtalent
count = 2
output:
ubtalentih
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
int count=2;
String word1=str.substring(count,str.length());
String word2=str.substring(0,count);
str=word1+word2;
System.out.println(str);
}
input:
str = IhubTalent
index= 4
word = For
output:
IhubForTalent
ex:
class Test
{
public static void main(String[] args)
{
String str ="IhubTalent";
int index= 4;
String word ="For";
String word1=str.substring(0,index);
String word2=str.substring(index,str.length());
str = word1+word+word2;
System.out.println(str);
input:
str = This is java class
delete = is
output:
Th java class
ex:
class Test
{
public static void main(String[] args)
{
String str="This is java class";
String delete="is";
str=str.replaceAll(delete,"");
System.out.println(str);
}
}
input:
hello
output:
olleh
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";
char[] carr=str.toCharArray(); // h e l l o
String rev="";
//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
System.out.println(rev);
}
}
output:
It is a palindrome string
ex:
---
class Test
{
public static void main(String[] args)
{
String str="racar";
char[] carr=str.toCharArray(); // r a c a r
String rev="";
//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
if(str.equals(rev))
System.out.println("It is a palindrome string");
else
System.out.println("It is not a palindrome string");
}
}
input:
This is java class
output:
class java is This
class Test
{
public static void main(String[] args)
{
String str="This is java class";
String rev="";
for(int i=sarr.length-1;i>=0;i--)
{
rev+=sarr[i]+" ";
}
System.out.println(rev);
}
}
input:
This is java class
output:
sihT si avaj ssalc
ex:
class Test
{
public static void main(String[] args)
{
String str="This is java class";
//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
System.out.print(carr[i]);
}
//space
System.out.print(" ");
}
}
}
Q) Write a java program to display the string starting with uppercase letters?
input:
This is Java language For students
output:
This Java For
ex:
---
class Test
{
public static void main(String[] args)
{
String str="This is Java language For students";
}
}
input:
Umbrella
output:
uea
ex:
class Test
{
public static void main(String[] args)
{
String str="Umbrella";
str=str.toLowerCase();
}
}
Input:
A1B2C3D4
output:
ABBCCCDDDD
class Test
{
public static void main(String[] args)
{
String str="A1B2C3D4";
for(int i=0;i<str.length();i++)
{
if(Character.isAlphabetic(str.charAt(i)))
{
System.out.print(str.charAt(i));
}
else
{
int n=Character.getNumericValue(str.charAt(i));
for(int k=1;k<n;k++)
{
System.out.print(str.charAt(i-1));
}
}
}
}
}
input:
str1 = silent
str2 = listen
output:
It is a anagram string
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
String str1 ="silent";
String str2 ="listen";
char[] carr1=str1.toCharArray();
char[] carr2=str2.toCharArray();
Arrays.sort(carr1); // e i l n s t
Arrays.sort(carr2); // e i l n s t
boolean flag=true;
for(int i=0;i<carr1.length && i<carr2.length;i++)
{
if(carr1[i]!=carr2[i])
{
flag=false;
break;
}
}
if(flag==true)
System.out.println("It is a anagram string");
else
System.out.println("It is not a anagram string");
}
}
input:
XYZ
output
XY
XZ
YX
YZ
ZX
ZY
class Test
{
public static void main(String[] args)
{
String str="XYZ";
char[] carr=str.toCharArray();
for(int i=0;i<carr.length;i++)
{
for(int j=0;j<carr.length;j++)
{
if(carr[i]!=carr[j])
{
System.out.println(carr[i]+""+carr[j]);
}
}
}
}
}
Q) Write a java program to display duplicate and unique characters from given string?
input:
google
output:
Duplicate characters : o g
Unique characters : g o l e
ex:
class Test
{
public static void main(String[] args)
{
String str="google";
String duplicates="";
String uniques="";
for(int i=0;i<str.length();i++)
{
String s=Character.toString(str.charAt(i));
if(!uniques.contains(s))
{
uniques+=s;
continue;
}
duplicates+=s;
}
input:
this is java class
output:
This Is Java Class
ex:
class Test
{
public static void main(String[] args)
{
String str="this is java class";
String result="";
for(int i=0;i<carr.length;i++)
{
if(i==0)
{
result+=(char)(carr[i]-32);
}
else
{
result+=carr[i];
}
}
//space
result+=" ";
}
System.out.print(result);
}
}
Q) Write a java program to find out most repeating character in a given string?
Input:
ihubtalentinstitute
output:
t is repeating for 5 times
ex:
class Test
{
public static void main(String[] args)
{
String str="ihubtalentinstitute";
for(int i=0;i<str.length();i++)
{
int cnt=0;
for(int j=0;j<str.length();j++)
{
if(str.charAt(i)==str.charAt(j))
{
cnt++;
}
}
if(maxCount<cnt)
{
maxCount=cnt;
character=str.charAt(i);
}
}
System.out.println(character+" is repeating for "+maxCount+" times");
}
}
Q) Write a java program to display permutation of a given string?
input:
ABC
output:
ABC
ACB
BAC
BCA
CBA
CAB
ex:
class Test
{
public static void main(String[] args)
{
String str="ABC";
//caller method
permutation(str.toCharArray(),0);
}
//callie method
public static void permutation(char[] arr,int fi)
{
if(fi==arr.length-1)
{
System.out.println(arr);
return;
}
for(int i=fi;i<arr.length;i++)
{
swapping(arr,fi,i);
permutation(arr,fi+1);
swapping(arr,fi,i);
}
}
//callie method
public static void swapping(char[] arr,int fi,int i)
{
char temp=arr[fi];
arr[fi]=arr[i];
arr[i]=temp;
}
}
StringBuffer
==============
If our content change frequently then it is not recommanded to use String because for every change a new
object will be created.
In SringBuffer all the required changes will be done in a single object only.
constructors
-------------
1) StringBuffer sb=new StringBuffer()
-------------------------------------
It will create empty StringBuffer object with default initial capacity of 16.
If we reach maximum capacity then new capacity will be created with below formulea.
ex:
new capacity = current_capacity + 1 * 2;
ex:
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //16
sb.append("abcdefghijklmnop");
System.out.println(sb.capacity());//16
sb.append("qr");
System.out.println(sb.capacity()); //16+1*2=34
}
ex:
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer(19);
System.out.println(sb.capacity()); //19
}
3) StringBuffer sb=new StringBuffer(String s)
------------------------------------------------------
It will create StringBuffer object equivalent to String.
ex:
capacity = s.length() + 16;
ex:
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("bhaskar");
System.out.println(sb.capacity()); //7+16=23
input:
hello
output:
olleh
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";
String rev=sb.reverse().toString();
System.out.println(rev);
}
input:
racar
output:
IT is a palindrome string
ex:
class Test
{
public static void main(String[] args)
{
String str="racar";
String rev=sb.reverse().toString();
if(str.equals(rev))
System.out.println("It is a palindrome string");
else
System.out.println("It is not a palindrome string");
}
input:
22
output:
6 (2,12,20,21,22)
ex:
---
class Test
{
public static void main(String[] args)
{
int num=22;
for(int i=1;i<=num;i++)
{
sb.append(i);
}
int cnt=0;
for(int i=0;i<sb.length();i++)
{
int n=Integer.parseInt(Character.toString(sb.charAt(i)));
if(n==2)
{
cnt++;
}
}
System.out.println(cnt);
}
}
Q) Write a java program to multiply two arrays?
input:
412
25
output:
10300 (412*25)
ex:
class Test
{
public static void main(String[] args)
{
int[] arr1={4,1,2};
int[] arr2={2,5};
//caller method
int a=Integer.parseInt(arrayToString(arr1));
int b=Integer.parseInt(arrayToString(arr2));
System.out.println(a*b);
}
//callie method
public static String arrayToString(int[] arr)
{
StringBuffer sb=new StringBuffer();
for(int i:arr)
{
sb.append(i);
}
return sb.toString();
}
}
input:
ABBCCCDDDD
output:
A1B2C3D4
ex:
class Test
{
public static void main(String[] args)
{
String str="ABBCCCDDDD";
int count=1;
for(int i=0;i<str.length();i++)
{
if(i<str.length()-1 && str.charAt(i) == str.charAt(i+1))
{
count++;
}
else
{
sb.append(str.charAt(i));
sb.append(count);
count=1;
}
}
System.out.println(sb.toString());
}
}
input:
1106
output:
AAJF
ex:
class Test
{
public static void main(String[] args)
{
String str="1106";
for(int i=0;i<str.length();i++)
{
int n=Integer.parseInt(Character.toString(str.charAt(i)));
if(n>0)
{
sb.append((char)('A'+ n-1));
}
else
{
int k=Integer.parseInt(str.substring(i-1,i+1));
sb.append((char)('A' + k-1));
}
}
System.out.println(sb.toString());
}
}
Q) Write a java program to display longest common sub sequence in a given string?
input:
ABCAB
AECB
output:
3
ex:
class Test
{
public static void main(String[] args)
{
String str1="ABCAB";
String str2="AECB";
//caller method
System.out.println(longestCommonSubsequence(str1,str2));
}
//callie method
public static int longestCommonSubsequence(String str1,String str2)
{
return solve(str1,str2,0,0);
}
//callie method
public static int solve(String str1,String str2,int i,int j)
{
if(i==str1.length())
return 0;
if(j==str2.length())
return 0;
int ans=0;
if(str1.charAt(i) == str2.charAt(j))
{
ans=1+solve(str1,str2,i+1,j+1);
}
else
{
ans=Math.max(solve(str1,str2,i+1,j),solve(str1,str2,i,j+1));
}
return ans;
}
Assignment
=========
Write a java program to decode the string?
input:
AAJF
output:
1106
char ch=str.charAt('A')
ch – 64
StringBuilder
=============
StringBuilder is exactly same as StringBuffer with following differences.
StringBuffer StringBuilder
----------------- ---------------
Methods which are present in StringBuffer No method present in StringBuilder is synchronized.
are synchronized.
At a time only one thread is allowed to operate Multiple threads are allowed to operator on
on StringBuffer object.StringBuffer is thread StringBuilder object.StringBuilder is not thread
safe. safe.
Waiting time of a thread will increase There is no waiting time relatively performance
relatively performance is low. is high.
StringTokenizer
===============
StringTokenizer is a class which is present in java.util package.
ex:
StringTokenizer st=new StringTokenizer(String str,RegExp reg);
ex:
public boolean hasMoreTokens()
public String nextToken()
public boolean hasMoreElements()
public Objct nextElement()
public int countTokens()
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class");
System.out.println(st.countTokens());
}
}
Note:
----
Here default regular expression is space.
ex:2
----
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class"," ");
while(st.hasMoreTokens())
{
String s=st.nextToken();
System.out.println(s);
}
}
}
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class"," ");
while(st.hasMoreElements())
{
String s=(String)st.nextElement();
System.out.println(s);
}
}
}
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("9,99,999",",");
while(st.hasMoreElements())
{
String s=(String)st.nextElement();
System.out.println(s);
}
}
}
Note:
----
If our content change frequently then it is never recommanded to use String.
If our content change frequently where thread safety is required then we need to use StringBuffer.
If our content change frequently where thread safety is not required then we need to use StringBuilder.
Exception Handling
===================
Exception
---------
Exception is a problem for which we can provide solution programmatically.
ex:
ArithmeticException
FileNotFoundException
IllegalArgumentException
Error
-----
Error is a problem for which we can't provide solution programmatically.
ex:
OutOfMemoryError
LinkageError
StackOverFlowError
2) Abnormal termination
1) Smooth termination
------------------------
During the program execution suppose if we are not getting any intteruption in the middle of the program such
type of termination is called smooth termination.
ex:
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
2) Abnormal termination
------------------------
During the program execution suppose if we are getting some intteruption in the middle of the program such
type of termination is called abnormal termination.
ex:
class Test
{
public static void main(String[] args)
{
System.out.println(10/0);
}
}
If any exception raised in our program we must and should handle that exception otherwise our program will
terminates abnormally.
Here exception will display name of the exception,description of the exception and line number of the
exception.
Exception
==========
It is a unwanted, unexpected event which disturbs normal flow of our program.
Exceptions always raised at runtime so they are also known as runtime events.
1) predefined exceptions
2) Userdefined exceptions
1) predefined exceptions
-------------------------
Built-In exceptions are called predefined exceptions.
i) Checked exceptions
-------------------
Exceptions which are checked by the compiler at the time of compilation is called checked exceptions.
ex:
InterruptedException
EOFException
FileNotFoundException
and etc.
ii) Unchecked exceptions
------------------------
Exceptions which are checked by the JVM at runtime is called unchecked exceptions.
ex:
ArithmeticException
ClassCastException
IllegalArgumentException
and etc.
Diagram: java34.1
If any checked exception raised in our program , we must and should handle exception by using try and catch
block.
try block
=========
It is a block which contains risky code.
catch block
==========
It is a block which contains error handling code.
A catch block is used to catch the exception which is thrown by try block.
A catch block will exception name as a parameter and that name must match with exception class name.
syntax:
------
try
{
-
- //risky code
-
}
catch(ArithmeticException ae)
{
-
- //error handling code
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
catch (Exception e)
{
System.out.println("catch-block");
}
}
}
o/p:
try-block
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("catch-block");
}
}
}
o/p:
catch-block
ex:
-----
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("stmt1");
System.out.println(10/0);
System.out.println("stmt2");
}
catch (ArithmeticException ae)
{
System.out.println("catch-block");
}
}
}
o/p:
stmt1
catch-block
ex:
class Test
{
public static void main(String[] args)
{
int i=1;
try
{
i++;
}
catch (Exception e)
{
i++;
}
System.out.println(i);//2
}
}
If a try block contains multiple catch blocks then order of catch blocks is very important .It should be from child
to parent but not from parent to child.
ex:
--
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("From AE");
}
catch(RuntimeException re)
{
System.out.println("From RE");
}
catch(Exception e)
{
System.out.println("From E ");
}
}
}
1) printStackTrace()
--------------------
It will display name of the excepiton ,description of the exception and line number of
the exception.
2) toString()
-----------
It will display name of the exception and description of the exception.
3) geMessage()
-------------
It will display description of the exception.
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
ae.printStackTrace();
System.out.println("==================");
System.out.println(ae.toString());
System.out.println("==================");
System.out.println(ae.getMessage());
}
}
}
finally block
==============
It is never recommanded to maintain cleanup code in try block because if any exception raise in try block then
try block won't be executed.
It is never recommanded to maintain cleanup code in catch bock because if there is no exception in try block
then catch won't be executed.
But we need a place where we can maintain cleanup code and it should execute irrespective of exception
raised or not.Such block is called finally block.
syntax:
------
try
{
-
- //Risky Code
-
}
catch(Exception e )
{
-
- //Error Handling Code
-
}
finally
{
-
- //cleanup code
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
o/p:
try-block
finally-block
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
o/p:
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:7)
finally-block
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
System.out.println(10/0);
System.out.println("stmt");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
o/p:
try-block
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:8)
finally-block
}
}
final
-----
A final is a modifier which is applicable for variables, methods and classes.
If we declare any variable as final then reassignment of that variable is not possible.
If we declare any method as final then overriding of that method is not possible.
If we declare any class as final then creating child class is not possible.
finally
-------
It is a block which contains cleanup code and it will execute irrespective of exception raise or not.
finalize
--------
It is a method called by garbage collector just before destroying an object for cleanup activity.
throw statement
===============
Sometime we will create exception object explicitly and handover to JVM manually by using throw statement.
ex:
throw new ArithmeticException("Don't divide by zero");
ex:
class Test
{
public static void main(String[] args)
{
throw new ArithmeticException("Don't divide by zero");
}
}
throws statement
===============
If any checked exception raised in our program we must and should handle that exception by using try and
catch block or by using throws statement.
ex:
class Test
{
public static void main(String[] args)
{
try
{
Thread.sleep(3000);
System.out.println("Welcome to Java ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ex:
---
class Test
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(5000);
System.out.println("Welcome to Java ");
}
}
2) Userdefined exception
=======================
Exception which are created by the user based on the application requirements are called userdefined
exceptions or customized exceptions.
ex:
NoPracticeException
NoInterestInJavaException
NoMoneyToEnjoyException
TooYoungException
TooOldException
ex:
import java.util.Scanner;
class TooYoungException extends RuntimeException
{
TooYoungException(String message)
{
super(message);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String message)
{
super(message);
}
}
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age :");
int age=sc.nextInt();
if(age<18)
throw new TooYoungException("U r not eligible to vote");
else
throw new TooOldException("U r eligible to vote");
}
}
java.io package
================
File
=======
File f=new File("abc.txt");
File will check is there any abc.txt file already created or not.
If it is available it simply refers to that file.If it is not created then
it won't create any new file.
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f=new File("abc.txt");
System.out.println(f.exists()); // false
f.createNewFile();
System.out.println(f.exists()); // true
}
}
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f=new File("bhaskar123");
System.out.println(f.exists());//false
f.mkdir();
System.out.println(f.exists());//true
}
}
Create a "cricket123" folder and inside that folder create "abc.txt" file.
ex:
--
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f1=new File("cricket123");
f1.mkdir();
FileWriter
==========
FileWriter is used to write character oriented data into a file.
constructor
--------------
FileWriter fw=new FileWriter(String s);
FileWriter fw=new FileWriter(File f);
ex:
FileWriter fw=new FileWriter("aaa.txt");
or
If file does not exist then FileWriter will create a physical file.
Methods
-----------
1)write(int ch)
-----------------
It will insert single character into a file.
2)write(char[] ch)
-----------------
It will insert array of characters into a file.
3)write(String s)
-------------------
It will insert String into a file.
4)flush()
----------
It gives guaranttee that last character of a file is also inserted.
5)close()
-----------
It is used to close the FileWriter object.
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileWriter fw=new FileWriter("aaa.txt");
fw.write(98); //b
fw.write("\n");
char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");
fw.write("bhaskar\nsolution");
fw.flush();
fw.close();
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)
{
try
{
FileWriter fw=new FileWriter("aaa.txt");
fw.write(98); //b
fw.write("\n");
char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");
fw.write("bhaskar\nsolution");
fw.flush();
fw.close();
System.out.println("Please check the location");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
A try -with-resource ensures that each resource is closed at the end of the statement.
syntax:
------
try(resources)
{
}
catch(Exception e)
{
}
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)
{
FileReader
==================
It is used to read character oriented data from a file.
constructor
--------------
FileReader fr=new FileReader(String s);
FileReader fr=new FileReader(File f);
ex:
FileReader fr=new FileReader("aaa.txt");
or
File f=new File("aaa.txt");
FileReader fr=new FileReader(f);
Methods
----------
1)read()
--------
It will read next character from a file and return unicode value.
If next character is not available then it will return -1.
2)read(char[] ch)
----------------
It will read collection of characters from a file.
3)close()
---------
It is used to close FileReader object.
ex:
----
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");
int i=fr.read();
while(i!=-1)
{
System.out.print((char)i);
i=fr.read();
}
fr.close();
}
}
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");
char[] ch=new char[250];
fr.read(ch);
fr.close();
}
}
While reading the data by using FileReader object we need to read character by character which is not
convenient to the programmer.
To overcome this limitation Sun Micro System introduced BufferedWriter and BufferedReader.
BufferedWriter
=================
It is used to insert character oriented data into a file.
constructor
-----------
BufferedWriter bw=new BufferedWriter(Writer w);
BufferedWriter bw=new BufferedWriter(Writer w,int buffersize);
or
Methods
---------
1)write(int ch)
-----------------
It will insert single character into a file.
2)write(char[] ch)
-----------------
It will insert array of characters into a file.
3)write(String s)
-------------------
It will insert String into a file.
4)flush()
----------
It gives guaranttee that last character of a file is also inserted.
5)close()
-----------
It is used to close the BufferedWriter object.
6)newLine()
----------
It will insert new line into a file.
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("bbb.txt"));
bw.write(98);//b
bw.newLine();
char[] ch={'a','b','c'};
bw.write(ch);
bw.newLine();
bw.write("bhaskar");
bw.flush();
bw.close();
System.out.println("Please check the location");
}
}
BufferedReader
=================
It is enhanced reader to read character oriented data from a file.
constructor
------------
BufferedReader br=new BufferedReader(Reader r);
BufferedReader br=new BufferedReader(Reader r,int buffersize);
ex:
FileReader fr=new FileReader("bbb.txt");
BufferedReader br=new BufferedReader(fr);
or
methods
---------
1)read()
--------
It will read next character from a file and return unicode value.
If next character is not available then it will return -1.
2)read(char[] ch)
----------------
It will read collection of characters from a file.
3)close()
---------
It is used to close BufferedReader object.
4)nextLine()
------------
It is used to read next line from the file.If next line is
not available then it will return null.
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("bbb.txt"));
while(line!=null)
{
System.out.println(line);
line= br.readLine();
}
br.close();
}
}
PrintWriter
===============
It is enhanced write to write character oriented data into a file.
constructor
-----------
PrintWriter pw=new PrintWriter(String s);
PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(Writer w);
PrintWriter can communicate with files directly and it will take the support of some writer objects.
ex:
PrintWriter pw=new PrintWriter("ccc.txt");
or
The main advantage of PrintWriter over FileWriter and BufferedWriter is we can insert any type of data.
methods
------------
write(int ch)
write(char[] ch)
write(String s)
flush()
close()
writeln(int i)
writeln(float f)
writeln(double d)
writeln(String s)
writeln(char c)
writeln(boolean b)
write(int i)
write(float f)
write(double d)
write(String s)
write(char c)
write(boolean b)
ex:
----
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
PrintWriter pw=new PrintWriter("ccc.txt");
pw.write(98); // b
pw.println(98);//98
pw.println(true);//true
pw.println(10.5d);//10.5
pw.println("Hello");//Hellow
pw.println('a');// a
pw.flush();
pw.close();
2) BufferedReader class
3) Console class
4) Scanner class
ex:
---
class Test
{
public static void main(String[] args)
{
String name=args[0];
System.out.println("Welcome :"+name);
}
}
o/p:
javac Test.java
2) BufferedReader class
-----------------------
BufferedReader is a class which is present in java.io package.
String name=br.readLine();
System.out.println("Welcome :"+name);
}
}
3) Console class
----------------
Console is a class which is present in java.io package.
ex:
Console c=System.console();
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
Console c=System.console();
System.out.println("Enter the Name :");
String name=c.readLine();
System.out.println("Welcome :"+name);
}
}
4) Scanner class
------------------
Scanner is a class which is present in java.util package.
ex:
Scanner sc=new Scanner(System.in);
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
sc.nextLine();
Generics
=========
Arrays are typesafe.It means we can give guaranetee that what type of elements are present in array.
If requirement is there to store string values then it is recommanded to use String array.
ex:
String[] sarr=new String[10];
sarr[0]="hi";
sarr[1]="hello";
sarr[2]="bye";
sarr[3]=10; //invalid
At the time of retrieving the data from array we don't need to perform typecasting.
ex:
String[] sarr=new String[10];
sarr[0]="hi";
sarr[1]="hello";
sarr[2]="bye";
-
-
String value1=sarr[0];
Collections are not typesafe.It means we can't give guarantee that what type of elements are present in
Collections.
If requirement is there to store String values then it is not recommanded to use ArrayList because we won't get
any compile time error or runtime error but sometimes our program get failure.
ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("hello");
al.add("bye");
al.add(10);
At the time of retrieving the data from Collections compulsary we need to perform typecasting.
ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("hello");
al.add("bye");
al.add(10);
-
-
String value1=(String)al.get(0);
To overcome this above limitations Sun Micro System introduced Generics concept in 1.5v.
java.util package
=================
Arrays Collections
-------------- ---------------
It is a collection of homogeneous data It is a collection of homogeneous and
elements. hetrogeneous data elements.
It is fixed in size. It is growable in nature.
Performance point of view arrays are Memory point of view Collections are
recommanded to use. recommanded to use.
It can hold primitive types and object types. It holds only object types.
Arrays not implemented based on data structure Collections are implemented based on data structure
concept so we can't expect any readymade concept so we can expect readymade methods.
methods.
Collection Framework
====================
Collection Framework defines several utility classes and interfaces to represent group of objects in a single
entity.
Collection
===========
Collection is an interface which is present in java.util package.
If we want to represent group of individual objects in a single entity then we need to use Collection.
Collection interface contains following methods which are available for entire Collection objects.
ex:
cmd> javap java.util.Collection
add()
remove()
removeAll()
addAll()
contains()
containsAll()
retainAll()
clear()
and etc.
List
=====
It is a child interface of Collection interface.
If we want to represent group of individual objects in a single entity where duplicate objects are allowed and
order is preserved then we need to use List interface.
Diagram: java38.1
ArrayList
-------------
The underlying data structure is resizable array or growable array.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al);//[one,two,three]
al.add("one");
System.out.println(al);//[one,two,three,one]
al.add(10);
System.out.println(al); //[one,two,three,one,10]
al.add(null);
System.out.println(al); //[one,two,three,one,10,null]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al);//[one,two,three]
al.add("one");
System.out.println(al);//[one,two,three,one]
al.add(null);
System.out.println(al); //[one,two,three,one,null]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al.isEmpty()); // false
for(int i=0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al.contains("two")); //true
al.remove("two");
System.out.println(al);//[one,three]
al.clear();
System.out.println(al); //[]
}
}
ex:
====
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<String> list=new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);//[one,two,three]
list.add(0,"gogo");
System.out.println(list);//[gogo,one,two,three]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<String> list=Arrays.asList("one","two","three","four");
System.out.println(list);
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(4,2,7,1);
System.out.println(list);
}
}
LinkedList
============
The underlying data structure is doubly LinkedList.
If our frequent operation is adding and removing the elements in middle then LinkedList is a best choice.
ex:
public E getFirst();
public E getLast();
public E removeFirst();
public E removeLast();
public void addFirst(E);
public void addLast(E);
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("one");
ll.add("two");
ll.add("three");
System.out.println(ll);//[one,two,three]
ll.add("one");
System.out.println(ll);//[one,two,three,one]
ll.add(10);
System.out.println(ll);//[one,two,three,one,10]
ll.add(null);
System.out.println(ll);//[one,two,three,one,10,null]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("one");
ll.add("two");
ll.add("three");
System.out.println(ll);//[one,two,three]
ll.addFirst("gogo");
ll.addLast("jojo");
System.out.println(ll);//[gogo,one,two,three,jojo]
System.out.println(ll.getFirst());//gogo
System.out.println(ll.getLast());//jojo
ll.removeFirst();
ll.removeLast();
System.out.println(ll);//[one,two,three]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList<String> ll1=new LinkedList<String>();
ll1.add("one");
ll1.add("two");
ll1.add("three");
System.out.println(ll1);//[one,two,three]
System.out.println(ll2.containsAll(ll1)); //true
ll2.removeAll(ll1);
System.out.println(ll2); // [raja]
}
}
import java.util.*;
class Student
{
private int studId;
private String studName;
//constructor
Student(int studId,String studName)
{
this.studId=studId;
this.studName=studName;
}
//getter methods
public int getStudId()
{
return studId;
}
public String getStudName()
{
return studName;
}
System.out.println(al);
}
}
Vector
=======
The underlying data structure is resizable array or growable array.
ex:
----
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();
System.out.println(v.capacity());//10
for(int i=1;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v); //[1,2,3,4,5,6,7,8,9,10]
System.out.println(v.firstElement());//1
System.out.println(v.lastElement());//10
v.removeElement(5);
System.out.println(v);//[1,2,3,4,6,7,8,9,10]
v.removeAllElements();
System.out.println(v); //[]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();
System.out.println(v.capacity());//10
for(int i=1;i<=10;i++)
{
v.add(i);
}
System.out.println(v); //[1,2,3,4,5,6,7,8,9,10]
System.out.println(v.get(0));//1
System.out.println(v.get(v.size()-1));//10
v.remove(4);
System.out.println(v);//[1,2,3,4,6,7,8,9,10]
v.clear();
System.out.println(v); //[]
}
}
ArrayList Vector
------------ -----------
It is a non-legacy class. It is a legacy class.
ArrayList LinkedList
------------ -----------
The underlying data structure is resizable The underlying data structure is doubly
array or growable array. linked list.
ArrayList is better for storing and accessing LinkedList is better for manipulating data.
data.
The memory location for the elements of The location for the elements of a linked list
an ArrayList is contiguous. is not contagious.
Stack
=====
Stack is a child class of Vector class.
If we depend upon Last In First Out (LIFO) order then we need to use Stack.
constructor
---------
Stack s=new Stack();
methods
--------
push(Object o)
-------------
It is used to push the element in stack.
pop()
-----
It is used to pop the element from stack.
peek()
-------
It will return toppest element of a stack.
isEmpty()
--------
It is used to check stack is empty or not.
search(Object o)
----------------
It will return offset value if element found otherwise it will return -1.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Stack<String> s=new Stack<String>();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s); //[A,B,C]
s.pop();
System.out.println(s);//[A,B]
System.out.println(s.peek()); // B
System.out.println(s.isEmpty()); // false
System.out.println(s.search("K")); // -1
System.out.println(s.search("A")); // 2
}
}
Set
====
It is a child interface of Collection interface.
If we want to represent group of individual objects in a single entity where duplicate objects
are not allowed and order is not preserved then we need to use Set interface.
Diagram: java39.1
HashSet
========
The underlying data structure is Hashtable.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("three");
hs.add("one");
hs.add("two");
System.out.println(hs); //[one, three, two]
hs.add("one");
System.out.println(hs);//[one, three, two]
hs.add(10);
System.out.println(hs);//[one, 10, three, two]
hs.add(null);
System.out.println(hs); // [null, one, 10, three, two]
}
}
LinkedHashSet
==============
It is a child class of HashSet class.
ex:
HashSet LinkedHashSet
------------ -------------
The underlying data structure is The underlying data structure is Hashtable
Hashtable. and LinkedList.
ex:
----
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedHashSet lhs=new LinkedHashSet();
lhs.add("three");
lhs.add("one");
lhs.add("two");
System.out.println(lhs); //[three, one, two]
lhs.add("one");
System.out.println(lhs);//[three, one, two]
lhs.add(10);
System.out.println(lhs);//[three, one, two, 10]
lhs.add(null);
System.out.println(lhs); // [three, one, two, 10, null]
}
}
input:
1223334444
output:
1234
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
int[] arr={1,2,2,3,3,3,4,4,4,4};
TreeSet
========
The underlying data structure is Balanced Tree.
Hetregeneous objects are not allowed. If we insert hetrogeneous objects then we will get
ClassCastException.
Null insertion is not possible. If we insert null then we will get NullPointerException.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add(5);
ts.add(1);
ts.add(10);
ts.add(7);
System.out.println(ts);//[1,5,7,l0]
ts.add(1);
System.out.println(ts);//[1,5,7,10]
//ts.add("hi");
//System.out.println(ts);// R.E ClassCastException
//ts.add(null);
//System.out.println(ts); // R.E NullPointerException
}
}
import java.util.*;
public class Test
{
public static void main(String[] args) {
// Create a new ArrayList
List<String> arrayList = new ArrayList<>();
Input:
Ball Dog Apple Cat Elephant
output:
Apple Ball Cat Dog Elephant
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="Ball Dog Apple Cat Elephant";
for(String s:sarr)
{
list.add(s);
}
Collections.sort(list);
Comparable
----------
Comparable is an interface which is present in java.lang package.
If we depends upon default natural sorting order then we need to use Comparable interface.
ex:
obj1.compareTo(obj2)
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("A".compareTo("Z")); // -25
System.out.println("Z".compareTo("A")); // 25
System.out.println("K".compareTo("K")); // 0
}
}
Comparator
----------
Comparator is an interface which is present in java.util package.
Comparator interface contains two methods i.e compare() and equals() method.
If we depends upon customized sorting order then we need to use Comparator interface.
ex:
public int compare(Object obj1,Object obj2)
Implementation of equals() method is optional because it is available to the class by the Object
class through inheritance.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>(new MyComparator());
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(7);
System.out.println(ts);//[10,7,5,1]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return 1;
else if(i1>i2)
return -1;
else
return 0;
}
}
ex:
----
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>(new MyComparator());
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(7);
System.out.println(ts);//[1,5,7,10]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return -1;
else if(i1>i2)
return 1;
else
return 0;
}
}
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date1=LocalDate.of(2023,07,31);
LocalDate date2=LocalDate.now();
if(date1.compareTo(date2)>0)
System.out.println("date1 is greatest");
else if(date1.compareTo(date2)<0)
System.out.println("date2 is greatest");
else
System.out.println("Both are same");
}
}
ex:
---
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date1=LocalDate.now();
LocalDate date2=LocalDate.of(2023,07,31);
if(date1.compareTo(date2)>0)
System.out.println("date1 is greatest");
else if(date1.compareTo(date2)<0)
System.out.println("date2 is greatest");
else
System.out.println("Both are same");
}
}
Map
====
It is not a child interface of Collection interface.
If we want to represent group of individual objects in key and value pair then we need to use
Map interface.
Diagram: java40.1
HashMap
=========
The underlying data structure is Hashtable.
Insertion order is not preserved because it will take hash code of a key.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");
System.out.println(hm);//{1=one, 3=three, 7=seven, 10=ten}
hm.put(1,"gogo");
System.out.println(hm);//{1=gogo, 3=three, 7=seven, 10=ten}
hm.put("nine",9);
System.out.println(hm); //{1=gogo, nine=9, 3=three, 7=seven, 10=ten}
hm.put(null,null);
System.out.println(hm);//{null=null, 1=gogo, nine=9, 3=three, 7=seven, 10=ten}
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");
System.out.println(hm);//{1=one, 3=three, 7=seven, 10=ten}
hm.put(1,"gogo");
System.out.println(hm);//{1=gogo, 3=three, 7=seven, 10=ten}
hm.put(null,null);
System.out.println(hm);//{null=null, 1=gogo, 3=three, 7=seven, 10=ten}
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");
Set s=hm.keySet();
System.out.println(s); //[1, 3, 7, 10]
Collection c=hm.values();
System.out.println(c); // [one, three, seven, ten]
Set s1=hm.entrySet();
System.out.println(s1); //[1=one, 3=three, 7=seven, 10=ten]
}
}
LinkedHashMap
==============
It is a child class of HashMap class.
LinkedHashMap is exactly same as HashMap class with following differences.
HashMap LinkedHashMap
--------------- ---------------
The underlying data structure is Hashtable. The underlying data structure is Hashtable and
LinkedList.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedHashMap<Integer,String> lhm=new LinkedHashMap<Integer,String>();
lhm.put(1,"one");
lhm.put(7,"seven");
lhm.put(10,"ten");
lhm.put(3,"three");
lhm.put(1,"gogo");
System.out.println(lhm); //{1=gogo, 7=seven, 10=ten, 3=three}
lhm.put(null,null);
System.out.println(lhm); //{1=gogo, 7=seven, 10=ten, 3=three, null=null}
}
}
TreeMap
=========
The underlying data structure is RED BLACK TREE.
Insertion order is not preserved because it will take sorting order of a key.
If we depend upon default natural sorting order then keys must be homogeneous and Comparable.
If we depend upon customized natural sorting order then keys must be hetrogeneous and Non Comparable.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(6,"six");
tm.put(1,"one");
tm.put(5,"five");
tm.put(10,"ten");
System.out.println(tm);//{1=one, 5=five, 6=six, 10=ten}
tm.put(1,"gogo");
System.out.println(tm);//{1=gogo, 5=five, 6=six, 10=ten}
tm.put(7,null);
System.out.println(tm);// {1=gogo, 5=five, 6=six, 7=null, 10=ten}
Insertion order is not preserved because it will take descending order of the key.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(6,"six");
ht.put(1,"one");
ht.put(5,"five");
ht.put(10,"ten");
System.out.println(ht);//{10=ten, 6=six, 5=five, 1=one}
ht.put(1,"gogo");
System.out.println(ht);//{10=ten, 6=six, 5=five, 1=gogo}
//ht.put(7,null);
//System.out.println(ht);// R.E NullPointerException
//ht.put(null,"seven");
//System.out.println(ht);// R.E NullPointerException
}
}
Interview Questions
===================
Q) Write a java program to display number of occurance of a given string?
input:
this class class for java java
output:
this=1, class=2 , for=1, java=2
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="this class class for java java";
for(String s:sarr)
{
if(map.get(s)!=null)
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s,1);
}
}
}
}
input:
java
output:
j=1,a=2,v=1
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="java";
char[] carr=str.toCharArray();
for(char ch:carr)
{
if(map.get(ch)!=null)
{
map.put(ch,map.get(ch)+1);
}
else
{
map.put(ch,1);
}
}
}
}
Cursor
=======
Cursor is used to read the objects one by one from Collections.
1) Enumeration
2) Iterator
3) ListIterator
1)Enumeration
==============
Enumeration interface present in java.util package.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=1;i<=10;i++)
{
v.add(i);
}
System.out.println(v);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
System.out.println(i);
}
}
}
Using Enumeration interface we can perform read operation but not delete/remove operation.
2)Iterator
==========
It is used to retrieve the objects one by one from any Collection object.Hence it is known as universal cursor.
Using Iterator interface we can perform read and remove operation.
ex:
Iterator itr=al.iterator();
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
for(int i=1;i<=10;i++)
{
al.add(i);
}
System.out.println(al);//[1,2,3,4,5,6,7,8,9,10]
Iterator itr=al.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
itr.remove();
else
System.out.println(i);
}
}
}
Using Iterator we can perform read and remove operation but not adding
and replacement of new objects.
3)ListIterator
================
It is a child interface of Iterator interface.
Using ListIterator we can read objects in forward direction and backward direction.Hence it is a bi-directional
cursor.
Using ListIterator we can perform read, remove ,adding and replacement of new objects.
ex:
ListIterator litr=al.listIterator();
ex:
public boolean hasNext()
public Object next()
public boolean hasPrevious()
public Object previous()
public void remove();
public void add(Object o);
public void set(Object o);
public void nextIndex();
public void previousIndex();
ex:1
------
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("nag");
al.add("chiru");
al.add("bala");
System.out.println(al);//[venki,nag,chiru,bala]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
System.out.println(s);
}
}
}
ex:2
-------
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("nag");
al.add("chiru");
al.add("bala");
System.out.println(al);//[venki,nag,chiru,bala]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.remove();
}
}
System.out.println(al);//[venki, chiru, bala]
}
}
ex:3
-------
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("nag");
al.add("chiru");
al.add("bala");
System.out.println(al);//[venki,nag,chiru,bala]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.add("Chetu");
}
}
System.out.println(al);//[venki, nag, Chetu, chiru, bala]
}
}
ex:4
-------
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("nag");
al.add("chiru");
al.add("bala");
System.out.println(al);//[venki,nag,chiru,bala]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.set("Chetu");
}
}
System.out.println(al);//[venki, Chetu, chiru, bala]
}
}
Interview question
====================
Q) Write a java program to find out number of characters occurrence in String?
Example
Input:
java
Output:
j=1, a=2, v=1
import java.util.*;
class Test
{
public static void main(String[] args)
{
findDuplicatesCharacters("java");
}
char c=str.charAt(i);
if(lhm.get(c)!=null)
{
lhm.put(c,lhm.get(c)+1);
}
else
{
lhm.put(c,1);
}
}
System.out.println(lhm);
}
}
Multithreading
==============
Q) What is the difference between Thread and Process?
Thread
-------
Thread is a light weight sub process.
We can run multiple threads concurently.
One thread can communicate with another thread.
ex:
class is one thread
block is one thread
constructor is one thread
and etc.
Process
--------
Process is a collection of threads.
We can run multiple process concurently.
One process can't communicate with another process.
ex:
Typing the notes in editor is one process
downloading a file from internet is one process
taking class from zoommeeting is one process.
Q) What is multitasking?
Executing several task simultenously where each task is a same part of a program.
Q) What is multithreading ?
3) To develop animations.
//start a thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
What algorithm, behaviour or mechanism used by thread schedular is depends upon JVM vendor.
ex:
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
//instantiate a thread
MyThread t=new MyThread();
//start a thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
If we invoke t.run() method then no new thread will be created but run() method will execute
just like normal method.
ex:
---
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
//instantiate a thread
MyThread t=new MyThread();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
ex:
Thread class run() method is a empty implementation.Hence we won't get any output from child thread.
ex:
---
class MyThread extends Thread
{
}
class Test
{
public static void main(String[] args)
{
Diagram: java43.1
Once if we create a thread then our thread will be in New or Born state.
Once if we invoke t.start() method then our thread goes to ready/runnable state.
If thread schedular allocates to CPU then our thread enters to running state.
Once the run() method execution is completed then our thread goes to dead state.
ex:
public final void setName()
public final String getName()
ex:
Thread.currentThread().setName("Parent-Thread");
System.out.println(Thread.currentThread().getName()); // Parent-Thread
t.setName("Child-Thread");
System.out.println(t.getName());// Child-Thread
}
}
Thread priority
================
In java, every thread has a priority automatically generated by JVM or explicitly provided by the programmer.
The valid range of thread priority is 1 to 10. Where 1 is a least priority and 10 is a highest priority.
If we take more then 10 priority then we will get IllegalArgumentException.
If multiple threads having same priority then we can't expect any execution order.
ex:
Thread.currentThread().setPriority(9);
System.out.println(Thread.currentThread().getPriority()); // 9
t.setPriority(4);
System.out.println(t.getPriority());// 4
//t.setPriority(11);//R.E IllegalArgumentException
}
}
1) yield()
2) join()
3) sleep()
1) yield()
-----------
It pause current execution thread and gives the chance to other threads having same priority.
If there is no waiting threads then same thread will continue it's execution.
If multiple threads having same priority then we can't expect any execution order.
ex:
public static native void yield()
Diagram: java43.2
ex:
---
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
Thread.currentThread().yield();
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
2) join()
------------
If a thread wants to wait untill the completion of some other thread then we need to join() method.
A join() method throws one checked exception so we must and should handle that exception by using
try and catch block or by using throws statement.
ex:
public final void join()throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms,int ns)throws InterruptedException
Diagram: java43.3
ex:
t.start();
t.join();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
3) sleep()
-----------
If a thread don't want to perform any operation on perticular amount of time then we need to use sleep()
method.
A sleep() method throws one checked exception called InterruptedException so we must and should handle
that exception by using try and catch block or using throws statement.
ex:
public static native void sleep()throws InterruptedException
public static native void sleep(long ms)throws InterruptedException
public static native void sleep(long ms,int ns)throws InterruptedException
Diagram: java43.4
ex:
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
Daemon Thread
=============
Daemon thread is a service provider thread which provides services to user threads.
There are many deamon threads are running internally like Garbage Collector, Finalizer and etc.
ex:
---
1) Data inconsistency
2) Thread interference
ex:
---
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(10);
}
}
class Test
{
public static void main(String[] args)
{
Table obj=new Table();
t1.start();
t2.start();
}
}
Synchronization
===============
Lock Mechanism
synchronized method
synchronized block
static synchronization
Inter-Thread Communication
----------------------------
wait(), notify() and notifyAll() method
DeadLock
---------
Java 8 Features
===============
Functional interface
=====================
Interface which contains only one abstract method is called functional interface.
f1(f2(){})
{}
@FunctionalInterface annotation is used to declare functional interface which is optional.
ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
}
}
ex:
--
@FunctionalInterface
interface A
{
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
A a=new A()
{
public void m1()
{
System.out.println("M1-Method");
}
};
a.m1();
}
}
Lamda Expression
================
Lamda expression introduced in java 1.8v.
ex:
Java method
-----------
public void m1()
{
System.out.println("M1-Method");
}
Lamda expression
-----------------
()->
{
System.out.println("M1-Method");
};
ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
A a=()->
{
System.out.println("From M1-Method");
};
a.m1();
}
}
ex:
---
@FunctionalInterface
interface A
{
public abstract void m1(int i,int j);
}
class Test
{
public static void main(String[] args)
{
A a=(int i,int j)->
{
System.out.println(i+j);
};
a.m1(10,20);
}
}
ex:
---
@FunctionalInterface
interface A
{
public abstract int m1(int i,int j);
}
class Test
{
public static void main(String[] args)
{
A a=(int i,int j)->
{
return i+j;
};
System.out.println(a.m1(20,50));
}
}
ex:
----
interface A
{
public abstract void m1();
ex:
---
interface A
{
public abstract void m1();
ex:
interface Right
{
default void m1()
{
System.out.println("Right-M1-Method");
}
}
interface Left
{
default void m1()
{
System.out.println("Left-M1-Method");
}
}
class Middle implements Right,Left
{
public void m1()
{
System.out.println("Middle-M1 Method");
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}
ex:
---
interface Right
{
default void m1()
{
System.out.println("Right-M1-Method");
}
}
interface Left
{
default void m1()
{
System.out.println("Left-M1-Method");
}
}
class Middle implements Right,Left
{
public void m1()
{
Right.super.m1();
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}
ex:
--
interface Right
{
default void m1()
{
System.out.println("Right-M1-Method");
}
}
interface Left
{
default void m1()
{
System.out.println("Left-M1-Method");
}
}
class Middle implements Right,Left
{
public void m1()
{
Left.super.m1();
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}
If we declare any method inside the interface and tagged with static keyword then it is called
static method.
ex:
interface A
{
static void m1()
{
System.out.println("A-M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A.m1();
}
}
Stream API
===========
Stream API is used to perform bulk operations on Collection.
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
List<Integer> newList=list.stream().filter(i->i%2==0).collect(Collectors.toList());
System.out.println(newList);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
List<Integer> newList=list.stream().filter(i->i%2!=0).collect(Collectors.toList());
System.out.println(newList);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
List<Integer> newList=list.stream().map(i->i+10).collect(Collectors.toList());
System.out.println(newList);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
long evens=list.stream().filter(i->i%2==0).count();
System.out.println(evens);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
List<Integer> newList=list.stream().sorted().collect(Collectors.toList());
System.out.println(newList);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
List<Integer>
newList=list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(newList);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
long min=list.stream().min((i1,i2)->i1.compareTo(i2)).get();
System.out.println(min);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
long max=list.stream().max((i1,i2)->i1.compareTo(i2)).get();
System.out.println(max);
}
}
forEach() method
================
A forEach() method introduced in Java 1.8v.
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
Map<Integer,String> map=new LinkedHashMap<Integer,String>();
map.put(1,"one");
map.put(10,"ten");
map.put(5,"five");
map.forEach((key,value)-> System.out.println(key+"="+value));
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(7,3,9,1,4,6);
list.forEach(System.out::println);
}
}
class Test
{
public static void main(String[] args)
{
List<Employee> l=new ArrayList<Employee>();
l.add(new Employee(104,"Alan",4000d));
l.add(new Employee(101,"Jose",1000d));
l.add(new Employee(102,"Kelvin",2000d));
l.add(new Employee(103,"Mark",3000d));
List<Employee> newList=l.stream().
sorted(Comparator.comparingInt(Employee::getEmpId)).collect(Collectors.toList());