0% found this document useful (0 votes)
6 views104 pages

Java Documents

The document provides a comprehensive overview of Full Stack Java Development, detailing both front-end and back-end technologies, including HTML5, CSS3, Java, and various frameworks. It covers programming languages, specifically Java and C, their characteristics, and differences, along with common interview questions and answers related to Java. Additionally, it discusses Java's internal architecture, features, naming conventions, and setup instructions for developing Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views104 pages

Java Documents

The document provides a comprehensive overview of Full Stack Java Development, detailing both front-end and back-end technologies, including HTML5, CSS3, Java, and various frameworks. It covers programming languages, specifically Java and C, their characteristics, and differences, along with common interview questions and answers related to Java. Additionally, it discusses Java's internal architecture, features, naming conventions, and setup instructions for developing Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Full Stack Java Development

(Full Stack Developer)


|
|---------------------------------------------------------------------|
FrontEnd Technologies BackEnd Technologies
(FrontEnd Developer) (BackEnd Developer)

> HTML5 > Core Java


> CSS3 > Advanced Java
> JavaScript > JDBC
> Bootstrap5 > Servlets
> ReactJS > JSP
> Oracle DB
> SQL
> PL/SQL
> Frameworks
> SpringBoot
> Microservices

Programming language
====================
1. A language which is used to communicate between user and computer is called
programming language.
2. Programming language acts like a mediator or interface between user and computer.
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)
C
===
Procedure oriented programming language.
Platform dependent programming language.
Case sensitive programming language.
Loosely typed checking language.
Middle level language (LOW + HIGH).

Interview Question
==================
Q) What is Java?
Java is a object oriented, platform independent, case sensitive, strongly typed checking,
high level, open source programming language developed by James Gosling in the year of 1995.
Q) What is the difference between Python and Java?

Python Java
-------- --------
1. It is developed by Guido Van Rossum. It is developed by James Gosling.
2. It is a product of Microsoft. It is a product of Oracle Corporation.
3. It is a scripting language. It is a object oriented programming anguage.
4. It is a interpreted language. It is a compiled language.
5. It contains PVM. It contains JVM.
(Python Virtual Machine) (Java Virtual Machine)
6. It is a dynamically typed language. It is a statically typed language.
7. Performance is low. Performance is high.
8. There is less securty. It is highly secured.

Note:
----
.py file -------------------------------------> computer
(High level language)

compile
.java file ------------------- .class file -------------> computer
(High level language) (Byte Code)

Note:
-----
.py file -------------------------------------> computer/Machine

.java file ---------------> .class file ----------> JRE


Escape Characters / Escape Sequences
=====================================
Escape characters are used to design the output in neat and clean manner.
Escape characters start with back slash (\) followed by a character.
ex:
\n
Mostly escape characters are placed inside the output statement.

ex:
System.out.println("\n");

We have following list of escape characters in java.

1) \n (New Line)
2) \t (Horizontal Tab)
3) \b (Backspace)
4) \r (Carriage Return)
5) \f (Form Feeding)
6) \\ (Back Slash)
7) \" (Double Quote)
8) \' (Single Quote)
and etc.

1) \n (New Line)
-----------------
class Akhil
{
public static void main(String[] args)
{
System.out.println("IHUB\nTALENT");
}
}
o/p:
IHUB
TALENT

2) \t (Horizontal Tab)
---------------------
class Anapati
{
public static void main(String[] args)
{
System.out.println("IHUB\tTALENT");
}
}
o/p:
IHUB TALENT
3) \b (Backspace)
------------------
class Anil
{
public static void main(String[] args)
{
System.out.println("IHUBTA\bLENT");
}
}
o/p:
IHUBTLENT

ex:
---
class Bharath
{
public static void main(String[] args)
{
System.out.println("IHUB\b\b\bTALENT");
}
}

o/p:
ITALENT

4) \r (Carriage Return)
-----------------------
class Bharani
{
public static void main(String[] args)
{
System.out.println("IHUB\rTALENT");
}
}
o/p:
TALENT

ex:
----
class Prabhas
{
public static void main(String[] args)
{
System.out.println("TALENT\rIHUB");
}
}
o/p:
IHUBNT

6) \\ (Back Slash)
-------------------
class Akshay
{
public static void main(String[] args)
{
System.out.println("IHUB\\TALENT");
}
}

o/p:
IHUB\TALENT

C program
=========
Q) Write a c program to display %d ?

void main()
{
clrscr();

printf("%%d"); // %d

getch();
}

7) \" (Double Quote)


--------------------
class Sadwika
{
public static void main(String[] args)
{
System.out.println("I love \"java\" programming");
}
}

o/p:
I love "java" programming

8) \' (Single Quote)


--------------------
class Hema
{
public static void main(String[] args)
{
System.out.println("I Love 'java' programming ");
System.out.println("I Love \'java\' programming ");
}
}
o/p:
I Love 'java' programming
I Love 'java' programming

Comments in Java
================
Comments are created for documentation purpose.
Comments are used to improve readability of our code.
It is highly recommanded to use comments in regular programming.
Diagram : java4.1
Comments will not display in output because they won't compiled by the compiler.
In java, we have two types of comments.

1) Single line comment


--------------------
It is used to comment a single line.
ex:
// comment here
2) Multiple line comment
------------------------
It is used to comment multiple lines.
ex:
/*
-
- comment here
-
*/

ex:
---
//class declaration
class Test
{

//main method
public static void main(String[] args)
{

//variable declaration
int sum=0;

//sum of 10 natural numbers logic


for(int i=1;i<=10;i++)
{
sum+=i;
}

//display the result


System.out.println(sum);
}
}

Interview Questions
====================
Q) How many modules are there in java?
There are three modules in java.
1) JSE/J2SE (Java Standard Edition)
2) JEE/J2EE (Java Enterprise Edition)
3) JME/J2ME (Java Micro Edition)
Q) What is the difference between JDK, JRE and JVM ?
JDK
----
JDK stands for Java Development Kit.
It is a installable software which consist Java Runtime Environment (JRE), Java Virtual Machine
(JVM),compiler (javac) , interpreter (java), an archiever (.jar) , document generator (javadoc)
and other tools needed for java application development.

JRE
----
JRE stands for Java Runtime Environment.
It provides very good environment to run java applications only.

JVM
----
JVM stands for Java Virtual Machine.
JVM is an interpreter which is used to execute our program line by line procedure.

Diagram: java4.2

Q) Java is a platform dependent or independent?


Java is a platform independent.
Diagram: java4.3
Q) JVM is platform dependent or independent?
JVM is platform dependent

Naming Conventions in Java


