Java Documents
Java Documents
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
ex:
System.out.println("\n");
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();
}
o/p:
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.
ex:
---
//class declaration
class Test
{
//main method
public static void main(String[] args)
{
//variable declaration
int sum=0;
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
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.
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
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.
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);
}
}
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
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)
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.
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
ex1:
----
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 initialized default values.
ex3:
---
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
{
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;
ex:3
-----
class Test
{
//static variable
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();
}
//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
{
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
{
System.out.println(i); // C.T.E
}
}
o/p:
C.T.E : variable i might not have been initialized
ex:
---
class Test
{
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
{
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);
//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);
output:
25
import java.util.Scanner;
class Example3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//logic
int square=n*n;
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;
//logic
int cube=(int)Math.pow(n,3);
//logic
float area=3.14f*r*r;
//logic
float perimeter=2*3.14f*r;
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?
//logic
int temp=a;
a=b;
b=temp;
//logic
a = a + b;
b = a - b;
a = a - b;
float tds=(float)salary*10/100;
float percent=cgpa*9.5f;
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;
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;
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);
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
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(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 + 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 + 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+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;
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;
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;
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
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;
}
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);
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);
}
}
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);
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);
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);
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);
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();
}
}
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);
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);
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.
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);
}
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
{
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);
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);
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);
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);
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;
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);
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);
int c = a + b;
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
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);
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);
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
Array Creation
--------------
In java, every array consider as an object. Hence we will use new operator to create an array.
Diagram: java24.1
Rule2:
-----
It is legal to have an array size with zero.
ex:
int[] arr=new int[0];
System.out.println(arr.length);//0
Rule3:
------
We can't take negative number 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:
int[] arr = new int['a'];
byte b=10;
int[] arr=new int[b];
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
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"};
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
}
}