Core-Java Full Notes
Core-Java Full Notes
Programming language
=======================
Diagram: introduction1.1
Java
====
>Object oriented programming language.
>Platform independent programming language.
>Case sensitive programming language.
>Strongly typed checking language
>High level programming language.
>Open-source programming language.
1995 --> James Gosling --> Sun Micro System (Oracle Corporation)
JDK software
C
===
>Procedure oriented programming language.
>Platform dependent programming language.
>Case sensitive programming language.
>Loosely typed checking language.
>Middle level language (LOW + HIGH)
Interview Questions
===================
Q) What is Java?
Python Java
----------- -----
>It is developed by Guido >It is developed by James van Rossum
Gosling.
Note:
------
Note:
-----
.java file ------------> .class file ----------------> JRE
ex1:
----
python
------
class Test:
java
-----
class Test
{
}
ex:2
----
python
------
i = 10;
java
----
int i = 10;
ex:3
----
python
------
for i in range(1,11):
print(i);
java
----
for(int i=1;i<=10;i++)
System.out.println(i);
Project
========
A project is a collection of modules.
ex:
report generation module
admin module
login module
registration module
payment module
and etc.
1) Technical Domain
-------------------
Technical domain describes using which technology we developed
our project.
ex:
Java
2) Functional Domain
------------------
Functional domain describes state of a project.
ex:
Healthcare domain
Banking domain
Insurance domain
ERP domain
and etc.
1) \n (new line)
2) \t (horizontal tab)
3) \b (back space)
4) \r (carriage return)
5) \f (form feeding)
6) \\ (back slash)
and etc.
1) \n (new line)
-----------------
class Ganesh
{
public static void main(String[] args)
{
System.out.println("IHUB\nTALENT");
}
}
o/p:
IHUB
TALENT
2) \t (horizontal tab)
----------------------
class Akhila
{
public static void main(String[] args)
{
System.out.println("IHUB\tTALENT");
}
}
o/p:
IHUB TALENT
3) \b (back space)
-------------------
class Yogeesh
{
public static void main(String[] args)
{
System.out.println("IHUBTALENT\b");
}
}
o/p:
IHUBTALEN
ex:
---
class Rakesh
{
public static void main(String[] args)
{
System.out.println("IHUB\b\b\bTALENT");
}
}
o/p:
ITALENT
4) \r (carriage return)
----------------------
class Sowmya
{
public static void main(String[] args)
{
System.out.println("IHUB\rTALENT");
}
}
o/p:
TALENT
ex:
---
class Jagadeesh
{
public static void main(String[] args)
{
System.out.println("TALENT\rIHUB");
}
}
o/p:
IHUBNT
6) \\ (back slash)
------------------
class Harsha
{
public static void main(String[] args){
System.out.println("IHUB\\TALENT");
}
}
o/p:
IHUB\TALENT
C program
=========
Q) Write a c program to print %d ?
void main()
{
clrscr();
printf("%d"); // 0
getch();
}
ex:
---
void main()
{
clrscr();
printf("%%d"); // %d
getch();
}
o/p:
I Love "Java" programming
o/p:
I Love 'java' programming
I Love 'java' programming
*Programming language
========================
Diagram: java1.1
ex:
Machine language
Assembly language
Machine language
----------------
It is a fundamental language of a computer which is combination of 0's
and 1's.
It is also known as binary language.
Advantages:
Disadvantages:
Assembly language
-----------------
The second generation language came into an existence is called
assembly language.
1) Assembler
2) Compiler
3) Interpreter
1) Assembler
-------------
It is one of the translator which converts assemblic code to machine
code.
Merits:
Demerits:
1) It is a mind trick to remember all symbolic code.
2) It requires translator.
Q)What is Debugging?
ex:
Java, .Net, Python, Perl and etc.
compiler
--------
It will compile and execute our program at a time.
interpreter
-----------
It will execute our program line by line procedure.
Advantages:
1) It is easy to learn and easy to use because it is similar to english
language.
Disadvantages:
2) It requires translator
*Modules in Java
==================
We have three modules in java.
Java
|-----------------------|-----------------|
JSE/J2SE JEE/J2EE JME/J2ME
(Java Standard Edition) (Java Enterprise Edition) (Java Micro Edition)
ex:
class Test
{
public static void main(String[] args)
{
-
- // any logic here
-
}
}
> Desktop App
-----------
It is a software application which is used to perform perticular task.
ex:
Control Panel
Recycle bin
VLC Media Player
and etc
Diagram: java2.2
ex:
Facebook
Online Shopping website
Diagram: java2.4
>Mobile App
----------
It is a software application or a program which specially designed for
wireless network devices like phone , tab , cell , cellular and etc
rather then laptop's and pc's.
ex:
PubG
PhonePay
Gpay
templeRun
and etc.
Q) What is Java ?
>Memory allocation and deallocation will >Memory allocation and deallocation will taken
taken care by a programmer. care by JVM.
>It supports multiple inheritance. >It does not support multiple inheritance.
>It supports operator overloading. >It does not support operator overloading.
>It supports three access specifiers >It supports four access modifiers i.e default
i.e, public, private and protected. Public ,private and protected.
>It supports three types of loops i.e >It supports four types of loops i.e do while
loop ,do while loop, while loop and while loop, for loop and for each loop.
for loop.
>It supports preprocessor directory(#). >It does not support preprocessor directory(#).
>To save c++ program we will use .cpp >To save java program we will use .java
extension. Extension.
.Net Java
---------- --------------
>It is a product of Microsoft. >It is a product of Oracle Corporation.
Types of IT companies
======================
We have three types of IT companies.
*SDLC
=======
SDLC stands for Software Development Life Cycle.
1) Feasibility study
2) Analysis
3) Designing
4) Coding
5) Testing
1) Feasibility study
---------------------
Feasibility study completely depends upon TELOS formulea.
ex:
T - Technical feasibility
E - Economical feasibility
L - Legal feasibility
O - Operational feasibility
S - Scheduled feasibility
All the above information they will keep in a document called BDD.
BDD stands for Business Design Document.
2) Analysis
-----------
In analysis phase, system analyst or product owner will involved.
Later they will keep all the above information in a document called
SRS.
3) Designing
------------
We have two types of designing.
All the above information they will keep in a document called PDD/TDD.
4) Coding
----------
In coding phase, developers will involved.
5) Testing
----------
In testing phase, Testing team or QA team will involved.
They will use one software component called STLC to test the build.
i) Alpha testing
*Comments in java
===================
>Comments are created for documentation purpose.
Diagram: java4.1
Comments will not display in output because they will not compiled by
the compiler.
ex:
---
//class declaration
class Example
{
//main method
public static void main(String[] args)
{
//variable declaration
int i=10;
//output stmt
System.out.println(i);
}
}
ex:
classes
interfaces
variables
methods
keywords
packages
constants
classes
--------
In java, a class name must and should starts with upper case letter and
if it contains multiple words then each inner word must starts with
initcap.
ex:
Predefined classes Userdefined classes
------------------- --------------------
System Test
File TestApp
BufferedWriter DemoExample
StringBuffer EmployeeDetails
and etc. and etc.
interfaces
-----------
In java, an interface name must and should starts with upper case
letter and if it contains multiple words then each inner word must
starts with initcap.
ex:
predefined interfaces userdefined interfaces
--------------------- -----------------------
Runnable ITest
Serializable IDemoApp
ListIterator IExampleDemo
Enumeration IEmployeeDetails
and etc. and etc.
variables
-----------
In java , a variable name must and should starts with lowercase letter
and if it contains multiple words then each inner word must starts with
initcap.
ex:
predefined variables userdefined variables
------------------- ---------------------
length empId
out studName
err deptNo
in countTokens
and etc. and etc.
Methods
-------
In java, a method name must and should starts with lowercase letter and
if it contains multiple words then each inner word must and should
starts with uppercase letter.
ex:
predefined methods userdefined methods
----------------- --------------------
getPriority() getDetails()
setName() setInfo()
getClass() getEmployeeDetails()
hashCode() calculateBillAmt()
toString() discount()
and etc. and etc.
keywords
----------
In java, all keywords we need to declare under lowercase letters only.
ex:
predefined keywords
-------------------
if, else, for, switch, while, public, static, void and etc.
packages
--------
In java, all packages we need to declare under lowercase letters only.
ex:
predefined packages user-defined packages
------------- --------------------
java.lang(default pkg) com.ihub.www
java.io com.google.www
java.util com.java.www
java.util.stream and etc.
java.sql
java.time
java.text
and etc.
constants
--------- In java , all constants we need to declare under uppercase
letters only.
ex:
predefined constants userdefined constants
----------------- ----------------------
MAX_PRIORITY int LIMIT=10;
MIN_PRIORITY
NORM_PRIORITY
MAX_VALUE
MIN_VALUE
and etc.
Interview Questions
===================
java.lang package
53
platform independent.
Q) JVM is platform dependent or independent?
JDK
-----
JDK stands for Java Development Kit.
JRE
----
JRE stands for Java Runtime Environment.
It provides very good environment to run java applications only.
JVM
----
JVM stands for Java Virtual Machine.
It is an interpreter which is used to execute our program line by line
procedure.
Diagram: java4.2
Assignment
===========
1) class : QualityThought
2) interface : IQualityThought
3) variable : qualityThought
4) method : qualityThought()
5) package : com.qualitythought.www
*History of Java
=================
In 1990, Sun Micro System 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
was 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 created our own programming language which is system
independent.
In 1991, They have develop a programming language called OAK. OAK means
strength , itself is a coffee seed name and it is a national tree for
many contries like Germany, France, USA and etc.
*Identifiers
============
A name in java is called identifier.
ex:
class Test
{
public static void main(String[] args)
{
int x=10;
System.out.println(x);
}
}
Rule2:
-----
If we take other characters then we will get compile time error.
ex:
int emp$alary;
int emp_id;
int emp#Name; //invalid
Rule3:
-----
Identifier must and should starts with alphabet, dollar or
underscore but not with digit.
ex:
int emp123;
int empSal;
int $alary;
int 1abcd; // invalid
Rule4:
-----
We can't take reserved words as an identifiers.
ex:
int if; //invalid
int else; //invalid
int for; //invalid
Rule5:
------
Every identifier is a case sensitive.
ex:
int number;
int NUMBER;
int NuMbEr;
Rule6:
------
There is no length limit for an identifier but it not recommanded
to take more then 15 characters.
Reserved Words
===============
There are some identifiers which are reserved to associate some
functionality or meaning
such type of identifiers are called reserved words.
Diagram: java5.1
for
case
Interview Questions
====================
Q) Who is the creator of Java?
James Gosling
In 1995.
OAK
2) Object oriented
3) Platform independent
4) Architecture Neutral
5) Multithreaded
6) Robust
7) Portable
8) Highly secured
9) Dynamic
10) Distributed
and etc.
*INSTALLATION OF JAVA
=======================
Version : Java 8
Software : JDK 11
Website : www.oracle.com/in/java
Download link :
https://drive.google.com/file/d/1GtRLHXK4y3s97BH2UcYiJPNBaROR1DBV/view?
usp=drive_link
step2:
-----
Copy "lib" directory from java-home folder.
ex:
C:\Program Files\Java\jdk-11\lib
step3:
------
Paste "lib" directory in environmental variables.
ex:
Right click to My PC --> properties --> Advanced System
settings -->
Environmental variables --->
step4:
-----
Test the environment setup done perfectly or not.
ex:
cmd> javap
cmd> java -version
step2:
-----
Make sure environmental setup done perfectly.
step3:
-----
Create a "javaprog" folder inside 'E' drive.
step4:
-----
Open the notepad and develop simple Hello World program.
ex:
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
step5:
------
Save above program by using same name as class name inside
"javaprog" location.
step6:
------
Open the command prompt from javaprog location.
step7:
-----
Compile java program by using below command.
ex:
javac Test.java
|
file name
step8:
-----
Run java program by using below command.
ex:
java Test
|
class name
JVM will invoke one module called classloader or subsystem to load all
the byte code instructions from .class file. The work of classloader is
to check , these byte code instructions are proper or not. If they are
not proper then it will refuse the execution. If they are proper then
it will allocates the memories.
1) Method Area
--------------
It contains code of a class, code of a variable and code of a method.
2) Heap
--------
Our object creations will store in heap area.
3) Java Stack
----------
[whenever we declare variables inside a method they will strore in java
Stack]
Java methods stored in method area. But to execute those methods we
required some memory and that memory will be allocated in Java Stack.
4) PC Register
--------------
It is a program counter register which is used to track the address of
an instructions.
Execution engine
---------------
Execution engine contains interpreter and JIT compiler.
Whenever JVM loads byte code instructions from .class file , it uses
interpreter and JIT compiler simultaneously.
Interview Questions
===================
1) Method Area
2) Heap
3) Java Stack
4) PC Register
5) Native Method Stack
1) Bootstrap classloader
2) Extension classloader
3) System/Application classloader
*Datatypes
==============
Datatype describes what type of value we want to store in a variable.
Datatype also tells how much memory has to be created for a variable.
1) Primitive Datatypes
2) Non-Primitive Datatypes
Diagram: java7.1
byte
-----
It is a smallest datatype in java.
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 a rarely used datatype in java.
ex:
1) short s=10.56;
System.out.println(s); // C.T.E
2) short s="hi";
System.out.println(s); // C.T.E
3) short s=true;
System.out.println(s); // C.T.E
int
----
It is mostly used datatype in java.
ex:
1) byte b=10;
short s=b;
int i=s;
System.out.println(i); // 10
2) int i="false";
System.out.printn(i); // C.T.E
3) int i=10.5;
System.out.println(i); // C.T.E
4) 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 hold large value then we need to use
long datatype.
ex:
1) long l="a";
System.out.println(l); //C.T.E
2) long l='A';
System.out.println(l); //65
3) 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.
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.
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.
Range : 0 to 65535
ex:
1) char ch='a';
System.out.println(ch); // a
2) char ch=97;
System.out.println(ch); // a
3) char ch='ab';
System.out.println(ch); // C.T.E
Diagram: java7.2
ex:
class Test
{
public static void main(String[] args)
{
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
}
}
INTERVIEW QUESTIONS:
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.
1) Primitive variables
----------------------
It is used to represent primitive values.
2) Reference variables
----------------------
It is 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
----------------------
A value of a variable which is varied(changes) from object to object is
called instance variable.
Instance variable must and should declare immediately after the class
but not inside methods, blocks and constructors.
ex:1
----
class Test
{
//instance variable
int i=10;
ex:2
----
class Test
{
//instance variable
int 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:4
-----
class Test
{
//instance variable
int i=10;
System.out.println(t1.i); //10
System.out.println(t2.i); //10
t1.i=100;
System.out.println(t1.i); //100
System.out.println(t2.i); //10
}
}
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 must and should declare immediately after the class
using static keyword but not inside methods, blocks and constructors.
Static variable we can access by using object reference and class name.
ex:1
----
class Test
{
static int 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 String s=”ram”;
System.out.println(Test.s);//null
}
}
ex:3
-----
class Test
{
static int i=10;
System.out.println(t1.i); // 10
System.out.println(t2.i); // 10
t1.i=100;
System.out.println(t1.i); // 100
System.out.println(t2.i); // 100
}
}
ex:4
---
class Test
{
public static void main(String[] args)
{
m1();
Test.m1();
}
public static void m1()
{
System.out.println("static-method");
}
}
3) Local variables
-------------------
To meet temperory requirements we will declare some variables inside
methods, blocks and constructors such type of variables are called
local variables.
ex:
---
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 any default value.
ex:2
----
class Test
{
public static void main(String[] args)
{
//local variable
int i;
System.out.println(i); //variable i might not have been
initialized
}
}
ex:3
----
class Test
{
public static void main(String[] args)
{
//local variable
final int i=10;
System.out.println(i); //10
}
}
Assignment
==========
Q) Declare a class?
class Test
{
int i=10;
*Main Method
=============
Our program contains main method or not. Either it is properly declared
or not. It is not a responsibility of a compiler to check. It is a
liability of a JVM to look for main method.
If JVM won't find main method then it will throw one runtime error
called main method not found.
ex:
public static void main(String[] args)
If we perform any changes in above signature then JVM will throw one
runtime error called main method not found.
public
------
JVM wants to call main method from anywhere.
static
------
JVM wants to call main method without using object reference.
void
-----
Main method does not return anything to JVM.
main
----
It is an identifier given to main method.
String[] args
-----------
It is a command line argument.
ex:
javac Test.java
ex:
----
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
System.out.println(args[3]);
}
}
System.out.println()
====================
It is a output statement in java.
syntax:
-------
static variable
|
System.out.println();
| |
predefined final predefined method
class
Diagram: java9.1
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
System.out.print("stmt2");
System.out.printf("stmt3");
}
}
2)
int i=10;
System.out.println(i);
System.out.println("The value is ="+i);
2)
int i=10,j=20;
System.out.println(i+" "+j);
3)
int i=10,j=20,k=30;
System.out.println(i+" "+j+" "+k);
*Fully Qualified Name
=======================
Fully qualified name means we will declare a class or interface along
with package.
ex:
java.lang.System(C)
java.lang.Runnable(I)
ex:
---
class Test
{
public static void main(String[] args)
{
java.util.Date d=new java.util.Date();
System.out.println(d);
}
}
*Import Statements
===================
Whenever we use import statements then we should not use fully
qualified name.
3) Static import
ex:
import java.util.Date;
class Test
{
public static void main(String[] args)
{
Date d=new Date();
System.out.println(d);
}
}
ex:
----
import java.time.LocalDate;
class Test
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
System.out.println(date);
}
}
ex:
---
import java.time.LocalDate;
import java.time.LocalTime;
class Test
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time);
}
}
ex:
---
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time);
}
}
3) Static import
----------------
Using static import we can call static members(static variables and
static methods) directly.
Often use of static import makes our program complex and unreadable.
ex:
---
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 Editor
================
Download link : https://www.editplus.com/download.html
import java.util.Scanner;
class Example1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int c = a + b;
import java.util.Scanner;
class Example2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Assignment
==========
Q) Write a java program to perform area of a rectangle?
input:
5
output:
25
ex:
import java.util.Scanner;
class Example3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int square=n*n;
input:
5
output:
125
ex:
import java.util.Scanner;
class Example4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int cube=n*n*n;
import java.util.Scanner;
class Example5
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
float area=3.14f*r*r;
import java.util.Scanner;
class Example6
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
float perimeter=2*3.14f*r;
System.out.println("perimeter of a circle is ="+perimeter);
}
}
input:
a = 10 and b = 20
output:
a = 20 and b = 10
import java.util.Scanner;
class Example7
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//swapping logic
int temp=a;
a=b;
b=temp;
}
}
import java.util.Scanner;
class Example8
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//swapping logic
a = a + b;
b = a - b;
a = a - b;
}
}
Q) Write a java program to accept one salary then find out 10% of TDS?
import java.util.Scanner;
class Example9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
float tds=(float)salary*10/100;
}
}
import java.util.Scanner;
class Example10
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
float percentage=cgpa*9.5f;
}
}
*Typescasting in java
=======================
The process of converting from one datatype to another datatype is
called typecasting.
2) Explicit typecasting
ex:
byte ---> short
--->
int ---> long ---> float ---> double
--->
char
ex:1
-----
class Test
{
public static void main(String[] args)
{
byte b=10;
int i=b;
System.out.println(i);//10
}
}
ex:2
----
class Test
{
public static void main(String[] args)
{
char ch='a';
double d=ch;
System.out.println(d); // 97.0
}
}
ex:3
----
class Test
{
public static void main(String[] args)
{
int i=10;
float f=i;
System.out.println(f); // 10.0
}
}
ex:
byte <--- short
<---
int <--- long <--- float <--- double
<---
char
ex:1
----
class Test
{
public static void main(String[] args)
{
double d=10.5d;
int i=(int)d;
System.out.println(i); //10
}
}
ex:2
----
class Test
{
public static void main(String[] args)
{
int i=65;
char ch=(char)i;
System.out.println(ch); // A
}
}
ex:3
---
class Test
{
public static void main(String[] args)
{
int i=130;
byte b=(byte)i;
System.out.println(b); // -126
}
}
Assignment
==========
Q) Write a java program to accept six marks of a student then find out
total and average?
1) Instance block
2) Static block
3) Local block
1) Instance block
------------------
It 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.
syntax:
------
//instance block
{
-
- //set of statements
-
}
ex:1
----
class Test
{
//instance block
{
System.out.println("instance-block");
}
ex:2
-----
class Test
{
//instance block
{
System.out.println("instance-block");
}
ex:
----
class Test
{
//instance block
{
System.out.println("instance-block");
}
ex:
---
class Test
{
//instance variable
int i;
//instance block
{
i=100;
}
2) Static block
-----------------
A static block is used to initialize the values to static variables.
A static block must and should declare immediately after the class
using static keyword.
syntax:
------
//static block
static
{
-
- //set of statements
-
}
ex:
---
class Test
{
//static block
static
{
System.out.println("static-block");
}
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}
//static block
static
{
System.out.println("static-block");
}
ex:
----
class Test
{
//static variable
static int i;
//static block
static
{
i=200;
}
3) Local block
--------------
A local block is used to initialize the local variables.
A local block must and should declare inside the methods and
constructors.
syntax:
------
//local block
{
-
- //set of statements
-
}
ex:
---
class Test
{
//local block
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
ex:
---
class Test
{
//local block
{
i=300;
}
System.out.println(i); //300
}
}
Interview Question
==================
ex:
class Test
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
Q) What is Literal ?
ex:
int i = 10;
| | |___ value of a variable / Literal
| |_________ variable name / identifier
|______________ Datatype / keyword
*Operators
============
Operator is a symbol which is used to perform some operations on
operands.
ex:
c = a + b;
1) Assignment 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:
-----
Re-initialization 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
}
}
Note:
------
We can't change or modify 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
}
}
Note:
-----
We can't assign multiple values.
ex:
---
class Test
{
//global variable
static int i=10;
System.out.println(i);//20
}
}
Note:
----
Here priority goes to local variables.
ex:
---
class Test
{
//static variable
static int i=100;
//instance variable
int i=200;
ex:
----
class Test
{
public static void main(String[] args)
{
int i=10;
i+=5; // i = i + 5
System.out.println(i); //15
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i-=5; // i = i - 5
System.out.println(i); //5
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i*=5; // i = i * 5
System.out.println(i); //50
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
i/=5; // i = i / 5
System.out.println(i); //2
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
i/=50; // i = i / 50
System.out.println(i); //0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
i %= 5;
System.out.println(i); // 1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
i %= 15;
System.out.println(i); // 11
}
}
2) Ternary operators
====================
syntax:
-------
(condition)?value1:value2;
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>2)?true:false;
System.out.println(b); //true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=(5>20)?1:0;
System.out.println(i);//0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String s=(true)?"hi":"bye";
System.out.println(s);//hi
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int max=(a>b)?a:b;
System.out.println(max+" is greatest");
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int max=(a>b)?((a>c)?a:c):((b>c)?b:c);
System.out.println(max+" is greatest");
}
}
3) Logical operators
=====================
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) && (10<20);
System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String s=((6>2) && (10<5))?"Welcome":"Thankyou";
System.out.println(s); //Thankyou
}
}
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) || (60<10);
System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=(5>20 || false)?1:0;
System.out.println(i); // 0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String str=(!(5>2))?"Hi":"Bye";
System.out.println(str); // Bye
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String str=(!(5>20))?"Hi":"Bye";
System.out.println(str); // Hi
}
}
2|10
---- 0
2|5
---- 1
2|2
---- 0
1
1010
<---
0 + 2 + 0 + 8 = 10
4) Bitwise operators
=====================
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 + 2 + 0 + 8 = 10
*/
ex:
---
class Test
{
public static void main(String[] args)
{
int a=2, b=3;
int c = a & b;
System.out.println(c); //2
}
}
/*
2 - 0010
3 - 0011
--------
& - 0010
<----
0*1 + 1*2 + 0*4 + 0*8
0 + 2 + 0 + 0 = 2
*/
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=15;
int c = a | b;
System.out.println(c); //15
}
}
/*
10 - 1010
15 - 1111
----------
| - 1111
<----
1 + 2 + 4 + 8 = 15
*/
Truth table
----------
T T = F
T F = T
F T = T
F F = F
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 + 0 + 4 + 0 = 5
*/
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= ~56;
System.out.println(i); // -57
}
}
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= 6+7%2+5*2+8/2+9/10+6*2+10%20-40;
System.out.println(i); // 3
}
}
/*
6 + 7%2 + 5*2 + 8/2 + 9/10 + 6*2 + 10%20 - 40
6 + 1 + 10 + 4 + 0 + 12 + 10 - 40
43 - 40
3 */
6) Relational operators
========================
class Test
{
public static void main(String[] args)
{
System.out.println(10 > 20); //false
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(10 == 10); //true
}
}
7) Shift operators
===================
ex:
---
class Test
{
public static void main(String[] args)
{
int i= 10 >> 3; //10/8
System.out.println(i); // 1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i= 100 >> 5; // 100 / 32
System.out.println(i); // 3
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 5 << 3; // 5 * 8
System.out.println(i); // 40
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 << 6;
System.out.println(i); // 10 * 64 = 640
}
}
8)Unary operators
=================
Increment/Decrement operators(++/--)
-------------------------------------
We have two types of increment operators.
1) Post Increment
ex:
i++;
2) Pre Increment
ex:
++i;
1) Post Decrement
ex:
i--;
2) Pre Decrement
ex:
--i;
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); // 8 19
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
}
}
Pre Increment/Decrement
-------------------------
ex:1
-----
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);//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;
System.out.println(i+" "+j);// 8 17
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(i++ + ++i);// 10 + 12 = 22
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=100;
100++;
System.out.println(i);// C.T.E
}
}
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)
{
byte b=127;
b++;
System.out.println(b);//-128
}
}
Question
=========
Q) Write a java program to find square 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 result=(int)Math.pow(n,2);
System.out.println(result);
}
}
Assignment
==========
Q) Write a java program to convert USD to INR ?
Input:
1
Output:
83.52
Q) Write a java program to convert INR to USD?
Input:
83.52
Output:
1
Control Statements
=====================
Control statement enables the programmer to control flow of the
program.
2) Select Statement
3) Iteration Statement
4) Jump Statement
i) if stmt
i) if stmt
------------
It is used to execute the code only if our condition is true.
syntax:
-----
if(condition)
{
-
- //code to be execute if cond is true
-
}
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(false)
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);
if(a>b)
System.out.println(a+" is greatest");
if(b>a)
System.out.println(b+" is greatest");
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
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(6!=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(6==10)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}
o/p:
stmt1
stmt3
stmt4
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(age>=18)
System.out.println("U r eligible to vote");
else
System.out.println("U r not eligible to vote");
}
}
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 a positive number");
else
System.out.println("It is a negative number");
}
}
if(n%2==0)
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(n%2!=0)
System.out.println("It is odd number");
else
System.out.println("It is not odd number");
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(option==100)
System.out.println("It is a 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");
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
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");
}
}
Assignment
===========
Write a java program to accept six marks of a student then find out
total, average and grade?
syntax:
------
if(condition)
{
if(condition)
{
-
- //code to be execute
-
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(5>2)
{
System.out.println("stmt2");
if(true)
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
System.out.println("stmt5");
}
}
o/p:
stmt1
stmt2
stmt3
stmt4
stmt5
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(5>20)
{
System.out.println("stmt2");
if(true)
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
System.out.println("stmt5");
}
}
o/p:
stmt1
stmt5
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(5>2)
{
System.out.println("stmt2");
if(false)
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
System.out.println("stmt5");
}
}
o/p:
stmt1
stmt2
stmt4
stmt5
Q) Write a java program to find out given number is +ve or -ve using
nested if stmt ?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(n!=0)
{
if(n>0)
{
System.out.println("It is positive number");
System.exit(0);
}
2) Selection statement
======================
switch
=======
It will execute the source code based on multiple conditions.
syntax:
------
switch(condition)
{
case value1: //code to be execute
break stmt;
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
switch(option)
{
case 100: System.out.println("It is a police number");
break;
case 103: System.out.println("It is a enquirynumber");
break;
case 108: System.out.println("It is a emergency
number");
break;
default: System.out.println("Invalid option");
}
}
}
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
switch(option)
{
case 100: System.out.println("It is a police number");
//break;
case 103: System.out.println("It is a enquiry
number");
//break;
case 108: System.out.println("It is a emergency
number");
//break;
default: System.out.println("Invalid option");
}
}
}
The allowed datatype of switch case are byte , short, int, char and
String.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
switch(ch)
{
case 'a': System.out.println("It is a vowel"); break;
case 'e': System.out.println("It is a vowel"); break;
case 'i': System.out.println("It is a vowel"); break;
case 'o': System.out.println("It is a vowel"); break;
case 'u' : System.out.println("It is a vowel"); break;
default: System.out.println("It is a consonent");
}
}
}
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
switch(str)
{
case "one": System.out.println("January"); break;
case "two": System.out.println("February"); break;
case "three": System.out.println("March"); break;
case "four": System.out.println("April"); break;
case "five" : System.out.println("May"); break;
default: System.out.println("Coming Soon...");
}
}
}
3) Iteration Statement
======================
Iteration statement is used to execute the source code repeatedly.
i) do while loop
-----------------
It will execute the source code untill our condition is true.
syntax:
-----
do
{
-
- //code to be execute
-
}while(condition);
ex:
---
class Test
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.print(i+" "); // infinite 1
}
while(i<=10);
}
}
In do while loop, our code will execute atleast for one time either our
condition is true or false.
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
do
{
System.out.print(i+" "); //11
}
while(i<=10);
}
}
class Test
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.print(i+" "); //1 2 3 4 5 6 7 8 9 10
i++;
}
while (i<=10);
}
}
class Test
{
public static void main(String[] args)
{
int i=10;
do
{
System.out.print(i+" "); //10 9 8 7 6 5 4 3 2 1
i--;
}
while (i>=1);
}
}
output:
1+2+3+4+5+6+7+8+9+10 = 55
ex:
---
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
do
{
sum=sum+i;
i++;
}
while (i<=10);
System.out.println(sum);
}
}
output:
120 (5*4*3*2*1)
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();
System.out.println(fact);
}
}
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();
int i=1;
do
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
while (i<=10);
}
}
ii) while loop
==============
It will execute the source code untill our condition is true.
syntax:
------
while(condition)
{
-
- //code to be execute
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=1;
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
}
}
}
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i=1;
while(i<=10)
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
}
Q) Write a java program to perform sum of digits of a given number?
input:
123
output:
6
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
System.out.println(sum);
}
}
input:
153
output:
It is an amrstrong number (1*1*1+5*5*5+3*3*3)(1+125+27)(153)
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int temp=n;
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(temp==sum)
System.out.println("It is an armstrong number");
else
System.out.println("It is not an armstrong number");
}
}
Input:
123
Output:
321
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int rem,rev=0;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
System.out.println(rev);
}
}
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 palidrome number");
}
}
Orchasp company Interview Question
==================================
Write a java program to calculate costs based on user input. The
program
should prompt users to enter the total weight of items(in kilograms)
and the shipping destination (domestic or international). For demostic
orders, the program should charge Rs.500 for weights upto 5 kg and
Rs.100 per additional kg. For international orders, it should charge
Rs.1000 for weights upto 5 kg , Rs.200 per additional kg , and a Rs.500
surcharge for weights exceeding 10 kg. print calculated shipping cost.
Input:
Enter total weight of items : 11
Enter the shipping destination : domestic
Output:
1100 (weight <=5 --> Rs. 500 + 600(6kgs) ) --> Domestic
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
if(destination.equals("domestic"))
{
if(weight<=5)
System.out.println(500);
else if(weight>5)
System.out.println(500 + (weight-5) * 100);
}
else
{
if(weight<=5)
System.out.println(1000);
else if(weight>5 && weight<=10)
System.out.println(1000 + (weight-5)*200);
else if(weight>10)
System.out.println(1000 + (weight-5)*200 + 500);
}
}
}
3) for loop
===========
It will execute the source code untill our condition is true.
syntax:
------
for(initialization;condition;incrementation/decrementation)
{
-
- //code to be execute
-
}
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.
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)
{
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
System.out.print(i+" "); //2 4 6 8 10
}
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int cnt=0;
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
cnt++;
}
}
System.out.println(cnt); //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);
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 a prime number");
else
System.out.println("It is not a prime number");
}
}
Assignment
==========
Q) Write a java program to find out factorial of a given number using
for loop?
Input:
n = 5
Output:
120
Input:
123
Output:
ThreeTwoOne
output:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.
ex:
---
class 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);
System.out.println("Enter the number :");
int n=sc.nextInt(); //6
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(n==sum)
System.out.println("It is a perfect number");
else
System.out.println("It is not a perfect number");
}
}
Input:
12 18
Output:
6
class Test
{
public static void main(String[] args)
{
int a=12,b=18,gcd=0;
input:
6
output:
0 1 1 2 3 5 8
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();
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)
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
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)
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
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)
4 4 4 4
3 3 3 3
2 2 2 2
1 1 1 1
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)
A A A A
B B B B
C C C C
D D D D
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)
D D D D
C C C C
B B B B
A A A A
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();
}
}
}
Assignment
==========
Write a java program to display below loop pattern?
ex:
4 3 2 1
4 3 2 1
4 3 2 1
4 3 2 1
ex:
1 1 1
1 0 1
1 1 1
1
2 2
3 3 3
4 4 4 4
ex:
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
2)
4 4 4 4
3 3 3
2 2
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
2 3
4 5 6
7 8 9 0
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+" ");
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 num=2;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(num+" ");
num+=2;
}
//new line
System.out.println();
}
}
}
5)
1
3 5
7 9 11
13 15 17 19
class Test
{
public static void main(String[] args)
{
int num=1;
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(num+" ");
num+=2;
}
//new line
System.out.println();
}
}
}
6)
2
3 5
7 11 13
17 19 23 29
class Test
{
public static void main(String[] args)
{
int num=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<=num/2;k++)
{
if(num%k==0)
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.print(num+" ");
num++;
break;
}
num++;
}
}
//new line
System.out.println();
}
}
}
7)
1
2 1
1 2 3
4 3 2 1
class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//odd records
if(i%2!=0)
{
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
else
{
for(int j=i;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
1
2 2
3 3 3
4 4 4 4
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(" ");
}
//right elements
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}
2)
4 4 4 4
3 3 3
2 2
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(" ");
}
//right elements
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++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//element
for(int j=1;j<=i;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(" ");
}
//element
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}
Pyramid patterns
================
1)
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
ex:
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)
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
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();
}
}
}
Interview Questions
===================
Q) Write a java program to display below loop pattern?
*
*
* * * * *
*
*
ex:
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
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
ex:
class Test
{
public static void main(String[] args)
{
int rows=4;
//rows
for(int i=1;i<=rows;i++)
{
//left side
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
for(int j=i;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}
Assignment
==========
Q) Write a java program to display below loop pattern?
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
ex:
class Test
{
public static void main(String[] args)
{
//rows
for(int i=0;i<5;i++)
{
//spaces
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();
}
}
}
*
* *
* * *
* * * *
* * * * *
class Test
{
public static void main(String[] args)
{
//rows
for(int i=0;i<5;i++)
{
//spaces
for(int j=1;j<5-i;j++)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}
4) Jump Statements
==================
Jump statements are used to jump from one section of code to another
section.
i) break stmt
i) break stmt
-------------
A break statement is used to break the execution of loops and switch
case.
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
}
}
}
syntax:
continue;
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
continue;
System.out.println("stmt2");
}
}
o/p:
C.T.E : 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
}
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
sum();
}
//callie method
public static void sum()
{
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
int c=a+b;
System.out.println("sum of two numbers is ="+c);
}
}
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*=i;
}
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
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);
}
}
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
//caller method
reverse(n);
}
//callie method
public static void reverse(int n)
{
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;
}
}
}
Assignment
==========
Q) Write a java program to check given number is palindrome or not
using
i) No Returntype with no argument
ii) No Returntype with no argument
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);
//logic
int c=a+b;
return c;
}
}
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();
//logic
float area=3.14f*r*r;
return area;
}
}
//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 find out given number is even or odd using
with returntype with argument method?
approach1
----------
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();
//caller method
System.out.println(find(n));
}
//callie method
public static String find(int n)
{
if(n%2==0)
return "It is even number";
else
return "It is odd number";
}
}
approach2
---------
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();
//caller method
int k=find(n);
if(k==1)
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
//callie method
public static int find(int n)
{
if(n%2==0)
return 1;
else
return 0;
}
}
approach3
-------
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();
//caller method
boolean b=find(n);
if(b)
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
============
Q) Write a java program to check given number is Armstrong or not?
Recursion
============
A method which call itself for many number of times is called
recursion.
It is similar to loopings.
import java.util.Scanner;
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);
}
}
}
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();
//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);
}
}
Fibonacci sequence : 0 1 1 2 3 5 8 . . . .
Input:
4
Output:
2
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
System.out.println(fib(n));
}
//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
=========
Arrays is a collection of homogeneous data elements.
Array Declaration
=================
At the time of array declaration we should not specify array size.
Array
|
|--------------------------|-------------------------|
Single Dimensional Array Double Dimensional Array Multi Dimensional
Array
Array Creation
==============
In java, every array consider as an object. Hence we will use new
operator to create an array.
Diagram: java22.1
Rules to constructor an array
-----------------------------
Rule1:
-----
At the time of array creation compulsory we need to specify array
size.
ex:
int[] arr=new int[3];
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 numbers as an array size otherwise we will
get
runtime exception called NegativeArraySizeException.
ex:
int[] arr=new int[-3];
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 length we can take for array size is maximum length
of int datatype.
ex:
int[] arr=new int[2147483647];
Array Initialization
====================
Once if we create an array , every array element initialized with
default values.
If we are not happy with default values then we can change with
customized values.
Diagram: java22.2
int[] arr;
arr = new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30; ==> int[] arr={10,20,30};
length
-------
It is a final variable which is applicable for arrays.
ex:
class Test
{
public static void main(String[] args)
{
int[] arr=new int[5];
System.out.println(arr.length); //5
}
}
length() method
----------------
It is a final method which is applicable for String objects.
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
System.out.println(str.length()); //7
}
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//inserting elements
for(int i=0;i<arr.length;i++)
{
System.out.println("Enter the element :");
arr[i]=sc.nextInt();
}
//displaying elements
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
input:
4 8 1 3 9 7
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
//display
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
input:
4 8 1 3 9 7
output:
7 9 3 1 8 4
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
for(int i=arr.length-1;i>=0;i--)
{
System.out.print(arr[i]+" ");
}
}
input:
4 8 1 3 9 7
output:
32
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
int sum=0;
for(int i:arr)
{
sum+=i;
}
System.out.println(sum);
}
input:
4 8 1 3 9 7
output:
4 8
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
for(int i:arr)
{
if(i%2==0)
{
System.out.print(i+" ");
}
}
}
input:
4 8 1 3 9 7
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,1,3,9,7};
int cnt=0;
for(int i:arr)
{
if(i%2!=0)
{
cnt++;
}
}
System.out.println(cnt);
}
input:
4 2 9 5 7 12 13 20
output:
2 5 7 13
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={4,2,9,5,7,12,13,20};
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+" ");
}
}
Assignment
===========
8) Write a java program to display array elements in sorting order?
input:
5 8 1 3 9 6
output:
1 3 5 6 8 9
input:
9 1 5 2 7 6 4
output:
1 2 4 5 6 7 9
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={9,1,5,2,7,6,4};
Arrays.sort(arr);
//display the elements
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
input:
9 1 5 2 7 6 4
output:
1 2 4 5 6 7 9
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={9,1,5,2,7,6,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;
}
}
}
//display
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
input:
9 1 5 2 7 6 4
output:
9 7 6 5 4 2 1
ex:
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={9,1,5,2,7,6,4};
Arrays.sort(arr);//1 2 4 5 6 7 9
//reading reverse
for(int i=arr.length-1;i>=0;i--)
{
System.out.print(arr[i]+" ");
}
}
}
input:
9 1 5 2 7 6 4
output:
9 7 6 5 4 2 1
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={9,1,5,2,7,6,4};
//decending 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;
}
}
}
//display
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
12) Write a java program to find out highest element from given array?
input:
1 5 2 7 9 6 4
output:
9
ex:
----
class Test
{
public static void main(String[] args)
{
int[] arr={1,5,2,7,9,6,4};
int big=arr[0];
for(int i:arr)
{
If(i>big)
{
big=i;
}
}
System.out.println(big);
}
}
13) Write a java program to find out least element from given array?
input:
5 2 7 1 9 6 4
output:
1
+-
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={5,2,7,1,9,6,4};
int small=arr[0];
for(int i:arr)
{
if(i<small)
{
small=i;
}
}
System.out.println(small);
}
}
14) Write a java program to display three highest elements from given
array?
input:
4 8 2 9 6 1 7 5
output:
9 8 7
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,8,2,9,6,1,7,5};
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);
}
}
output:
7 1 3
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,4,1,3,7,6};
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]+" ");
}
}
}
}
}
16) Write a java program to display unique elements from given array?
input:
5 7 1 3 9 4 1 3 7 6
output:
5 9 4 6
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,4,1,3,7,6};
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]+" ");
}
}
}
17) Write a java program to display most repeating element from given
array?
input:
5 7 1 3 9 4 1 3 7 6 1 8 1
output:
1 repeating for 4 times
ex:
---
class Test
{
public static void main(String[] args)
{a
int[] arr={5,7,1,3,9,4,1,3,7,6,1,8,1};
int maxCount=0;
int element=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(cnt>maxCount)
{
maxCount=cnt;
element=arr[i];
}
}
Assignment
==========
18) Write a java program to display second highest element from given
array without using sort() method?
input:
5 8 1 9 6 2 7
output:
8
19) Write a java program to segregate array elements?
input:
0 1 1 0 0 1 0 1 0 1
output:
0 0 0 0 0 1 1 1 1 1
ex:
class Test
{
public static void main(String[] args)
{
int[] arr={0,1,1,0,0,1,0,1,0,1};
//inserting 1
while(j<arr.length)
{
newArr[j++]=1;
}
}
}
20) Write a java program to find out leader elements from given array?
input:
5 2 34 7 16 3 9
output:
9 16 34
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={5,2,34,7,16,3,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+" ");
}
}
}
}
21) Write a java program to display missing element from given array?
input:
7 3 1 5 6 2
output:
4
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={7,3,1,5,6,2};
int sum_of_ele=arr.length+1;
for(int i:arr)
{
sum-=i; //sum = sum - i;
}
System.out.println(sum);
}
}
input:
arr = 8 3 2 5 6 2 9 1 2
element = 2
output:
8 3 5 6 2 9 1 2
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={8,3,2,5,6,2,9,1,2};
int element=2;
int cnt=0,j=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]==element && cnt==0)
{
cnt=1;
continue;
}
newArr[j++]=arr[i];
}
}
}
input:
arr = 7 1 9 4 7 2
ele = 10
index = 3
output:
7 1 9 10 4 7 2
ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={7,1,9,4,7,2};
int ele=10;
int index=3;
arr=Arrays.copyOf(arr,arr.length+1);
for(int i=arr.length-1;i>=index;i--)
{
arr[i]=arr[i-1];
}
arr[index]=ele;
//display elements
for(int i:arr)
{
System.out.print(i+" ");
}
}
}
24) Write a java program to merge two arrays and display them in
sorting order?
input:
5 1 4 3 2
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,4,3,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);
//display elements
for(int i:arr1)
{
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.println(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[] coins=findMinimumCoins(denominations,amount);
for(int i=0;i<coins.length;i++)
{
if(coins[i]>0)
{
System.out.println(coins[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];
return coinsCount;
}
}
syntax:
------
datatype[][] variable_name=new datatype[rows][columns];
ex:
int[][] arr=new int[3][3];
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//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();
}
}
}
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}
};
int rows=arr.length;
int cols=arr[0].length;
input:
1 2 3
4 5 6
7 8 9
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
int rows=arr.length;
int cols=arr[0].length;
//sum of diagonal elements
int sum=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(i==j)
{
sum+=arr[i][j];
}
}
}
System.out.println("sum of diagonal elements is ="+sum);
}
}
input:
1 2 3
4 5 6
7 8 9
ex:
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
int rows=arr.length;
int cols=arr[0].length;
ex:
class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};
int rows=arr.length;
int cols=arr[0].length;
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;
}
}
Interview Program
===================
Q) Write a java program to display largest prime number in the list?
Input:
2 3 4 5 7 9 11 12
Output:
11
class Test
{
public static void main(String[] args)
{
int[] arr={2,3,4,5,7,9,11,12};
int maxElement=Integer.MIN_VALUE;
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)
{
if(n>maxElement)
{
maxElement=n;
}
}
}
System.out.println(maxElement);
}
input:
1 2 3
4 5 6
7 8 9
output:
1 2 3 6 9 8 7 4 5
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 left=0;
int right=rows-1;
int top=0;
int bottom=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++;
}
}
}
OOPS
======
OOPS stands for Object Oriented Programming System / Structure.
ex:
class
object
Abstraction
Encapsulation
Inheritance
and
Polymorphism
class
======
A class is a blue print of an object.
syntax:
optional
|
Modifier class class_name <extends> Parent_classname
<implements> interface_name
{
-
-
-
}
A class will accept following modifiers.
ex:
default
public
final
abstract
Realtime example
-----------------
To constructor a building we required a design. That design is known as
blue print/class.
ex: ex:
class Test public class Test
{ {
} }
ex: ex:
final class Test abstract class Test
{ {
} }
object
=======
It is a outcome of a blue print.
It is a instance of a class.
It is a physical entity.
Realtime example
-----------------
Dog (object)
|
|--------------------------------|
properties behaviours
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@Hexadecimal
System.out.println(t2.toString());
System.out.println(t3.toString());
}
}
For every object, JVM will create a unique identification number i.e
hash code.
Diagram: java27.1
What ever the properties are present in Object class that can be
inherit by child classes.
ex:
cmd> javap java.lang.Object
hashCode()
toString()
getClass()
clone()
notify()
notifyAll()
wait()
and etc.
class object
---------------- -----------
To declare a class we will use To declare an object we will use
class keyword. new .
Data Hiding
===========
It is a technique of hiding object data from outsiders.
ex:
---
class Account
{
private double balance=10000d;
}
class Test
{
public static void main(String[] args)
{
Account account=new Account();
System.out.println(account.balance); // 10000
}
}
Our internal data should not go out directly. It means outside person
must not access our data directly.
Abstraction
============
The process of hiding internal implementation and highlighting the set
of services is called abstraction.
Where bank people will hide internal implementation and highlights the
set of services like Banking, Withdrawl, MiniStatement and etc.
Ecapsulation
=============
The process of encapsulating or grouping variables and it's associate
methods in a single entity is called encapsulation.
Diagram: java27.2
A class is said to be encapsulated class if it supports data hiding and
abstraction.
Diagram: java27.3
1) It gives security.
ex:
---
class Student
{
private int studId;
private String studName;
private double studFee;
//setter methods
public void setStudId(int studId)
{0
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());
}
}
Here we don't need to check these variables contain setter and getter
methods.
ex:
class A
{
private int i;
}
It is tightly encapsulated class.
ex:
class A
{
int i;
private int j;
}
It is not tightly encapsulated class.
Is-A relationship
=================
Is-A relationship is also known as inheritance.
ex:
class Vehicle
{
public void engine()
{
System.out.println("Engine Method");
}
}
class Car extends Vehicle
{
public void company()
{
System.out.println("Company Method");
}
}
class Test
{
public static void main(String[] args)
{
Vehicle v=new Vehicle();
v.engine();
conclusion
-----------
Whatever our parent contains property it comes to child. But whatever
child contains property never
goes back to parent.
A parent reference can hold child object but child reference can't hold
parent object.
Inheritance
============
Inheritance is a mechanism where we will derived a class in the
presence of existing class.
Diagram: java28.1
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
Diagram:
A (Parent/Base/Super class)
|
|
|
B (Child/Derived/Sub class)
ex:
----
class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();
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)
{
B b=new B();
int c=b.i+b.j;
System.out.println(c); //30
}
}
Diagram:
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 simultenously because
java does not support multiple
inheritance.
ex:
class A
{
}
class B
{
}
class C extends A,B --> invalid
{
}
But interface can extends more then one interface so 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 it is a indirect child class
of Object class.
ex: Diag:
class A Object
{ |
} |
class B extends A A
{ |
} |
B
There is a chance of raising ambiguity problem that's why java does not
support multiple inheritance.
ex:
P1.m1() P2.m1()
|--------------------------------------------|
|
c.m1();
4) Hierarchical inheritance
----------------------------
If we derived multiple classes in the presence of one base class is
called hierarchical inheritance.
ex: Diagram:
class A A
{ |----------|-------|
} B C
class B extends A
{
}
class C extends A
{
}
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.
Has-A relationship
==================
Has-A relationship is also known as composition and aggregation.
ex:
class Course
{
-
- //course logic
-
}
class Job
{
Course c=new Course();
-
-
}
ex:
---
class Ihub
{
public String courseName()
{
return "Full Stack Java";
}
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: java28.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: java28.3
Method overloading
=====================
Having same method name with different parameters/signatures in a
single class is called method
overloading.
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 Customer
{
public static void main(String[] args)
{
MeeSeva ms=new MeeSeva();
ms.search(101);
ms.search("1-6-4/1/A");
ms.search(1024L);
}
}
Yes, we can overload main method in java but JVM always execute main
method with String[]
argument.
ex:
class Test
{
public static void main(int[] iargs)
{
System.out.println("int[] iargs");
}
public static void main(String[] args)
{
System.out.println("string[] args");
}
}
Method overriding
==================
Having same method name with same parameters in a two different class
is called method overriding.
Methods which are present in child class are called overriding methods.
ex:
---
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
//overridden method
public void marry()
{
System.out.println("Anushka");
}
}
class Child extends Parent
{
//overriding method
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(); // Anushka
}
}
ex:
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
//overridden method
public final void marry()
{
System.out.println("Anushka");
}
}
class Child extends Parent
{
//overriding method
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(); // Anushka
}
}
o/p:
C.T.E : Overridden method is final
ex:
class Parent
{
private void property()
{
System.out.println("House-Not For Sale");
}
}
class Child extends Parent
{
public void property()
{
System.out.println("House- For Sale");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property();
}
}
o/p:
C.T.E : property() has private access in Parent
Private and final methods can be overloaded. Private and final methods
can't be overridden.
Method Hiding
=============
Method hiding is exactly same as method overriding with following
differences.
ex:
--
class Parent
{
public static void property()
{
System.out.println("cash+gold+land");
}
//overridden method
public static void marry()
{
System.out.println("Anushka");
}
}
class Child extends Parent
{
//overriding method
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(); // Anushka
}
}
Diagram: java29.1
2) Runtime polymorphism
ex:
Method overloading
Method hiding
2) Runtime polymorphism
-----------------------
A polymorphism which exhibits at run time is called run time
polymorphism.
ex:
Method overriding
Abstraction Encapsulation
---------- -------------
Hiding internal implementation and highlighting The process of
encapsulating variables and it's
the set of services is called abstraction. associate methods in a
single entity is called
encapsulation.
Q) What is the difference between POJO class and Java Bean class?
Fields can have any visibility. Fields can have only private
visibility.
There may or may not have 0-arg constructor. It must have 0-argument
constructor.
ex:
POJO
----
class Student
{
private int studId;
Java Bean
---------
class Student implements java.io.Serializable
{
private int studId;
Student()
{
Diagram: java29.2
constructors
==============
A constructor is a special method which is used to initialized an
object.
ex:
default
public
private
protected
A constructor does not allow any returntype.
1) Userdefined constructor
2) Default constructor
1) Userdefined constructor
-------------------------
If a constructor is created by the user based on the application
requirement is
called user defined constructor.
ex:
---
class Test
{
Test()
{
System.out.println("0-arg const");
}
ex:
---
class Test
{
public Test()
{
System.out.println("0-arg const");
}
ex:
---
class Test
{
private Test()
{
System.out.println("0-arg const");
}
ex:
---
class Test
{
protected Test()
{
System.out.println("0-arg const");
}
ex:
class Employee
{
//current class variables
private int empId;
private String empName;
private double empSal;
2) Default constructor
------------------------
It is a compiler generated constructor for every java program where we
are not defining
atleast zero argument constructor.
ex:
cmd> javac Test.java
cmd> javap -c Test
Diagram: java30.1
Q) What is 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.
System.out.println(cust.getCustId());
System.out.println(cust.getCustName());
System.out.println(cust.getAddress());
}
}
Interface
============
Interface is a collection of zero or more abstract methods.
Abstract methods are incomplete methods because they ends with
semicolon and does not have any body.
ex:
void m1();
ex:
public abstract void m1();
syntax:
-------
interface <interface_name>
{
- //abstract methods
- //constants
}
Diagram: java31.1
ex:
----
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:
---
interface A
{
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();
}
}
ex:
---
interface A
{
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.show();
a.see();
a.view();
a.display();
}
}
In java, a class can't extends more then one class.
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)
{
C c=new D();
c.m1();
c.m2();
c.m3();
}
}
ex:
interface Father
{
float HT=6.2f;
void height();
}
interface Mother
{
float HT=5.8f;
void height();
}
class Child implements Father,Mother
{
public void height()
{
float height=(Father.HT+Mother.HT)/2;
System.out.println("Child Height :"+height);
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
c.height();
}
}
Note:
-----
From Java 8 version, Interface is a collection of abstract methods,
default methods and static methods.
ex:
Serializable
Cloneable
Remote
and etc.
ex:
---
class Item implements java.io.Serializable
{
private int itemId;
private String itemName;
private double itemPrice;
Abstract class
==============
Abstract class is a collection of zero or more abstract methods and
concrete methods.
A abstract keyword is applicable for methods and classes but not for
variables.
syntax:
-----
abstract class class_name
{
-
- // abstract methods
- // concrete methods
- // instance variables
}
If we know partial implementation then we need to use abstract class.
ex:
----
abstract class Plan
{
//instance variable
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 Shape
{
public abstract void draw();
}
class Rectangle extends Shape
{
public void draw()
{
System.out.println("I draw rectangle");
}
}
class Test
{
public static void main(String[] args)
{
Rectangle rect=new Rectangle();
rect.draw();
}
}
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) User-defined API
-------------------
API created by the user based on the application requirements.
1) Predefined packages
2) Userdefined packages
1) Predefined packages
------------------------
Built-In packages are called predefined packages.
ex:
java.lang
java.io
java.util
java.time
java.util.stream
java.text
java.sql
javax.servlet
and etc.
2) Userdefined packages
------------------------
Packages which are created by the user based on the application
requirements are called userdefined packages.
ex:
package com.google.www;
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 folder
Singleton class
================
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.
If we call any method by using class name and that method returns same
class object is called singleton class.
ex:
Calendar c=Calendar.getInstance();
LocalDate d=LocalDate.now();
LocalTime t=LocalTime.now();
ex:
---
class Singleton
{
static Singleton singleton=null;
//private constructor
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();
System.out.println(s1.hashCode());
Singleton s2=Singleton.getInstance();
System.out.println(s2.hashCode());
}
}
Inner classes
==============
Sometimes we will declare a class inside another class such concept is
called inner class.
ex:
class Outer
{
class Inner
{
-
- //code to be execute
-
}
}
}
Note:
-----
If we compile above program we will get two .class files i.e
Outer.class and Outer$Inner.class.
ex:
---
class Outer
{
class Inner
{
//non-static method
public void m1()
{
System.out.println("Inner-M1 Method");
}
}
}
Inner class does not allow static declaration.
ex:
---
class Outer
{
class Inner
{
//static method
public static void m1()
{
System.out.println("Inner-M1 Method");
}
}
Enum
======
Enum concept introduced in 1.5v.
Enum is a group of named constants.
Using enum we can create our own datatype called enumerated datatype.
syntax:
------
enum enumtype_name
{
value1,value2,.....,valueN
}
ex:
----
enum Months
{
JAN,FEB,MAR
}
ex:
{ {
JAN,FEB,MAR ==> public static final Months JAN=new
Months();
} public static final Months FEB=new
Months();
public static final Months MAR=new
Months();
}
ex:
---
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months m=Months.MAR;
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 number.
ex:
----
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months[] m=Months.values();
ex:
---
enum Week
{
MON,TUE,WED,THU,FRI,SAT,SUN;
Week()
{
System.out.println("constructor");
}
}
class Test
{
public static void main(String[] args)
{
Week w=Week.TUE;
}
}
ex:
---
enum Drinks
{
COLA,CAMPA,PEPSI;
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
-----------
There are two ways to create object for wrapper classes. One will take
corresponding primitive as an argument and another takes 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)
{
Boolean b1=new Boolean(true);
System.out.println(b1);
ex:
---
class Test
{
public static void main(String[] args)
{
Character ch=new Character('a');
System.out.println(ch); //a
}
}
Utility methods
===============
1) parseXxx()
-------------
It is used to convert string type to primitive type.
ex:
--
class Test
{
public static void main(String[] args)
{
String str="23";
int i=Integer.parseInt(str);
System.out.println(i); //23
long l=Long.parseLong(str);
System.out.println(l); //23
float f=Float.parseFloat(str);
System.out.println(f); //23.0
double d=Double.parseDouble(str);
System.out.println(d); //23.0
}
}
2) toString()
--------------
It is used to convert wrapper object to String type.
ex:
---
class Test
{
public static void main(String[] args)
{
Integer i=new Integer(10);
System.out.println(str); //10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(str); // C.T.E
}
}
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;
ex:
class Test
{
public static void main(String[] args)
{
char ch='a';
String s=Character.toString(ch);
System.out.println(s);
}
}
1) Immutable object
2) Mutable object
1) Immutable object
--------------------
After object creation if we perform any changes then for our 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 the required
changes will be reflected to same object only 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 change a new object will be created such
behaviour is called immutability of an object.
Diagram: java34.1
case2:
------
What is the difference between == and .equals() method?
==
----
It is a comparision operator which always return boolean value.
ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("ihub");
String s2=new String("ihub");
System.out.println(s1==s2);//false
}
}
.equals()
-----------
It is a method present in String class which always returns boolean
value.
ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("ihub");
String s2=new String("ihub");
System.out.println(s1.equals(s2));//true
}
}
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
only.
Diagram: java34.2
Object creation in SCP area is always optional.
First JVM will check is there object is created with same content or
not. If it is created then it 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.
Even though SCP area objects do not have any object reference , garbage
collection can't access them.
Diagram: java34.3
Diagram: java34.4
input:
hello
output:
5
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";
System.out.println(str.length());//5
}
}
input:
ihub
output:
i
h
u
b
ex:
class Test
{
public static void main(String[] args)
{
String str="ihub";
//reading characters
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
System.out.println(ch);
}
}
}
input:
ihubtalent
output:
IHUBTALENT
ex:
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
str=str.toUpperCase();
System.out.println(str);
}
}
input:
IHUBTALENT
output:
ihubtalent
ex:
---
class Test
{
public static void main(String[] args)
{
String str="IHUBTALENT";
str=str.toLowerCase();
System.out.println(str);
}
}
Q) Write a java program to concatinate two strings?
input:
ihub
talent
output:
ihubtalent
ex:
---
class Test
{
public static void main(String[] args)
{
String str1="ihub";
String str2="talent";
String result=str1.concat(str2);
System.out.println(result);
}
}
input:
ihubtalent
qualitythought
output:
Both are not equals
ex:
class Test
{
public static void main(String[] args)
{
String str1="ihubtalent";
String str2="qualitythought";
if(str1.equals(str2))
System.out.println("Both are equals");
else
System.out.println("Both are not equals");
}
}
input:
str = bhaskar
ch = 'a'
output:
2
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
int index=str.indexOf(ch);
System.out.println(index);
}
}
input:
str = bhaskar
ch = 'a'
output:
5
ex:
---
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
int index=str.lastIndexOf(ch);
System.out.println(index);
}
}
input:
I_hu@bTa$len#t12
output:
IhubTalent12
ex:
----
class Test
{
public static void main(String[] args)
{
String str="I_hu@bTa$len#t12";
str = str.replaceAll("[^A-Za-z0-9]","");
System.out.println(str);
}
}
input:
I_hu@bTa$len#t12
output:
_@$#
ex:
class Test
{
public static void main(String[] args)
{
String str="I_hu@bTa$len#t12";
str = str.replaceAll("[A-Za-z0-9]","");
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";
String newStr=str.substring(4);
System.out.println(newStr);
}
}
input:
ihubtalent
output:
hub
ex:
---
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
String newStr=str.substring(1,4);
System.out.println(newStr);
}
}
input:
str = javaisindependent
word = platform
index = 6
output:
javaisplatformindependent
ex:
---
class Test
{
public static void main(String[] args)
{
String str ="javaisindependent";
String word ="platform";
int index = 6;
String word1=str.substring(0,index);
String word2=str.substring(index,str.length());
System.out.println(word1+word+word2);
}
}
input:
str = ihubtalent
cnt = 2
output:
ubtalentih
ex:
--
class Test
{
public static void main(String[] args)
{
String str ="ihubtalent";
int cnt=2;
String word1=str.substring(cnt,str.length());
String word2=str.substring(0,cnt);
System.out.println(word1+word2);
}
}
input:
hello
output:
olleh
ex:
class Test
{
public static void main(String[] args)
{
String str="hello"; // h e l l o
String rev="";
for(int i=str.length()-1;i>=0;i--)
{
rev+=str.charAt(i);
}
System.out.println(rev);
}
}
approach2
----------
class Test
{
public static void main(String[] args)
{
String str="hello";
char[] carr=str.toCharArray(); // h e l l o
String rev="";
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
System.out.println(rev);
}
}
input:
racar
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="";
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
ex:
class Test
{
public static void main(String[] args)
{
String str="This is java class";
//reading reverse
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";
String rev="";
//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
//add space
rev+=" ";
}
System.out.println(rev);
}
}
input:
google
output:
og
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 current=Character.toString(str.charAt(i));
if(uniques.contains(current))
{
if(!duplicates.contains(current))
{
duplicates+=current;
continue;
}
}
uniques+=current;
}
System.out.println(duplicates);
}
}
input:
google
output:
gole
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 current=Character.toString(str.charAt(i));
if(uniques.contains(current))
{
if(!duplicates.contains(current))
{
duplicates+=current;
continue;
}
}
uniques+=current;
}
System.out.println(uniques);
}
}
input:
ihubtalentinstitute
output:
t is repeating for 5 times
ex:
---
class Test
{
public static void main(String[] args)
{
String str="ihubtalentinstitute";
int maxCount=0;
char element=' ';
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;
element=str.charAt(i);
}
}
System.out.println(element+" is repeating for "+maxCount+"
times");
}
}
input:
i hub tale nt
output:
ihubtalent
ex:
class Test
{
public static void main(String[] args)
{
String str="i hub tale nt";
str=str.replaceAll("\\s","");
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:
silent
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:
A1B2C3D4
output:
ABBCCCDDDD
ex:
---
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 j=Character.getNumericValue(str.charAt(i));
for(int k=1;k<j;k++)
{
System.out.print(str.charAt(i-1));
}
}
}
}
}
input:
This is java Class for Student
output:
This Class Student
ex:
--
class Test
{
public static void main(String[] args)
{
String str="This is java Class for Student";
for(String s:sarr)
{
if(s.charAt(0)>='A' && s.charAt(0)<='Z')
{
System.out.print(s+" ");
}
}
}
}
input:
Now is raining where my Umbrella
output:
is umbrella
ex:
class Test
{
public static void main(String[] args)
{
String str="Now is raining where my Umbrella";
str=str.toLowerCase();
for(String s:sarr)
{
char ch=s.charAt(0);
input:
umbrella
output:
u e a
ex:
class Test
{
public static void main(String[] args)
{
String str="umbrella";
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
}
}
input:
umbrella
output:
3
ex:
class Test
{
public static void main(String[] args)
{
String str="umbrella";
int cnt=0;
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
input:
XYZ
output:
XY
XZ
YX
YZ
ZX
ZY
ex:
class Test
{
public static void main(String[] args)
{
String str="XYZ";
for(int i=0;i<str.length();i++)
{
for(int j=0;j<str.length();j++)
{
if(i!=j)
{
System.out.println(str.charAt(i)+""+str.charAt(j));
}
}
}
}
}
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[] carr,int fi)
{
if(fi==carr.length-1)
{
System.out.println(carr);
return;
}
for(int i=fi;i<carr.length;i++)
{
swap(carr,fi,i);
permutation(carr,fi+1);
swap(carr,fi,i);
}
}
//callie method
public static void swap(char[] carr,int fi,int i)
{
//swapping logic
char temp=carr[fi];
carr[fi]=carr[i];
carr[i]=temp;
}
}
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(longestCommSubsequence(str1,str2));
}
//callie method
public static int longestCommSubsequence(String s1,String s2)
{
return solve(s1,s2,0,0);
}
//callie method
public static int solve(String s1,String s2,int i,int j)
{
if(i==s1.length())
return 0;
if(j==s2.length())
return 0;
int ans=0;
if(s1.charAt(i)==s2.charAt(j))
{
ans=1+solve(s1,s2,i+1,j+1);
}
else
{
ans=Math.max(solve(s1,s2,i+1,j),solve(s1,s2,i,j+1));
}
return ans;
}
}
StringBuffer
==============
If our content change frequently then it is never recommanded to go
with String object because for every change a new object will be
created.
constructor
-----------
1) StringBuffer sb=new StringBuffer();
--------------------------------------
It will create empty StringBuffer object with default initial capacity
of 16.
syntax:
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("abcdefgjijklmnop");
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
}
}
ex:
capacity = s.length()+16;
ex:
---
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("ihub");
System.out.println(sb.capacity()); //4+16=20
}
}
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 plaindrome 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:
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)).append(count);
count=1;
}
}
System.out.println(sb.toString());
}
}
input:
5 8 2
2 6
output:
15132 (582*26)
ex:
class Test
{
public static void main(String[] args)
{
int[] arr1={5,8,2};
int[] arr2={2,6};
//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:
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);
}
System.out.println(count);
}
input:
1106
output:
AAJF
ex:
class Test
{
public static void main(String[] args)
{
String str="1106";
//caller method
System.out.println(encodeString(str));
}
//callie method
public static String encodeString(String str)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<str.length();i++)
{
int n=Character.getNumericValue(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));
}
return sb.toString();
}
StringBuilder
===============
StringBuilder is exact same as StringBuffer with following differences.
StringBuffer StringBuilder
------------------- ----------------
Every method present in StringBuffer is No method present in
StringBuilder is
synchronized. synchronized.
Note:
-----
If our content not change frequently then we need to use String.
StringTokenizer
=================
StringTokenizer is a class which is present in java.util package.
syntax:
------
StringTokenizer st=new StringTokenizer(String
str,RegularExpression regEx);
ex:
public boolean hasMoreTokens()
public String nextToken()
public boolean hasMoreElements();
public Object 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()); // 4
}
}
Here default regular expression is space.
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()); // 4
}
}
ex:
---
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);
}
}
}
Assignment
===========
Q) Write a java program to display palindrome strings?
input:
racar is madam for bit
output:
racar madam
ex:
---
class Test
{
public static void main(String[] args)
{
String str="racar is madam for bit";
//for each
for(String s:sarr)
{
StringBuffer sb=new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()))
{
System.out.print(s+" ");
}
}
}
}
Assignment
===========
Q) Write a java program to decode the string?
input:
AAJF
output:
1106
Exception Handling
===================
Exception
---------
Exception is a problem for which we can provide solution
programmatically.
Exception will raise due to syntax errors.
ex:
FileNotFoundException
ArithmeticException
IllegalArgumentException
Error
------
Error is a problem for which we can't provide solution
programmatically.
Error will raise due to lack of system resources.
ex:
LinkageError
OutOfMemoryError
StackOverFlowError
1) Smooth termination
----------------------
During the program execution suppose if we are not getting any
interruption 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!");
}
}
1) Abnormal termination
----------------------
During the program execution suppose if we are getting some
interruptions 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 otherwiser our
program will terminates abnormally.
Exception
===========
It is a unwanted, expected event which disturbs normal flow of our
program.
1) Predefined exceptions
2) Userdefined exception
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 are called
checked exceptions.
ex:
EOFException
FileNotFoundException
InterruptedException
ex:
ArithmeticException
ClassCastException
IllegalArgumentException
Diagram: java38.1
If any checked exception raised in our program we must and should
handle that exception by using try and catch block.
try block
==========
It is a block which contains risky code.
If any exception raise in try block then try block won't be executed.
catch block
=============
It is a block which contains error handling code.
A catch block will take exception name as a parameter and that name
must match with exception class name.
syntax:
-------
try
{
- // Risky Code
}
catch(ArithmeticException ie)
{
- // 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:2
-----
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:3
----
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:4
-----
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 block then order of catch blocks
are 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 is used to display name of the exception ,description of the
exception and line number of the exception.
2) toString()
--------------
It is used to display name of the exception and description of the
exception.
3) getMessage()
---------------
It is used to 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 recommended to maintain cleanup code in try block because
if any exception raise in try block then try block won't be executed.
But we need a place where we can maintain cleanup code and it should
execute irrespective of
exception raise 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:2
----
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:3
-----
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
System.out.println(10/0);
System.out.println("stmt2");
}
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
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
finally
{
System.out.println("finally-block");
}
}
}
final
------
It is a modifier which is applicable for variables ,methods and
classes.
If we declare any variable as final then reinitialization 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 should execute
irrespective of exception raised or not.
finalize
---------
It is a method called by garbage collector just before destroying an
object for cleanup activity.
throw Statement
=================
Sometimes we will create exception objects 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)
{
System.out.println(10/0);
}
}
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 (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
ex:
---
class Test
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(5000);
System.out.println("Welcome to Java");
}
}
2) Userdefined exceptions
=========================
Exceptions which are created by the user based on the application
requirements are called
customized exceptions or userdefined exceptions.
ex:
NotInterestInJavaException
NoPracticeException
NoJobException
EligileException
NotEligibleException
ex:
---
import java.util.Scanner;
class EligibleException extends RuntimeException
{
EligibleException(String s)
{
super(s);
}
}
class NotEligibleException extends RuntimeException
{
NotEligibleException(String s)
{
super(s);
}
}
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 NotEligibleException("U r not eligible to
vote");
else
throw new EligibleException("U r eligile to vote");
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
//System.out.println(10/0);
Thread.currentThread().setPriority(15);
}
catch (IllegalArgumentException | NullPointerException |
ArithmeticException e)
{
e.printStackTrace();
}
}
}
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)
{
File f=new File("abc.txt");
System.out.println(f.exists());//false
}
}
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
}
}
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();
System.out.println("Please check the location");
}
}
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:1
-------
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:2
----------
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");
fr.close();
}
}
While reading the data by using FileReader object ,we need to read
character
by character which is not convenient to the programmer.
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);
ex:
FileWriter fw=new FileWriter("bbb.txt");
BufferedWriter bw=new BufferedWriter(fw);
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
{
char[] ch={'a','b','c'};
bw.write(ch);
bw.newLine();
bw.write("bhaskar");
bw.newLine();
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"));
String line=br.readLine();
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
or
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(100);// d
pw.println(100);// 100
pw.print('a');
pw.println(true);
pw.println("hi");
pw.println(10.5d);
pw.flush();
pw.close();
System.out.println("Please check the location");
}
}
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
java Test Alan
2)BufferedReader class
--------------------------
BufferedReader class present in java.io package.
ex:
BufferedReader br=
new BufferedReader
(new InputStreamReader(System.in));
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Welcome : "+name);
}
}
3)Console class
================
Console class present in java.io package.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
Console c=System.console();
System.out.println("Welcome : "+name);
}
}
4)Scanner class
==================
Scanner class present 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);
Generics
=========
Arrays are typesafe. We can give guarantee that what type of elements
are present in array.
ex:
String[] sarr=new String[5];
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[5];
sarr[0]="hi";
sarr[1]="hello";
sarr[2]="bye";
-
-
String value=sarr[0];
Collections are not typesafe. We can't give guarantee that what type of
elements are present in
Collections.
ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("hello");
al.add(10);
ex:
java.util package
===================
Arrays Collections
------------- ----------------
It is a collection of homogeneous It is a collection of
Data elements. homogeneous and hetrogeneous
Data elemnets
Arrays can hold primitive types and Collections can hold only
Object types. object types.
Collection Framework
=======================
Collection framework defines several classes and interfaces to
represent group of individual objects.
Collection
============
It is a root interface for entire Collection Framework.
ex:
cmd> javap java.util.Collection
ex:
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator<E> iterator();
public abstract java.lang.Object[] toArray();
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection<?>);
public abstract boolean addAll(java.util.Collection<? extends
E>);
public abstract boolean removeAll(java.util.Collection<?>);
and etc..
Collection Collections
----------- ------------
input:
ball cat dog apple elephant
output:
apple ball cat dog elephant
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="ball cat dog apple elephant";
Collections.sort(al);
}
}
1.List
======
It is a child interface of Collection interface.
Diagram: java40.1
i)ArrayList
==========
The underlying data structure is resizable array or growable array.
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++)
{
String s=al.get(i);
System.out.println(s);
}
}
}
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");
al.add(1,"gogo");
System.out.println(al); //[one,gogo,two,three]
System.out.println(al.contains("gogo")); // true
al.remove("gogo");
System.out.println(al);//[one,two,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);
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<String> list=Arrays.asList("one","two","three","four");
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,3,9,1,4);
ii)LinkedList
============
The underlying data structure is doubly LinkedList.
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");
ll.addFirst("gogo");
ll.addLast("jojo");
System.out.println(ll);//[gogo,one,three,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]
}
}
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]
ll2.addAll(ll1);
System.out.println(ll2);//[raja,one,two,three]
System.out.println(ll2.containsAll(ll1)); // true
ll2.removeAll(ll1);
System.out.println(ll2);//[raja]
}
}
iii)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.removeElementAt(5);
System.out.println(v);//[1,2,3,4,5,7,8,9,10]
v.insertElementAt(100,5);
System.out.println(v);
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(5);
System.out.println(v);//[1,2,3,4,5,7,8,9,10]
v.add(5,100);
System.out.println(v);
v.clear();
System.out.println(v); //[]
}
}
ArrayList Vector
----------- --------
No method is synchronized All methods are synchronized.
ArrayList LinkedList
------------- ----------
Array list is better for sorting Linked list is better for manipulating
And accessing data. Data.
The memory location for the The memory location for the elements
Elements of an ArrayList is of an LinkedList is not contiguous.
Contiguous.
iv)Stack
========
It is a child class of Vector class.
If we depends upon Last In First Out order then we need to use Stack.
constructor
----------
Stack s=new Stack();
methods
-------
1) push(Object o)
-----------------
It is used to push the element in a stack.
2) pop()
---------
It is used to pop the element from stack.
3) peek()
---------
It returns toppest element from stack.
4) isEmpty()
-----------
It is used to check stack is empty or not.
5) Search(Object o)
-------------------
It will return offset value if element is 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("Z")); // -1
System.out.println(s.search("A"));// 2
}
}
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: java41.1
i)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("nine");
hs.add("one");
hs.add("six");
System.out.println(hs);//[nine, six, one]
hs.add("one");
System.out.println(hs);//[nine, six, one]
hs.add(10);
System.out.println(hs);//[nine, six, one, 10]
hs.add(null);
System.out.println(hs);//[null, nine, six, one, 10]
}
}
ii)LinkedHashSet
================
LinkedHashSet is a child class of HashSet class.
ex:
HashSet LinkedHashSet
----------- ---------------
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)
{
LinkedHashSet lhs=new LinkedHashSet();
lhs.add("nine");
lhs.add("one");
lhs.add("six");
System.out.println(lhs);//[nine, one, six]
lhs.add("one");
System.out.println(lhs);//[nine, one, six]
lhs.add(10);
System.out.println(lhs);//[nine, one, six, 10]
lhs.add(null);
System.out.println(lhs);//[nine, one, six, 10, null]
}
}
iii)TreeSet
============
The underlying data structure is Balanced Tree.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(3);
System.out.println(ts);//[1, 3, 5, 10]
ts.add(1);
System.out.println(ts);//[1, 3, 5, 10]
//ts.add("hi");
//System.out.println(ts); // R.E ClassCastException
//ts.add(null);
//System.out.println(ts); // R.E NullPointerException
}
}
Comparable
-----------
Comparable is an interface which is present in java.lang package.
ex:
obj1.compareTo(obj2)
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.
ex:
public int compare(Object obj1,Object obj2)
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>(newMyComparator());
ts.add(10);
ts.add(1);
ts.add(5);
System.out.println(ts);
}
}
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);
System.out.println(ts);
}
}
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;
}
}
3.Map
======
It is not a child interface of Collection interface.
Diagram: java42.1
HashMap
========
The underlying data structure is Hashtable.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("one","raja");
hm.put("six","alan");
hm.put("ten","jose");
hm.put("four","nancy");
System.out.println(hm);//{six=alan, four=nancy, one=raja,
ten=jose}
hm.put("one","gogo");
System.out.println(hm);//{six=alan, four=nancy, one=gogo,
ten=jose}
hm.put(1,100);
System.out.println(hm);//{1=100, six=alan, four=nancy,
one=gogo, ten=jose}
hm.put(null,null);
System.out.println(hm);//{null=null, 1=100, six=alan,
four=nancy, one=gogo, ten=jose}
}
}
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("one","raja");
hm.put("six","alan");
hm.put("ten","jose");
hm.put("four","nancy");
Set s=hm.keySet();
System.out.println(s);//[six, four, one, ten]
Collection c=hm.values();
System.out.println(c);//[alan, nancy, raja, jose]
Set s1=hm.entrySet();
System.out.println(s1);//[six=alan, four=nancy, one=raja,
ten=jose]
}
}
LinkedHashMap
===============
It is a child class of HashMap class.
HashMap LinkedHashMap
------------- ---------------
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)
{
LinkedHashMap lhm=new LinkedHashMap();
lhm.put("one","raja");
lhm.put("six","alan");
lhm.put("ten","jose");
lhm.put("four","nancy");
System.out.println(lhm);//{one=raja, six=alan, ten=jose, four=nancy}
lhm.put("one","gogo");
lhm.put(null,null);
System.out.println(lhm);//{one=gogo, six=alan, ten=jose, four=nancy,
1=100, null=null}
}
}
TreeMap
=========
The underlying datastructure is RED BLACK TREE.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(10,"ten");
tm.put(1,"one");
tm.put(5,"five");
System.out.println(tm); //{1=one, 5=five, 10=ten}
tm.put(1,"gogo");
System.out.println(tm); //{1=gogo, 5=five, 10=ten}
tm.put(4,null);
System.out.println(tm); //{1=gogo, 4=null, 5=five, 10=ten}
tm.put(null,"four");
System.out.println(tm); //R.E NullPointerException
}
}
Hashtable
=========
The underlying data structure is Hashtable.
Keys can't be duplicate but values can be duplicate.
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
Hashtable ht=new Hashtable();
ht.put(10,"ten");
ht.put(1,"one");
ht.put(5,"five");
System.out.println(ht); //{10=ten, 5=five, 1=one}
ht.put(1,"gogo");
System.out.println(ht); //{10=ten, 5=five, 1=gogo}
ht.put("six",6);
System.out.println(ht); //{10=ten, six=6, 5=five, 1=gogo}
//ht.put(4,null);
//System.out.println(ht); // R.E NullPointerException
//ht.put(null,"four");
//System.out.println(ht); // R.E NullPointerException
}
}
Interview Questions
======================
input:
{[()]}
output:
It is a balanced string
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="{[()]}";
//caller method
if(isBalanced(str.toCharArray()))
System.out.println("It is a balanced string");
else
System.out.println("It is not a balanced string");
}
//callie method
public static boolean isBalanced(char[] carr)
{
Stack<Character> s=new Stack<Character>();
return s.isEmpty();
}
}
input:
1 2 2 3 3 3 4 4 4 4
output:
1 2 3 4
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
int[] arr={1,2,2,3,3,3,4,4,4,4};
Set<Integer> set=new LinkedHashSet<Integer>();
for(int i:arr)
{
set.add(i);
}
ex:
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date1=LocalDate.of(2024,1,26);
LocalDate date2=LocalDate.of(2024,8,15);
if(date1.compareTo(date2)>0)
System.out.println("date1 is biggest");
else if(date1.compareTo(date2)<0)
System.out.println("date2 is biggest");
else
System.out.println("Both are same");
}
}
input:
this is is java java class
output:
this=1 is=2 java=2 class=1
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="this is is java java class";
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();
Map<Character,Integer> map=new
LinkedHashMap<Character,Integer>();
1) Enumeration
2) Iterator
3) ListIterator
1) Enumeration
---------------
Enumeration is used to read objects one by one from legacy Collection
objects.
ex:
Enumeration e=v.elements();
ex:
public boolean hasMoreElements()
public Object nextElement()
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);
}
}
}
2) Iterator
--------------
It is used to read objects one by one from any Collection object.Hence
it is a universal cursor.
ex:
Iterator itr=al.iterator();
ex:
public boolean hasNext()
public Object next()
public void remove()
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)
System.out.println(i+" ");
else
itr.remove();
}
System.out.println(al);//[2,4,6,8,10]
}
}
Using Iterator interface we can perform read and remove operation but
not adding and replacement of new object.
3) ListIterator
----------------
ListIterator is a child interface of Iterator interface.
ex:
ListIterator litr=al.listIterator();
ex:
public abstract boolean hasNext()
public abstract Object next()
public abstract boolean hasPrevious()
public abstract Object previous()
public abstract int nextIndex()
public abstract int previousIndex()
public abstract void remove()
public abstract void add(E)
public abstract void set(E)
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("bala");
al.add("nag");
al.add("chiru");
System.out.println(al);//[venki,bala,nag,chiru]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
System.out.println(s);
}
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("bala");
al.add("nag");
al.add("chiru");
System.out.println(al);//[venki,bala,nag,chiru]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("bala"))
{
litr.remove();
}
}
System.out.println(al);//[venki,nag,chiru]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("bala");
al.add("nag");
al.add("chiru");
System.out.println(al);//[venki,bala,nag,chiru]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.add("chaitanya");
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("bala");
al.add("nag");
al.add("chiru");
System.out.println(al);//[venki,bala,nag,chiru]
ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("chiru"))
{
litr.set("ramcharan");
}
}
System.out.println(al);//[venki,bala,nag,ramcharn]
}
}
Diagram: java43.1
Multithreading
================
Thread
------
A Thread is a light weight sub process.
ex:
class is one thread
constructor is one thread
block is one thread
Process
-------
A process is a collection of threads.
ex:
typing the notes in editor is one process
taking a class using zoom meeting is one process
downloading a file from internet is one process
Multitasking
=============
Executing several task simultenously such concept is called
multitasking.
Multithreading
================
Executing several threads simultenously such concept is called
multithreading.
3) To develop animations.
//start a thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
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");
}
}
}
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:
class MyThread extends Thread
{
}
class Test
{
public static void main(String[] args)
{
//instantiate a thread
MyThread t=new MyThread();
//new thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
ex:
class MyThread extends Thread
{
public void run(int i)
{
System.out.println("int-arg method");
}
public void run()
{
System.out.println("0-arg method");
}
}
class Test
{
public static void main(String[] args)
{
//instantiate a thread
MyThread t=new MyThread();
//new thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
case5: Life cycle of a thread
------------------------------
Diagram: java43.2
//new thread
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
1) yield()
2) join()
3) sleep()
1) yield()
-----------
It will pause current execution thread and gives the change to other
threads having same priority.
ex:
public static native void yield()
Diagram: java44.1
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 use join() method.
ex:
public final void join()throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(int ns)throws InterruptedException
Diagram: java44.2
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)throws InterruptedException
{
MyThread t=new MyThread();
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 will throw one checked exception so we must and should
handle that exception by using try and catch block or by 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: java44.3
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
try
{
Thread.sleep(3000);
}
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");
}
}
}
ex:
---
class MyThread extends Thread
{
}
class Test
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName()); //main
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. Explicitly provided by the
programmer or automatically generated by JVM.
ex:
---
class MyThread extends Thread
{
}
class Test
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority());
//5
System.out.println(Thread.currentThread().getPriority());//10
t.setPriority(4);
System.out.println(t.getPriority());//4
Deamon Thread
=============
Deamon Thread is a service provider thread which provides services to
user threads.
There are many daemon thread are running internally such as Garbage
Collector, Finalizer and etc.
ex:
--
1) Data inconsistency
2) Thread interference
ex:
----
class Table
{
public 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();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
synchronization
================
A synchronized keyword is applicable for methods and blocks.
When one thread is executing synchronized method then other threads are
not allowed to execute other synchronized methods in a same object
concurently.But other threads are allowed to execute non-synchronized
method concurently.
ex:
class Table
{
synchronized 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 Test
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
synchronized block
====================
If we want to perform synchronization on specific resource of a program
then we need to use
synchronization.
ex:
If we have 100 lines of code and if we want to perform
synchronization only for
10 lines then we need to use synchronized block.
ex:
class Table
{
void printTable(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}//sync
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class Test
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
3)Static synchronization
=====================
In static synchronization the lock will be on class but not on object.
If we declare any static method as synchronized then it is called
static synchronization method.
ex:
class Table
{
static synchronized 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
{
class Test
{
public static void main(String[] args)
{
t1.start();
t2.start();
}
}
Inter-Thread Communication
==========================
Two threads can communicate with one another by using wait(),notify()
and notifyAll() method.
The Thread which is expecting updations it has to wait() method and the
thread which is performing updations it has to call notify() method.
ex:
class MyThread extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("Child Thread started calculation");
for(int i=1;i<=10;i++)
{
total=total+i;
}
System.out.println("Child thread giving notification");
this.notify();
}
}
}
class Test
{
public static void main(String[] args)throws InterruptedException
{
MyThread t=new MyThread();
t.start();
synchronized(t)
{
sSystem.out.println("Main Thread waiting for updating");
t.wait();
System.out.println("Main -Thread got notification ");
System.out.println(t.total);
}
}
}
DeadLock in java
===============
DeadLock will occur in a suitation when one thread is waiting to access
object lock which is acquired by another thread and that thread is
waiting
to access object lock which is acquired by first thread.
Here both the threads are waiting release the thread but no body will
release such situation is called DeadLock.
ex:
class Test
{
public static void main(String[] args)
{
final String res1="hi";
final String res2="bye";
t1.start();
t2.start();
}
}
Drawbacks of multithreading
======================
1)DeadLock
2)Thread Starvation
Java 8 Features
==================
Functional interface
====================
Functional interface introduced in Java 8 version.
ex:
a = f1(){}
f1(f2(){})
{
}
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("From M1 Method");
}
};
a.m1();
}
}
Lamda Expression
================
Lamda expression introduced in Java 8 version.
ex:
Java Method
------------
public void m1()
{
System.out.println("Hello World");
}
Lamda expression
----------------
()->
{
System.out.println("Hello World");
};
ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
A a=()->
{
System.out.println("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,30));
}
}
ex:
----
interface A
{
public abstract void m1();
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
a.m2();
}
}
ex:
---
interface A
{
public abstract void m1();
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
a.m2();
}
}
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();
}
}
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();
Left.super.m1();
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}
ex:
---
interface A
{
static void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A.m1();
}
}
Stream API
==========
Stream is an interface which is present in java.util.stream package.
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(5,7,1,3,8,4,9);
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(5,7,1,3,8,4,9);
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(5,7,1,3,8,4,9);
long odd=list.stream().filter(i->i%2!=0).count();
System.out.println(odd);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(5,7,1,3,8,4,9);
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(5,7,1,3,8,4,9);
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(5,7,1,3,8,4,9);
List<Integer>
newList=list.stream().sorted(Comparator.reverseOrder()).collect(Collect
ors.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(5,7,1,3,8,4,9);
long minimum=list.stream().min((i1,i2)-
>i1.compareTo(i2)).get();
System.out.println(minimum);
}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(5,7,1,3,8,4,9);
long maximum=list.stream().max((i1,i2)-
>i1.compareTo(i2)).get();
System.out.println(maximum);
}
}
forEach() Method
==================
A forEach() method introduced in Java 8 version.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(5,7,1,3,8,4,9);
list.forEach(element-> System.out.print(element+" "));
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Map<Integer,String> map=new LinkedHashMap<Integer,String>();
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
map.forEach((key,value)->
System.out.println(key+"="+value));
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(5,7,1,9,2,3);
list.forEach(System.out::println);
}
}
Interview Question
==================
import java.util.*;
import java.util.stream.*;
class Employee
{
private int empId;
private String empName;
private double empSal;
//parameterized constructor
Employee(int empId,String empName,double empSal)
{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}
list.add(new Employee(104,"Jack",4000d));
list.add(new Employee(101,"Nancy",1000d));
list.add(new Employee(103,"Jose",3000d));
list.add(new Employee(102,"Linda",2000d));
List<Employee>
newList=list.stream().sorted(Comparator.comparingInt(Employee::getEmpId
)).collect(Collectors.toList());
newList.forEach(employee->
System.out.println(employee.getEmpId()
+" "+employee.getEmpName()+" "+employee.getEmpSal()));
}
}
import java.util.*;
import java.util.stream.*;
class Employee
{
private int empId;
private String empName;
private double empSal;
//parameterized constructor
Employee(int empId,String empName,double empSal)
{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}
list.add(new Employee(104,"Jack",4000d));
list.add(new Employee(101,"Nancy",1000d));
list.add(new Employee(103,"Jose",3000d));
list.add(new Employee(102,"Linda",2000d));
List<Employee>
newList=list.stream().sorted(Comparator.comparing(Employee::getEmpName)
).collect(Collectors.toList());
newList.forEach(employee->
System.out.println(employee.getEmpId()
+" "+employee.getEmpName()+" "+employee.getEmpSal()));
}
}
Garbage Collector
=================
It is a daemon thread which is responsible to destroy unused and
useless object from java.
1) System.gc()
2) Runtime.getRuntime().gc()
ex:
---
class Test
{
int i=10;
t1=null;
System.gc();
}
ex:
---
class Test
{
int i=10;
t1=null;
Runtime.getRuntime().gc();
}