===========================
In java, uppercase letters will consider as different and lowercase letters consider as different.
Hence we consider java is a case sensitive programming language.
When JAVA is a case sensitive we must and should follow naming conventions.
ex:
classes
interfaces
variables
methods
keywords
packages
constants
classes
---------
In java, a class name must and should starts with uppercase letter and if it contains multiple
words then each inner word must starts with initcap.
ex:
predefined classes userdefined classes
---------------- -------------------
System Test
FileWriter ExampleApp
BufferedWriter DemoApp
PrintWriter InstituteApp
and etc. and etc.
interfaces
-----------
In java, an interface name must and should starts with uppercase letter and if it contains multiple
words then each inner word must starts with initcap.
ex:
predefined interfaces userdefined interfaces
-------------------- ----------------------
Runnable ITest
Serializable IExampleApp
ListIterator IDemoApp
Enumeration IMyProgram
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 starts with initcap.
ex:
predefined variables userdefined variables
------------------- ---------------------
length empId
out studName
err deptNo
in empSalary
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 initpcap.
ex:
predefined methods userdefined methods
------------------- -------------------
getClass() setDetails()
hashCode() getInfo()
toString() setBillDetails()
setPriority() getStudentInfo()
and etc. and etc.
keywords
--------
In java, all keywords we need to declare under lowercase letters only.
ex:
predefined keywords
------------------
public, if , else, static, void, do, while, break and etc.
packages
--------
In java, all packages we need to declare under lowercase letters only.
ex:
predefined packages userdefined packages
------------------- ---------------------
java.lang (default pkg) com.ihub.www
java.io com.google.www
java.util com.qt.www
java.util.stream and etc.
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 N=10;
MIN_PRIORITY
NORM_PRIORITY
MAX_VALUE
MIN_VALUE
and etc.

Java
====
Version : Java 8
Software : JDK 11
Creator : James Gosling
Vendor : Oracle Corporation
Website : https://www.oracle.com/in/java
Tutorials : www.javatpoint.com
www.javaus.com
www.tutorialspoint.com
www.w3school.com
and etc.
Download link :
https://drive.google.com/file/d/1GtRLHXK4y3s97BH2UcYiJPNBaROR1DBV/view?usp=drive_
link
Steps to setup environmental variables
======================================
step1: Make sure JDK 11 installed successfully.

step2: Copy "lib" directory from java_home folder.


ex:
C:\Program Files\Java\jdk-11\lib

step3: Paste "lib" directly in environmental variables.


ex:
right click to This PC --> properties --> advanced system settings -->
Environmental varibles --> user variables ---> click to new button -->
variable name : CLASSPATH
variable value : C:\Program Files\Java\jdk-11\lib; --> ok.

system variables --> click to new button -->


variable name : path
variable value : C:\Program Files\Java\jdk-11\bin --> ok --> ok --> ok.

step4: Check environmental setup done perfectly or not.


ex:
cmd> javap
cmd> java -version
Steps to develop first application in java
============================================
step1: Make sure JDK 11 installed successfully.

step2: Make sure environmental setup done perfectly.

step3: Create a "javaprog" folder in 'D' drive.

step4: Open the nodepad and type Hello World program.


ex:
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

step5: Save above program with same name as class name inside "javaprog" location.
step6: Open the command prompt from javaprog location.
step7: Compile above program by using below command.
ex:
javac Test.java
|
filename
step8: Run the above program by using below command.
ex:
java Test
|
classname

Internal Architecture of JVM


===========================
Diagram: java7.1
Java program contains java code instructions.Once if we compile, java code instructions convert
to byte code instructions in .class file.

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 property it will refuse the execution.If they are property then it will allocates the
memory.

We have five memories in java.


1) Method Area
-------------
Method area 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
---------------
Java methods execute 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 address of an instructions.
5) Native method stack
------------------------
Java methods execute in method area.
Similarly native methods execute in native method stack.
But native methods we can't execute directly we required a program called Native method
interface.
Execution Engine
------------------
Executione engine contains interpreter and JIT compiler.
Whenever JVM loads byte code instructions from .class file , it uses interpreter and JIT compiler
simultenously.
Interpreter is used to execute our program line by line procedure.
JIT compiler is used to increase the execution speed of our program.
Finally , JVM converts byte code to machine code.
Interview Questions
==================
Q) What is native method in java?
A method which is developed by using some other language is called native method.
Q) How many memories are there in java?
We have five memories in java.
1) Method area
2) Heap
3) Java Stack
4) PC Register
5) Native method Stack
Q) What is JIT compiler?
It is a part of a JVM which is used to increase the execution speed of our program.

Q) How many classloaders are there in java?


We have three predefined classloader in java.
1) Bootstrap classloader
2) Extension classloader
3) Applicaiton/System classloader
History of Java
================
Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]). History of even naming of the Java is very interesting.

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 is renamed to Green project.

James Gosling, Mike Sheradin and Patrick Naughton were there to develop the project. They met
in a place called Aspan/Colarado to start the work with Graphic System.James Gosling thought
to use C and C++ languages to develop the project.But the problem what they have faced is C
and C++ languages are system dependent. Then James Gosling decided why don't we create our
own programming language which is system independent.

In 1991, they have developed a programming language called an OAK.There was an OAk tree in
front of his office. James Gosling used this name as Oak represents solidarity and Oak tree is the
national tree of multiple countries like USA, France, Romania etc. But OAk technologies already
had OAk as a trademark and James team had to brainstrom another title for the language.

Later in 1995, they have renamed OAK to Java. Java is a island of an Indonasia where first
coffee of seed was produced and during the development of project they were consuming lot of
coffee's.Hence a symbol of java is a cup of coffee with saucer.

Interview Questions
--------------------
Q) Who is the creator of java?
James Gosling
Q) In which year java was developed?
In 1995
Q) Java originally known as ___ ?
OAK
Features of Java
================
We have following important features in java.
1) Simple
2) Platform independent
3) Object oriented
4) Highly secured
5) Architecture neutral
6) Multithreaded
7) Portable
8) Dynamic
9) Distributed
and etc.
Identifiers
============
A name in java is called identifier.
It can be class name, variable name, method name or label name.
ex: class Test
{
public static void main(String[] args)
{
int x = 10;

System.out.println(x);
}
}

Here Test, main, args and x are identifiers.


Rules to declare an identifiers
-------------------------------
Rule1: Identifier will accept following characters.
ex:
A-Z
a-z
0-9
_
$

Rule2: If we take other characters then we will get compile time error.
ex:
int emp_id; //valid
int emp$alary; //valid
int emp#id; //invalid
Rule3: Identifier must and should starts with alphabet, underscore or dollar symbol but not with
digits.
ex:
int a1234; //valid
int _abcd; //valid
int $=20; //valid
int 1abcd; //invalid
Rule4: Every identifier is a case sensitive.
ex:
int num;
int NUM;
int NuM;
Rule5: We can't take reserved words as an identifier name.
ex:
int if; //invalid
int else; //invalid
Rule6: There is no length limit for an identifier but it is not recommanded to take more then
15 characters.

Reserved Words
===============
There are some identifiers which are reserved to associate some funtionality or meaning such
type of identifiers are called reserved words.
Java supports 53 reserved words and It is classified into two types.
Diagram: java9.1

Used keywords with respect to class


-------------------------------------
import
package
class
interface
enum
extends
implements

Used keywords with respect to object


-----------------------------------
new
instanceof
this
super

Used keywords with respect to datatype


--------------------------------------
byte
short
int
long
float
double
boolean
char

Used keywords with respect to returntype


-------------------
void

Used keywords with respect to modifiers


-----------------------------------
default
public
private
protected
abstract
static
final
synchronized
strictfp
transient
volatile
native

Used keywords with respect to flow control


------------------------------------------
if
else
do
while
switch
case
break
continue
for

Used keywords with respect to exception handling


--------------------------
try
catch
throw
throws
finally
assert
Datatypes
=========
Datatype describes what type of value we want to store inside a variable.
Datatype also tells how much memory has to be created for a variable.
In java, datatypes are divided into two types.
Diagram: java9.2

byte
----
It is a smallest datatype in java.
size : 1 byte (8 bits)
Range : -128 to 127 (-2^7 to 2^7-1)
ex:
1) byte b=10;
System.out.println(b); // 10

2) byte b=130;
System.out.println(b); // C.T.E
3) byte b=10.5;
System.out.println(b); // C.T.E
short
------
It is a rarely used datatype in java.
Size : 2 bytes (16 bits)
Range : -32768 to 32767 (-2^15 to 2^15-1)

ex: 1) byte b=20;


short s=b;
System.out.println(s); // 20

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.
Size : 4 bytes (32 bits)
Range : -2147483648 to 2147483647 (-2^31 to 2^31-1)

ex:
1) int i=10.5;
System.out.println(i); // C.T.E

2) int i="true";
System.out.println(i); // C.T.E

3) int i=false;
System.out.println(i); // C.T.E

4) int i='a';
System.out.println(i); // 97
Note:
------
In java, every character contains universal unicode value.
ex:
a - 97
A - 65

long
-----
If int datatype is not enough to hold large value then we need to use long datatype.
Size: 8 bytes (64 bits)
Range: (-2^63 to 2^63-1)
ex:
1) long l=10.5;
System.out.prntln(l); // C.T.E

2) long l="hi";
System.out.println(l); // C.T.E

3) long l=true;
System.out.println(l); // C.T.E

4) long l='A';
System.out.println(l); // 65
float double
-------- ---------
If we need 4 to 6 decimal point of accuracy then If we need 14 to 16 decimal point of
accuracy
we need to use float. then we need to use double.

Size : 4 byte (32 bits) Size : 8 bytes (64 bits)


Range : -3.4e38 to 3.4e38 Range: -1.7e308 to 1.7e308
To declare a float value we need to suffix To declare a double value we need to suffix
with 'f' or 'F'. with 'd' or 'D'.
ex: ex:
10.56f 10.56d;
ex:
1) float f=10;
System.out.println(f); //10.0

2) float f='a';
System.out.println(f); // 97.0

3) float f="hi";
System.out.println(f); // C.T.E

4) float f=true;
System.out.println(f); // C.T.E

5) float f=10.56f;
System.out.println(f); // 10.56

ex:
1) double d=10;
System.out.println(d); //10.0
2) double d='a';
System.out.println(d); // 97.0

3) double d="hi";
System.out.println(d); // C.T.E

4) double d=true;
System.out.println(d); // C.T.E

5) double d=10.56f;
System.out.println(d); // 10.56
boolean
-------
It is used to represent boolean values either true or false.
Size: (Not Applicable) (1-bit)
Range: (Not Applicable )
ex:
1) boolean b="true";
System.out.println(b); // C.T.E

2) boolean b=TRUE;
System.out.println(b); // C.T.E

3) boolean b=true;
System.out.println(b); // true
char
------
It is a single character which is enclosed in a single quotation.
Size: 2 bytes (16 bits)
Range : 0 to 65535
ex:
1) char ch='a';
System.out.println(ch); // a

2) char ch="A";
System.out.println(ch); // C.T.E

3) char ch=65;
System.out.println(ch); // A

Q) Write a java program to display range of byte datatype?


byte range : -128 to 127
class Test
{
public static void main(String[] args)
{
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
}
}
Q) Write a java program to display range of short datatype?
byte range : -32768 to 32767
class Test
{
public static void main(String[] args)
{
System.out.println(Short.MIN_VALUE);
System.out.println(Short.MAX_VALUE);
}
}
Q) Is java purely object oriented or not?
No, java will not consider as purely object oriented programming language because it does not
support many OOPS concepts like multiple inheritance, operator overloading and more ever we
depends upon primitive datatypes which are non-objects.
Types of variables
===================
A name given to a memory location is called variable.
Purpose of variable is used to store the data.
In java, we have two types of variables.
1) Primitive variables
--------------------
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 / Non-static variables
2) Static variables / Global variables
3) Local variables / Temperory variables / Automatic variables
1) Instance variables
----------------------
1. A value of a variable which is varied(changes) from object to object is called instance
variable.
2. Instance variable will be created at the time of object creation and it will destroy at the
time of object destruction.Hence scope of instance variable is same as scope of an object.
3. Instance variable will store in heap area as a part of an object.
4. Instance variable must and should declare immediately after the class but not inside
methods, blocks and constructors.
5. Instance variables we can access directly from instance area but we can't access directly
from static area.
6. To access instance variable from static area we need to create object reference.

ex1:
----
class Test
{
//instance variable
int i=10;

public static void main(String[] args)


{
System.out.println(i); // C.T.E
}
}
o/p:
C.T.E : non-static variable i cannot be referenced from a static

ex:2
----
class Test
{
//instance variable
int i=10;

public static void main(String[] args)


{
Test t=new Test();
System.out.println(t.i); // 10
}
}

Note:
-----
If we won't initialize any value to instance variable then JVM will initialized default values.

ex3:
---
class Test
{
//instance variable
boolean b;

public static void main(String[] args)


{
Test t=new Test();
System.out.println(t.b); //false
}
}

ex:4
----
class Test
{
//instance variable
int i=10;

public static void main(String[] args)


{
Test t1=new Test();
Test t2=new Test();

System.out.println(t1.i);//10
System.out.println(t2.i);//10

t1.i=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
===================
1. A value of a variable which is not varied(changes) object to object is called static
variable.
2. Static variable will be created at the time of classloading and it will destroy at the time of
classunloading.Hence scope of static variable is as same as scope of .class file.
3. Static variable will store in method area.
4. Static variable must and should declare immediately after the class using static keyword
but not inside methods,blocks and constructors.
5. Static variable we access directly from static area as well as from instance area.
6. Static variable we can access by using object reference and class name.
ex:1
----
class Test
{
//static variable
static int i=10;

public static void main(String[] args)


{
System.out.println(i); //10

Test t=new Test();


System.out.println(t.i); //10

System.out.println(Test.i);//10
}
}

Note:
-----
If we won't initialize any value to static variable JVM will initialized default values.

ex:2
-----
class Test
{
//static variable
static String s;

public static void main(String[] args)


{
System.out.println(s);

Test t=new Test();


System.out.println(t.s);
System.out.println(Test.s);
}
}

ex:3
-----
class Test
{
//static variable
static int i=10;

public static void main(String[] args)


{
Test t1=new Test();
Test t2=new Test();

System.out.println(t1.i);//10
System.out.println(t2.i);//10

t1.i=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 t=new Test();


t.m1();

Test.m1();
}

//static method
public static void m1()
{
System.out.println("static-method");
}
}
3) Local variable
=================
1. To meet temperory requirements a programmer will declare some variables inside
methods, blocks and constructors such type of variables are called local variables.
2. Local variables will be created at the time of execution block and they will destroy when
execution block is executed.Hence scope of local variable is same as scope of execution
block where it is declared.
3. Local variables will store in java stack memory.
ex:
---
class Test
{

public static void main(String[] args)


{
//local variables
int i=10;

System.out.println(i); //10
}
}

Note:
-----
If we won't initialize any value to local variable then JVM will not initialized default values.

ex:2
-----
class Test
{

public static void main(String[] args)


{
//local variables
int i;

System.out.println(i); // C.T.E
}
}
o/p:
C.T.E : variable i might not have been initialized

A local variable will accept only one modifier i.e final.

ex:
---
class Test
{

public static void main(String[] args)


{
//local variables
final int i=10;

System.out.println(i); //10
}
}

Interview Question
===================
Q) Jack and John both are best friends in a town.They goto school every day and comes
together every day.One day while going to school they saw one begger and they decided to
help him.Jack gave 100 rupees from his school fee and John gave 10 rupees from his pocket
money.Write a java program to find out how much contribution they have done to help a
poor guy?

ex:
---
class Test
{

public static void main(String[] args)


{
sum();
}
//static method
public static void sum()
{
int a=100;
int b=10;
int c=a+b;
System.out.print(c);
}
}
Import statements
=================
Whenever we use import statement we should not use fully qualified name.
Using short name also we can achieve.
We have three types of import statements in java.

1) Explicit class import


-------------------------
This type of import statement is highly recommended to use because it will improve readability
of our code.
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);
}
}
2) Implicit class import
------------------------
This type of import statement is not recommanded to use because it will reduce readability of our
code.
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 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("stmt3");
}
}
Editplus Editor
===============
Download link : https://www.editplus.com/latest5.html
Basic Java Programs
===================
Q) Write a java program to perform sum of two numbers?

import java.util.Scanner;
class Example1
{
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();

//logic
int c = a + b;
System.out.println("sum of two numbers is ="+c);
}
}
Q) Write a java program to perform sum of two numbers without using third variable?

import java.util.Scanner;
class Example2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt();

System.out.println("Enter the second number :");


int b=sc.nextInt();

System.out.println("sum of two numbers is ="+(a+b));


}
}
Q) Write a java program to display square of a given number?
input:
5

output:
25

import java.util.Scanner;
class Example3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();

//logic
int square=n*n;

System.out.println("Square of a given number is ="+square);


}
}
Q) Write a java program to display cube of a given number?
input:
5

output:
125
ex:
import java.util.Scanner;
class Example4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();

//logic
int cube=n*n*n;

System.out.println("Cube of a given number is ="+cube);


}
}
approach2
----------
import java.util.Scanner;
class Example4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();//5

//logic
int cube=(int)Math.pow(n,3);

System.out.println("Cube of a given number is ="+cube);


}
}
Q) Write a java program to find out area of a circle?
input:
r=5
output:
78.5
ex:
import java.util.Scanner;
class Example5
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the radius : ");


int r=sc.nextInt();

//logic
float area=3.14f*r*r;

System.out.println("Area of a circle is ="+area);


}
}
Q) Write a java program to find out perimeter of a circle?
Input:
r=5
Output:
31.40
ex:
---
import java.util.Scanner;
class Example6
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the radius : ");


int r=sc.nextInt();

//logic
float perimeter=2*3.14f*r;

System.out.println("Perimeter of a circle is ="+perimeter);


}
}
Q) Write a java program to accept six marks of a student then find out total and average?
class Example7
{
public static void main(String[] args)
{
int m1=89,m2=35,m3=46,m4=67,m5=72,m6=59;
int total=m1+m2+m3+m4+m5+m6;

float average=(float)total/6;

System.out.println("Total :"+total);
System.out.println("Average :"+average);

}
}
Assignment
==========
Q) Write a java program to perform area of rectangle?

Q) Write a java program to perform swapping of two numbers?


import java.util.Scanner;
class Example8
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt();//10

System.out.println("Enter the second number :");


int b=sc.nextInt();//20

System.out.println("Before swapping a = "+a+" and b = "+b);

//logic
int temp=a;
a=b;
b=temp;

System.out.println("After swapping a = "+a+" and b = "+b);


}
}
Q) Write a java program to perform swapping of two numbers without using third variable?
import java.util.Scanner;
class Example9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();//10

System.out.println("Enter the second number :");


int b=sc.nextInt();//20

System.out.println("Before swapping a = "+a+" and b = "+b);

//logic
a = a + b;
b = a - b;
a = a - b;

System.out.println("After swapping a = "+a+" and b = "+b);


}
}
Q) Write a java program to find out 10% of TDS from given salary?
import java.util.Scanner;
class Example10
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the salary :");


int salary=sc.nextInt();

float tds=(float)salary*10/100;

System.out.println("10 percent of TDS is ="+tds);


}
}
Q) Write a java program to convert CGPA to percentage?
import java.util.Scanner;
class Example11
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the CGPA :");


float cgpa=sc.nextFloat();

float percent=cgpa*9.5f;

System.out.println("CGPA to percentage is ="+percent);


}
}

Typescasting
=============
The process of converting from one datatype to another datatype is called typecasting.
In java, typecasting can be performed in two ways.
1) Implicit typecasting
2) Explicit typecasting

1) Implicit typecasting
-----------------------
1. If we want to store small value in a bigger variable then we need to use implicit
typecasting.
2. A compiler is responsible to perform implicit typecasting.
3. There is no possibility to loss the information.
4. It is also known as widening or upcasting.
5. We can perform implicit typecasting as follow.

ex:
byte --> short
-->
int --> long --> float --> double
-->
char
ex:
---
class Test
{
public static void main(String[] args)
{
byte b=10;

int i=b;

System.out.println(i); // 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
char ch='a';
long l=ch;

System.out.println(l); //97
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

double d=i;

System.out.println(d); //10.0
}
}
2) Explicit typecasting
-----------------------
1. If we want to store bigger value into a smaller variable then we need to use explicit
typecasting.
2. A programmer is responsible to perform explicit typecasting.
3. There is a possibility to loss the information.
4. It is also known as Narrowing or Downcasting.
5. We can perform explicit typecasting as follow.
ex:
byte <-- short
<--
int <-- long <-- float <-- double
<--
char
ex:1
----
class Test
{
public static void main(String[] args)
{
double d=10.56d;

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
}
}
Q) What is Literal?
A value which is assigned to a variable is called literal.
A value which is not change during the program execution is called literal.
ex:
int i = 10;
| | |____ value of a variable / Literal
| |________ variable name / identifier
|_____________ datatype / keyword
Operators
==========
Operator is a symbol which is used to perform some operations on operands.
ex:
c = a + b;

Here a,b and c are operands.


Here = and + are operators.
It can be arithmetic operation, logical operation, bitwise operation, relational operation and etc.
We have following list of operators in java.
1) Assignment operators
2) Conditional/Ternary 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:
-----
Reinitialization is possible in java.
ex:
---
class Test
{
public static void main(String[] args)
{
final int i=10;

i=20;
i=30;

System.out.println(i); //C.T.E
}
}
Note:
-----
cannot assign a value to final variable
ex:
---
class Test {
public static void main(String[] args)
{
int i=1,2,3,4,5;

System.out.println(i); // C.T.E
}
}
ex:
---
class Test
{
//global variable
static int i=100;

public static void main(String[] args)


{
//local variable
int i=200;

System.out.println(i); // 200
}
}
Note:
-----
Here priority goes to local variable.
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

i+=20; // i = i + 20

System.out.println(i); //30
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i-=20; // i = i - 20

System.out.println(i); //-10
}
}
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=10;

i/=5; // i = i / 5;

System.out.println(i); //2
}
}
ex:
--
class Test
{
public static void main(String[] args)
{
int i=10;

i/=50; // i = i / 50;

System.out.println(i); //0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

i%=5; // i = i % 5;

System.out.println(i); //0
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

i%=50; // i = i % 50;

System.out.println(i); //10
}
}
2) Conditional/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)
{
String s=(5>20)?"Hi":"Bye";

System.out.println(s);//Bye
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int i=(true)?1:0;

System.out.println(i);//1
}
}
Q) Write a java program to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt(); // 5

System.out.println("Enter the second number :");


int b=sc.nextInt(); // 10

int max=(a>b)?a:b;

System.out.println(max+" is greatest");
}
}
Q) Write a java program to find out greatest of three numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt(); // 5

System.out.println("Enter the second number :");


int b=sc.nextInt(); // 10

System.out.println("Enter the third number :");


int c=sc.nextInt(); // 2

int max=(a>b)?((a>c)?a:c):((b>c)?b:c);

System.out.println(max+" is greatest");
}
}
3) Logical operators
----------------------
Logical AND operator (&&)
--------------------------
Logical AND operator deals with boolean values either true or false.
Truth table
----------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true && true); // true
System.out.println(true && false); // false
System.out.println(false && true); // false
System.out.println(false && false); // false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = (5>2) && (6<10);

System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = (5>20) && (6<10);

System.out.println(b); // false
}
}
Logical OR operator (||)
-------------------------
Logical OR operator deals with boolean values either true or false.
Truth table
------------
T T =T
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true || true ); //true
System.out.println(true || false ); //true
System.out.println(false || true ); //true
System.out.println(false || false );//false
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5>20) || (10<100);

System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5<1) || (6<2);

System.out.println(b); // false
}
}

ex:
--
class Test
{
public static void main(String[] args)
{
boolean b= (5>2) && (6<10) || (1>-4);

System.out.println(b); // true
}
}
Q) Jack wants to buy a shoe and he went a big showroom to finalize the shoe.But
he has a myth that if shoe price is divisible by 3 and 5 then only he can buy
that shoes?
Input: 1000
output:
Jack can't buy the show
ex:
--
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the shoe price :");


int price=sc.nextInt();

String msg=((price%3==0) && (price%5==0))?"He can buy the shoes":"He can't


buy the shoes";

System.out.println(msg);
}
}
Logical NOT operator (!)
------------------------
Logical NOT operator deals with boolean value either true or false.
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=!(5>2);

System.out.println(b); // false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=!(5>20);

System.out.println(b); // true
}
}
How to convert decimal number to binary number
-----------------------------------------------
10 - decimal number
1010 - binary number

2|10
---- 0
2|5
---- 1
2|2
---- 0 ^
1 |
-----------------
1010
How to convert binary number to decimal number
-----------------------------------------
10 - decimal number
1010 - binary number
1010 <---
0*1 + 1*2 + 0*4 + 1*8

0 + 2 + 0 + 8 = 10
4) Bitwise operators
---------------------
Bitwise AND operator (&)
------------------------
Bitwise AND operator deals with binary numbers.
Truth table
------------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10,b=15;

int c = a & b ;

System.out.println(c); //10
}
}
/*
10 - 1010
15 - 1111
----------
& - 1010 <---

0*1 + 1*2 + 0*4 + 1*8

0 + 2 + 0 + 8 = 10
*/
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10,b=5;
int c = a & b ;

System.out.println(c); //0
}
}
/*
10 - 1010
5 - 0101
----------
& - 0000 <---

*/
Bitwise OR operator
-------------------
Bitwise OR operator deals with binary numbers.
Truth table
-----------
T T =T
T F =T
F T =T
F F =F
x:
---
class Test
{
public static void main(String[] args)
{
int a=10,b=5;

int c = a | b ;

System.out.println(c); //15
}
}
/*
10 - 1010
5 - 0101
----------
| - 1111 <---

1*1 + 1*2 + 1*4 + 1*8

1 + 2 + 4 + 8 = 15
*/
Bitwise XOR operator (^)
------------------------
Bitwise XOR operator deals with binary numbers.
Truth table
-----------
T T =F
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10,b=15;

int c = a ^ b ;

System.out.println(c); //5
}
}
/*
10 - 1010
15 - 1111
-----------
^ - 0101 <---

1*1 + 0*2 + 1*4 + 0*8

1+0+4+0=5
*/
Bitwise NOT operator (~)
--------------------------
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=~67;;
System.out.println(i); // -68
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=~(-7);
System.out.println(i); // 6
}
}
5) Arithmetic operators
----------------------
% - modules
/ - divison
* - multiplication
+ - addition
- - subtraction
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 5+6%3+7/2+8*2+10%20+6/100+2-20;
System.out.println(i); // 16
}
}
/*
5 + 6%3 + 7/2 + 8*2 + 10%20 + 6/100 + 2 - 20

5 + 0 + 3 + 16 + 10 + 0 + 2 - 20

36 - 20 = 16
*/

6) Relational operators
------------------------
class Test
{
public static void main(String[] args)
{
System.out.println(10 > 20); // false
System.out.println(10 >= 20); // false
System.out.println(10 < 20); // true
System.out.println(10 <= 10); // true
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(10 == 10); // true
System.out.println(10 == 20); // false
System.out.println(10 != 20); // true
System.out.println(10 != 10); // false
}
}
7) Shift operators
==================
Right shift operators (>>)
---------------------------
10 >> 1 = 10/2
10 >> 2 = 10/4 (10/2*2)
10 >> 3 = 10/8 (10/2*2*2)
10 >> 4 = 10/16 (10/2*2*2*2)
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 20 >> 3;

System.out.println(i); // 20/8 = 2
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 >> 8;

System.out.println(i); //100/256 = 0
}
}
Left shift operators (<<)
---------------------------
10 << 1 = 10*2
10 << 2 = 10*4 (10/2*2)
10 << 3 = 10*8 (10/2*2*2)
10 << 4 = 10*16 (10/2*2*2*2)
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 << 3;

System.out.println(i); // 10*8 = 80
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 << 4;

System.out.println(i); // 100 * 16 = 1600


}
}
8) Unary operators
===================
Increment/Decrement operator(++/--)
-----------------------------------
We have two types of increment operators.
1) Post increment
ex:
i++;
2) Pre increment
ex:
++i;
We have two types of decrement operators.
1) post decrement
ex:
i--;
2) pre decrement
ex:
--i;
POST increment/decrement operator
---------------------------------
Rule1: First Take
Rule2: Then Change
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

i++;

System.out.println(i); //11
}
}
ex:
class Test
{
public static void main(String[] args)
{
int i=10;

System.out.println(i++);// 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

int j=i++;

System.out.println(i+" "+j);//11 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

int j=i-- + i--; //10 + 9

System.out.println(i+" "+j);// 8 19
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

int j=i++ + i++ - i--; //10 + 11 - 12

System.out.println(i+" "+j);//11 9
}
}
Pre increment/decrement operator
-------------------------------
Rule1: First Change
Rule2: Then Take
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); //11
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

int j=++i;

System.out.println(i+" "+j); //11 11


}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

int j=--i + --i;//9+8

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
}
}
Types of blocks
================
A block is a set of statements which is enclosed in a curly braces i.e {}.
In java, we have three types of blocks.
1) Instance block
2) Static block
3) Local block

1) Instance block
-----------------
1. Instance block is used to initialized the instance members.
2. Instance block will execute when we create a instance(object) of a class.
3. Instance block must and should declare immediately after the class.
4. Instance block does not allow name, returntype and modifier.
5. Instance block will execute before constructor is invoked.
6. We can declare instance block as follow.
syntax:
------
//instance block
{
-
- //set of statements
-
}

ex:
---
class Test
{
//instance block
{
System.out.println("Instance-Block");
}
public static void main(String[] args)
{
System.out.println("Main-Method");
}
}
o/p:
Main-Method
ex:
---
class Test
{
//instance block
{
System.out.println("Instance-Block");
}
public static void main(String[] args)
{
System.out.println("Main-Method");
Test t=new Test();
}
}
o/p:
Main-Method
Instance-Block
ex:
---
class Test
{
//instance block
{
System.out.println("Instance-Block");
}
public static void main(String[] args)
{
Test t1=new Test();
System.out.println("Main-Method");
Test t2=new Test();
}
}
o/p:
Instance-Block
Main-Method
Instance-Block

ex:
---
class Test
{
//instance variable
int i;

//instance block
{
i=100;
}

public static void main(String[] args)


{
Test t=new Test();
System.out.println(t.i); // 100
}
}
1) Static block
-----------------
1. Static block is used to initialized the static members.
2. Static block will execute at the time of classloading.
3. Static block must and should declare immediately after the class using static keyword.
4. Static block does not allow name, returntype and modifier.
5. Static block will execute before constructor and instance block is invoked.
6. We can declare static block as follow.
syntax:
------
//static block
statics
{
-
- //set of statements
-
}
ex:
---
class Test
{
//static block
static
{
System.out.println("Static-Block");
}

public static void main(String[] args)


{
System.out.println("Main-Method");
}
}
o/p:
static-block
main-method
ex:
----
class Test
{
//instance block
{
System.out.println("instance-block");
}
//static block
static
{
System.out.println("Static-Block");
}

public static void main(String[] args)


{
System.out.println("Main-Method");
Test t=new Test();
}
}
o/p:
static-block
main-method
instance-block

3) Local block
===============
1. A local block is used to initialized the local variables.
2. A local block will execute just like a normal statement.
3. A local block must and should declare inside methods,blocks and constructors.
4. A local block does not allow any name , return type and modifier.
5. We can declare a local block as follow.
syntax:
------
//local block
{
-
- //set of statement
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

//local block
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
o/p:
stmt1
stmt2
stmt3

ex:
---
class Test
{
public static void main(String[] args)
{
//local variable
int i;

//local block
{
i=10;
}

System.out.println(i);//10
}
}
Q) Can we execute java program without main method?

Yes, Till 1.6 version it is possible to execute java program without main method using static
block.
But from 1.7 version onwards it is not possible to execute java program without main method.

ex:
--
class Test
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
Control statements
==================
Control statement enables the programmer to control flow of a program.
Control statement allows us to make decisions, to jump from one section of code to another
section
and to execute the code repeatedly.
In java, we have four content statements.
1) Decision Making Statement
2) Selection Statement
3) Iteration Statement
4) Jump Statement
1) Decision Making Statement
-----------------------------
Decision making statement is used to declare conditions in our program.
Decision making statement is possible by using following ways.

i) if stmt
ii) if else stmt
iii) if else if ladder
iv) nested if stmt

i) if stmt
------------
It will execute the source code only if our condition is true.
syntax:
------
if(condition)
{
-
- //code to be execute
-
}

ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

if(5>2)
{
System.out.println("stmt2");
}

System.out.println("stmt3");
}
}
o/p:
stmt1
stmt2
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

if(!(5>2))
{
System.out.println("stmt2");
}

System.out.println("stmt3");
}
}
o/p:
stmt1
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
if(5>20)
System.out.println("stmt1");
System.out.println("stmt2");
System.out.println("stmt3");
}
}
o/p:
stmt2
stmt3
Q) Write a java to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();

if(a>b)
System.out.println(a+" is greatest");
if(b>a)
System.out.println(b+" is greatest");

}
}
Q) Write a java program to find out greatest of three numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt();

System.out.println("Enter the second number :");


int b=sc.nextInt();

System.out.println("Enter the third number :");


int c=sc.nextInt();

if((a>b) && (a>c))


System.out.println(a+" is greatest");
if((b>a) && (b>c))
System.out.println(b+" is greatest");
if((c>a) && (c>b))
System.out.println(c+" is greatest");

}
}
ii) if else stmt
-----------------
It will execute the source code either our condition is true or false.
syntax:
-----
if(condition)
{
- //code to be execute if cond is true
}
else
{
- //code to be execute if cond is false
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

if(true)
{
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(false)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}
o/p:
stmt1
stmt3
stmt4
Q) Write a java program to find out given age is eligible to vote or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the age :");


int age=sc.nextInt();

if(age>=18)
System.out.println("U r eligible to vote");
else
System.out.println("U r not eligible to vote");

}
}
Q) Write a java program to find out given number is even or odd?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();

if(n%2==0)
System.out.println("It is even number");
else
System.out.println("It is odd number");

}
}
Q) Write a java program to find out given number is odd or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();

if(n%2!=0)
System.out.println("It is odd number");
else
System.out.println("It is not odd number");

}
}
Q) Write a java program to check given number is positive or negative?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number :");


int n=sc.nextInt();

if(n==0)
{
System.out.println("It is not positive or negative number");
System.exit(0);
}

if(n>0)
System.out.println("It is positive number");
else
System.out.println("It is negative number");

}
}
Q) Write a java program to check given year is a leap year or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the year :");
int year=sc.nextInt();

if(year%4==0 && year%100!=0 || year%400==0)

System.out.println("It is a leap year");


else
System.out.println("It is not a leap year");

}
}
iii) if else if ladder
=======================
It will execute the source code based on multiple conditions.
syntax:
------
if(cond1)
{
-
- //code to be execute
-
}
else if(cond2)
{
-
- //code to be execute
-
}
else if(cond3)
{
-
- //code to be execute
-
}
else
{
-
- //code to be execute if all conditions are false
-
}

ex:---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the option :");


int option=sc.nextInt();

if(option==100)
System.out.println("It is police number");
else if(option==103)
System.out.println("It is Enquiry number");
else if(option==108)
System.out.println("It is Emergency number");
else
System.out.println("Invalid option");
}
}
Q) Write a java program to find out given alphabet is a uppercase letter, lowercase letter,
digit or special symbol?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the alphabet :");


char ch=sc.next().charAt(0);

if(ch>='A' && ch<='Z')


System.out.println("It is uppercase letter");
else if(ch>='a' && ch<='z')
System.out.println("It is lowercase letter");
else if(ch>='0' && ch<='9')
System.out.println("It is digit");
else
System.out.println("It is special symbol");
}
}
Q) Write a java program to check given alphabet is a vowel or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the alphabet :");
char ch=sc.next().charAt(0);

if(ch=='a' || ch=='A')
System.out.println("It is a vowel");
else if(ch=='e' || ch=='E')
System.out.println("It is a vowel");
else if(ch=='i' || ch=='I')
System.out.println("It is a vowel");
else if(ch=='o' || ch=='O')
System.out.println("It is a vowel");
else if(ch=='u' || ch=='U')
System.out.println("It is a vowel");
else
System.out.println("It is not a vowel");

}
}
Assignment
==========
Write a java program to accept six marks of a student then find out total,average and grade?
i) if average is greater then equals to 70 then A grade.
ii) if average is greater then equals to 50 then B grade.
iii) if average is greater then equals to 35 then C grade.
iv) if average is less then 35 then failed.

iv) nested if stmt


==================
If statement contains another if statement is called nested if statement.
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(!true)
{
System.out.println("stmt3");
}

System.out.println("stmt4");
}

System.out.println("stmt5");
}
}
o/p:
stmt1
stmt2
stmt4
stmt5'
Q) Write a java program to check given number is positive or negative ?
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

if(n!=0)
{
if(n>0)
{
System.out.println("It is positive number ");
System.exit(0);
}

System.out.println("It is negative number");


}
}
}
Interview Question
===================
Q) Write a java program to calculate costs based on user inputs.The program should
prompt usersto enter the total weight of items (in kilograms) and the shipping destination
(domestic or international). For domestic orders , the program should charge Rs 500 for
weight upto 5 kg and Rs 100 per additional kg.For internal orders , it should charge Rs.
1000 for weight upto 5 kg and Rs 200 per additional kg, and a Rs 500 surcharge for weight
exceeding 10 kg. print calculated shipping cost.
Inputs:
Total weight of items : 11
Shipping destination : domestic
output:
1100 (500(5kg) + 600(6kg * 100))

import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the total weight of items :");


int weight=sc.nextInt();//11

System.out.println("Enter the shipping destination :");


String destination=sc.next();//domestic

if(destination.equals("domestic"))
{
if(weight<=5)
{
System.out.println(500);
}
else
{
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
{
System.out.println(1000 + (weight-5)*200 + 500);
}
}

}
}
2) Selection Statement
=======================
switch case
============
It is used to execute the source code based on multiple conditions.
It is similar to if else if ladder.
syntax:
-------

switch(condition)
{
case value1: //code to be execute
break stmt;
case value2: //code to be execute
break stmt;
-
-
default: //code to be execute
}
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the option :");


int option=sc.nextInt();//103

switch(option)
{
case 100: System.out.println("It is police number ");
break;
case 103: System.out.println("It is enquiry number ");
break;
case 108: System.out.println("It is emergency number ");
break;
default: System.out.println("Invalid option");
}

}
}
Declaration of break statement in switch is always optional.Whenever we are not defining
break statement then from where our condition is satisfied from there all cases will be executed
that state is called fall through state of switch case.
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the option :");


int option=sc.nextInt();//103

switch(option)
{
case 100: System.out.println("It is police number ");
//break;
case 103: System.out.println("It is enquiry number ");
//break;
case 108: System.out.println("It is emergency number ");
//break;
default: System.out.println("Invalid option");
}

}
}
Q) Write a java program to check given alphabet is a vowel or consonent?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the alphabet :");


char ch=sc.next().charAt(0);

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");
}

}
}
3) Iteration statement
======================
Iteration statement is used to execute the source code repeatedly.
Iteration statement is possible by using LOOPS.
We have four types of loops.
i) do while loop
ii) while loop
iii) for loop
iv) for each loop

i) do while loop
------------------
It will execute the source code how long 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);
}
}
Q) Write a java program to display 10 natural numbers?
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);
}
}
Q) Write a java program to perform sum of 10 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
do
{
sum=sum+i;

i++;
}
while (i<=10);

System.out.println(sum);
}
}
Q) Write a java program to display factorial of a given number?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//5

int i=n,fact=1;
do
{
fact = fact * i;
i--;
}
while (i>=1);

System.out.println(fact);
}
}
Q) Write a java program to display multiplication table of a given number?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//5

int i=1;
do
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
while (i<=10);
}
}
ii) while loop
----------------
It will execute the source code how long 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
}
}
}
It will execute the source code only if our condition is true.
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;

while(i<=10)
{
System.out.print(i+" "); // nothing
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;

while(i>=1)
{
System.out.print(i+" ");//10 9 8 7 6 5 4 3 2 1

i--;
}
}
}
Q) Write a java program to display 100 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=100)
{
System.out.print(i+" ");
i++;
}
}
}
Q) Write a java program to perform sum of 10 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
Q) Write a java program to find out factorial of a given number?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//5

int i=n,fact=1;

while(i>=1)
{
fact = fact * i;
i--;
}

System.out.println(fact);
}
}
Q) Write a java program to display multiplication table of a given 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();//5

int i=1;
while(i<=10)
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
}
}
Q) Write a java program to find out 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);
System.out.println("Enter the number :");
int n=sc.nextInt();//123

int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
System.out.println(sum);//6
}
}
Q) Write a java program to check given number is armstrong or not?
input: 153
output: It is a Armstrong number(1*1*1+5*5*5+3*3*3)(1+125+27)
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//123

int temp=n;

int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}

if(sum==temp)
System.out.println("It is a armstrong number");
else
System.out.println("It is not a armstrong number");
}
}
Q) Write a java program to display reverse of a given number?
input: 123
output: 321
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();//123

int rem,rev=0;

while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}

System.out.println(rev);
}
}
Q) Write a java program to find out given number is palindrome or not?
input: 121
output: It is a palindrom 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();//123

int temp=n;
int rem,rev=0;

while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}

if(temp==rev)
System.out.println("It is a palindrome number");
else
System.out.println("It is not a palindrome number");
}
}
Assignment
===========
Q) Write a java program to find out given number is lucky or not?
Input: 7
Output: It is a lucy number
Q) Write a java program to display reverse of a given number?
nput: 123
Output: ThreeTwoOne
iii) for loop
==============
It will execute the source code how long our condition is true.
syntax:
------
for(initialization;condition;incrementation/decrementation)
{
-
- //code to be execute
-
}

ex:
----
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+" ");//1 2 3 4 5 6 7 8 9 10
}
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=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 "); //infinite Hello
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i*i+" "); // 1 4 9 16 25 36 49 64 81 100
}
}
}
Q) Write a java program to check given number is prime or not?
nput: 5
output: It is a prime 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();

boolean flag=true;

for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
Q) Write a java program to display prime numbers from 1 to 100?
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)
System.out.print(n+" ");
}
}
}
Q) Write a java program to find out given number is perfect or not?
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(sum==n)
System.out.println("It is a perfect number");
else
System.out.println("It is not a perfect number");
}
}
Q) Write a java program to find out GCD (Greatest Common Divisor) of two numbers?
input: 12 18
output: 6
class Test
{
public static void main(String[] args)
{
int a=12,b=18,gcd=0;

for(int i=1;i<a && i<b;i++)


{
if(a%i==0 && b%i==0)
{
gcd=i;
}
}

System.out.println(gcd);
}
}
Q) Write a java program to find out fibonacci series of a given number?
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();//6

int a=0,b=1,c;
System.out.print(a+" "+b+" ");

for(int i=2;i<=n;i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
4) Jump statement
==================
Jump statement is used to jump from one section of code to another section.
We have three types of jump statements.
i) break
ii) continue
iii) return
i) break
---------
It is used to break the execution of loops and switch case.
For conditional statement we can use if condition.
syntax: break;
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

break;

System.out.println("stmt2");
}
}
output:
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");
}
}
output:
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
}
}
}
ii) continue
-------------
It is used to continue the execution of loops.
For conditional statement we can use if condition.
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
}
}
}
Various ways to declare methods in java
========================================
There are four ways to declare the methods in java.
1) No returntype with No argument method
2) No returntype with argument method
3) With returntype with No argument method
4) With returntype with argument method
1) No returntype with No argument method
----------------------------------------
If we don't have arguments then we need to ask input values inside callie method.

Q) Write a java program to perform sum of two numbers using no returntype with
argument method?
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();

System.out.println("Enter the second number : ");


int b=sc.nextInt();

int c = a + b;

System.out.println("Sum of two numbers is = "+c);


}
}
Q) Write a java program to find out factorial of a given number using no return type with
no argument method?
import java.util.Scanner;
class Test
{
//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;
}
System.out.println("Factorial of a given number is ="+fact);
}
public static void main(String[] args)
{
//caller method
factorial();
}
}
2) No returntype with argument method
---------------------------------------
If we have argument then we need to ask input values inside main method.
Number of arguments depend upon number of inputs.
Q) Write a java program to perform sum of two numbers by using no returntype with
argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt(); //10
System.out.println("Enter the second number :");
int b=sc.nextInt(); //20

//caller method
sum(a,b);
}

//callie method
public static void sum(int a,int b)
{
int c = a + b;
System.out.println("Sum of two numbers is = "+c);
}
}
Q) Write a java program to check given number is even or odd using no return type with
argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();

//caller method
find(n);
}
//callie method
public static void find(int n)
{
if((n&1)==0)
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
}

5 - 0101
1 - 0001
--------
& - 0001

3)With returntype with no argument method


=========================================
In a method we can declare multiple return statements but a method can run only one value at a
time.
Here return type is depends upon output datatype.
Q) Write a java program to perform sum of two numbers using with returntype with no
argument method?

import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
int k=sum();
System.out.println("Addition of two numbers is ="+k);
}
//callie method
public static int sum()
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
int c = a + b;
return c;
}
}
Q) Write a java program to perform area of a circle using with returntype with no
argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
float k=circle();
System.out.println("Area of a circle is ="+k);
}
//callie method
public static float circle()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();

float area=3.14f*r*r;

return area;
}
}
4) With returntype with argument method
========================================
Q) Write a java program to perform sum of two numbers using with returntype with
argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number : ");


int a=sc.nextInt();//10

System.out.println("Enter the second number : ");


int b=sc.nextInt();//20
//caller method
System.out.print("Sum of two numbers is ="+sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
int c = a + b;

return c;
}
}
Q) Write a java program to check given number is even or odd using with returntype with
argument method?
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();//2

//caller method
System.out.println(find(n));
}
//callie method
public static String find(int n)
{
if((n&1)==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();//2
//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&1)==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();//2

//caller method
if(find(n))
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
//callie method
public static boolean find(int n)
{
if((n&1)==0)
return true;
else
return false;
}
}
Recursion
==========
A method which call itself for many number of times is called recursion.
Recursion is similar to loopings.
Whenever we use recursion , we should not use loops.
Q) Write a java program to display 10 natural numbers without using loops?
class Test
{
public static void main(String[] args)
{
//caller method
display(1);
}
//callie method
public static void display(int i)
{
if(i<=10)
{
System.out.print(i+" ");

display(i+1);
}
}
}
Q) Write a java program to perform sum of two numbers without using arithmetic
operator?
class Test
{
public static void main(String[] args)
{
int a=5,b=10;

//caller method
System.out.println(sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
if(a==0)
return b;

return sum(--a,++b);
}
}
Q) Write a java program to find out factorial of a given number using recursion?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number : ");
int n=sc.nextInt(); // 5

//caller method
System.out.println(fact(n));
}
//callie method
public static int fact(int n)
{
if(n<0)
return -1;

if(n==0)
return 1;

return n*fact(n-1);
}
}
Q) Write a java program to display N-th element of fibonacci series?
fibonacci sequence : 0 1 1 2 3 5 8
Input: 4
output: 2
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
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);
}
}
Q) Write a java program to find out reverse of a given number using recursion?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
int orginal=123;
int reverse=0;

//caller method
System.out.println(reverse(orginal,reverse));
}
//callie method
public static int reverse(int n,int rev)
{
if(n==0)
return rev;
else
return reverse(n/10,rev * 10 + (n%10));
}
}
Arrays
=======
1. In a normal variable we can store only one value at a time.
2. If we want to store multiple values in a single variable then we need to use arrays.
3. Array is a collection of homogeneous data elements.
4. The main advantage of arrays are
1) We can represent multiple elements using single variable name.
Ex:
int[] arr={10,20,30};
2) Performance point of view arrays are recommanded to use.
The main disadvantage of arrays are
1) Arrays are fixed in size. Once if we create an array there is no chance of increasing or
decreasing the
size of an array.

2) To use array concept in advanced we should know what is the size of an array which is always
not possible.
In java, Arrays are classified into three types.
1) Single Dimensional Array
2) Double Dimensional Array
3) Multi Dimensional Array

Array Declaration
------------------
At the time of array declaration we should not specify array size.
Arrays
|----------------------------------|---------------------------------|
Single Dimesional Array Double Dimensional Array Multi-Dimensional
Array

int[] arr; int[][] arr; int[][][] arr;


int []arr; int [][]arr; int [][][]arr;
int arr[]; int arr[][]; int arr[][][];
int[] []arr; int[][] []arr;
int[] arr[]; int[][] arr[];
int []arr[]; int[] [][]arr;
int[] arr[][];
int[] []arr[];
int [][]arr[];
int []arr[][];

Array Creation
--------------
In java, every array consider as an object. Hence we will use new operator to create an array.
Diagram: java24.1

Rules to construct an array.


Rule1:
------
At the time of array creation compulsary we need to specify array size otherwise we will
get
compile time error.
ex:
int[] arr = new int[3];

int[] arr = new int[]; // C.T.E array dimension missing

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 take negative number as an array size otherwise we will get runtime exception
called
NegativeArraySizeException.
ex:
int[] arr=new int[3];

int[] arr=new int[-3]; // R.E NegativeArraySizeException

Rule4:
-----
The allowed datatype for an array size is byte,short,int and char.
If we take other datatypes then we will get compile time error.
ex:
int[] arr = new int['a'];

byte b=10;
int[] arr=new int[b];

int[] arr=new int[10.5d]; //invalid

Rule5:
------
The maximum length we can take for an array size is maximum length of int datatype.
ex:
int[] arr=new int[2147483647];

Array Initialization
----------------------
Whenever we construct an array, every array element will be initialized with default values.
If we are not happy with default values then we can change with customized values.

Ex:
int[] arr = new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40; // R.E ArrayIndexOutOfBoundsException
Diagram: java24.2

Array Declaration, Creation and Initialization using single line


----------------------------------------------------------------

int[] arr;
arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30; ===> int[] arr={10,20,30};
===> char[] carr={'a','b','c'};
===> String[] sarr={"hi","hello","Hey"};

Q) What is the difference between length and length() method?


length
-------
It is a final variable which is applicable for arrays.
It returns size of an array.
ex:

class Test
{
public static void main(String[] args)
{
int[] arr = new int[3];
System.out.println(arr.length);//3
}
}
length()
-------
It is a final method which is applicable for String objects.
It will return number of characters present in string.

ex:

class Test
{
public static void main(String[] args)
{
String str="ihub";
System.out.println(str.length());//4
}
}

You might also like