0% found this document useful (0 votes)
4 views46 pages

Java Fundamentals Revision

Java notes

Uploaded by

tripathiajay164
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)
4 views46 pages

Java Fundamentals Revision

Java notes

Uploaded by

tripathiajay164
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/ 46

Java Fundamentals Revision

Prepared by Er P K Tiwari

Java
Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun
Microsystems, Inc. in 1991. It is formally known as OAK. In 1995, Sun
Microsystem changed the name to Java. In 2009, Sun Microsystem
takeover by Oracle Corporation.

Editions of Java
Each edition of Java has different capabilities. There are three editions of
Java:
Java Standard Editions (JSE): It is used to create programs for a desktop
computer.
Java Enterprise Edition (JEE): It is used to create large programs that run
on the server and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small
devices such as set-top boxes, phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java
programming:
Standalone Applications: Java standalone applications uses GUI
components such as AWT, Swing, and JavaFX. These components
contain buttons, list, menu, scroll panel, etc. It is also known as desktop
alienations.
Enterprise Applications: An application which is distributed in nature is
called enterprise applications.
Web Applications: An application that run on the server is called web
applications. We use JSP, Servlet, Spring, and Hibernate technologies for
creating web applications.
Mobile Applications: Java ME is a cross-platform to develop mobile
applications which run across smartphones. Java is a platform for App
Development in Android.

Java Platform
Java Platform is a collection of programs. It helps to develop and run a
program written in the Java programming language. Java Platform
includes an execution engine, a compiler and set of libraries. Java is a
platform-independent language.

Features of Java
Simple: Java is a simple language because its syntax is simple, clean,
and easy to understand. Complex and ambiguous concepts of C++ are
either eliminated or re-implemented in Java. For example, pointer and
operator overloading are not used in Java.
Object-Oriented: In Java, everything is in the form of the object. It means
it has some data and behaviour. A program must have at least one class
and object.
Robust: Java makes an effort to check error at run time and compile time.
It uses a strong memory management system called garbage collector.
Exception handling and garbage collection features make it strong.
Secure: Java is a secure programming language because it has no
explicit pointer and programs runs in the virtual machine. Java contains a
security manager that defines the access of Java classes.
Platform-Independent: Java provides a guarantee that code writes once
and run anywhere. This byte code is platform-independent and can be run
on any machine.

Basics of Java
Portable: Java Byte code can be carried to any platform. No
implementation-dependent features. Everything related to storage is
predefined, for example, the size of primitive data types.
High Performance: Java is an interpreted language. Java enables high
performance with the use of the Just-In-Time compiler.
Distributed: Java also has networking facilities. It is designed for the
distributed environment of the internet because it supports TCP/IP
protocol. It can run over the internet. EJB and RMI are used to create a
distributed system.
Multi-threaded: Java also supports multi-threading. It means to handle
more than one job a time.

OOPs (Object Oriented Programming System)


Object-oriented programming is a way of solving a complex problem by
breaking them into a small sub-problem. An object is a real-world entity. It
is easier to develop a program by using an object. In OOPs, we create
programs using class and object in a structured manner.
Class: A class is a template or blueprint or prototype that defines data
members and methods of an object. An object is the instance of the class.
We can define a class by using the class keyword.
Object: An object is a real-world entity that can be identified distinctly. For
example, a desk, a circle can be considered as objects. An object has a
unique behaviour, identity, and state. Data fields with their current values
represent the state of an object (also known as its properties or attributes).
Abstraction: An abstraction is a method of hiding irrelevant information
from the user. For example, the driver only knows how to drive a car; there
is no need to know how does the car run. We can make a class abstract
by using the keyword abstract. In Java, we use abstract class and
interface to achieve abstraction.
Encapsulation: An encapsulation is the process of binding data and
functions into a single unit. A class is an example of encapsulation. In
Java, Java bean is a fully encapsulated class.
Inheritance: Inheritance is the mechanism in which one class acquire all
the features of another class. We can achieve inheritance by using the
extends keyword. It facilitates the reusability of the code.
Polymorphism: The polymorphism is the ability to appear in many forms.
In other words, single action in different ways. For example, a boy in the
classroom behaves like a student, in house behaves like a son. There are
two types of polymorphism: run time polymorphism and compile-time
polymorphism.
Java Version History
Many java versions have been released till now. The current stable
release of Java is Java SE 10.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan 1996)
JDK 1.1 (19th Feb 1997)
J2SE 1.2 (8th Dec 1998)
J2SE 1.3 (8th May 2000)
J2SE 1.4 (6th Feb 2002)
J2SE 5.0 (30th Sep 2004)
Java SE 6 (11th Dec 2006)
Java SE 7 (28th July 2011)
Java SE 8 (18th Mar 2014)
Java SE 9 (21st Sep 2017)
Java SE 10 (20th Mar 2018)
Java SE 11 (September 2018)
Java SE 12 (March 2019)
Java SE 13 (September 2019)
Java SE 14 (Mar 2020)
Java SE 15 (September 2020)
Java SE 16 (Mar 2021)
Java SE 17 (September 2021)
Java SE 18 (to be released by March 2022)
Since Java SE 8 release, the Oracle corporation follows a pattern in which
every even version is release in March month and an odd version released
in September month.

Parts of Program in Java


Tokens in Java
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables
in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
variables in java
int data=50; //Here data is variable

Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable

1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods
in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method,
is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and
is not shared among instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. We can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

Example to understand the types of variables in java


public class Sample
{
static int m=100; //static variable
int data; //instance variable
void method ()
{
int n=90; //local variable
}
public static void main (String args[])
{

}
} //end of class

Java Variable Example: Add Two Numbers


public class Sample
{
public static void main(String [] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
20

Java Variable Example: Widening


public class Sample
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0

Java Variable Example: Typecasting


public class Sample
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f; //Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10

Java Variable Example: Overflow


class Sample
{
public static void main(String[] args)
{
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}
}
Output:
130
-126

Java Variable Example: Adding Lower Type


class Sample
{
public static void main(String[] args)
{
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}
}
Output:
20
Input and Output in Java
Data Types in Java

Data types specify the different sizes and values that can be stored in
the variable. There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays etc.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.
Java is a statically-typed programming language. It means, all variables
must be declared before its use. That is why we need to declare variable's
type and name.
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Java Data Types
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
The boolean Data Type
The boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false
conditions.
The boolean data type specifies one bit of information, but its "size" can't
be defined precisely.
Example:
boolean one = false;
The byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int" data
type.
Example:
byte a = 10;
byte b = -20;
The short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
Example:
short s = 10000;
short r = -5000;
The int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.
Example:
int a = 100000;
int b = -200000;
The long Data Type
The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808 (-2^63) to
9,223,372,036,854,775,807 (2^63 -1) (inclusive). Its minimum value is -
9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is
used when you need a range of values more than those provided by int.
Example:
long a = 100000L;
long b = -200000L;
The float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its
value range is unlimited. It is recommended to use a float (instead of
double) if you need to save memory in large arrays of floating-point
numbers. The float data type should never be used for precise values,
such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f;
The double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating
point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also should
never be used for precise values, such as currency. Its default value is
0.0d.
Example:
double d1 = 12.3;
The char Data Type
The char data type is a single 16-bit Unicode character. Its value-range
lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive). The char data
type is used to store characters.
Example:
char letterA = 'A';
Why char uses 2 bytes in java and what is \u0000?
It is because java uses Unicode system not ASCII code system. The
\u0000 is the lowest range of Unicode system.
Unicode System
Unicode is a universal international standard character encoding that is
capable of representing most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the
United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for Chinese, and so on.
Problem
This caused two problems:
A particular code value corresponds to different letters in the various
language standards.
The encodings for languages with large character sets have variable
length. Some common characters are encoded as single bytes, other
require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e.
Unicode System.
In Unicode, character holds 2 bytes, so java also uses 2 bytes for
characters.
lowest value: \u0000
highest value: \uFFFF

Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr
Unary + - ~ ! +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample
{
public static void main (String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a); //10+12=22
System.out.println(b++ + b++); //10+11=21
}
}
Output:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a); //-11 (minus of total positive value
//which starts from 0)
System.out.println(~b); //9 (positive of total minus, positive
//starts from 0)
System.out.println(!c); //false (opposite of boolean value)
System.out.println(!d); //true
}
}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample
{
public static void main (String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to
the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
public class OperatorExample
{
public static void main(String args[])
{
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first
condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c); //false && true = false
System.out.println(a<b&a<c); //false & true = false
}
}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample
{
public static void main (String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c); //false && true = false
System.out.println(a); //10 because second condition is not
//checked
System.out.println(a<b&a++<c); //false && true = false
System.out.println(a); //11 because second
//condition is checked
}
}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first
condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c); //true || true = true
System.out.println(a>b|a<c); //true | true = true
//|| vs |
System.out.println(a>b||a++<c); //true || true = true
System.out.println(a); //10 because second condition is not
//checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition
//is checked
}
}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else
statement and used a lot in Java programming. It is the only conditional
operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output:
2
Another Example:
public class OperatorExample
{
public static void main (String args[])
{
int a=10;
int b=5;
int max=(a>b)?a:b;
System.out.println(max);
}
}
Output:
10
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used
to assign the value on its right to the operand on its left.
Java Assignment Operator Example1
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Output:
14
16
Java Assignment Operator Example2
public class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4; //13-4
System.out.println(a);
a*=2; //9*2
System.out.println(a);
a/=2; //18/2
System.out.println(a);
}
}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
public class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
//a+=b; //a=a+b internally so fine
a=a+b; //Compile time error because 10+10=20 now int
System.out.println(a);
}
}
Output:
Compile time error
After type cast:
public class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
a=(short)(a+b); //20 which is int now converted to short
System.out.println(a);
}
}
Output:
20

Java Keywords
Java keywords are also known as reserved words. Keywords are
particular words that act as a key to a code. These are predefined words
by Java so they cannot be used as a variable or object name or class
name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
abstract: Java abstract keyword is used to declare an abstract class. An
abstract class can provide the implementation of the interface. It can have
abstract and non-abstract methods.
boolean: Java boolean keyword is used to declare a variable as a
boolean type. It can hold True and False values only.
break: Java break keyword is used to break the loop or switch statement.
It breaks the current flow of the program at specified conditions.
byte: Java byte keyword is used to declare a variable that can hold 8-bit
data values.
case: Java case keyword is used with the switch statements to mark
blocks of text.
catch: Java catch keyword is used to catch the exceptions generated by
try statements. It must be used after the try block only.
char: Java char keyword is used to declare a variable that can hold
unsigned 16-bit Unicode characters
class: Java class keyword is used to declare a class.
continue: Java continue keyword is used to continue the loop. It
continues the current flow of the program and skips the remaining code at
the specified condition.
default: Java default keyword is used to specify the default block of code
in a switch statement.
do: Java do keyword is used in the control statement to declare a loop. It
can iterate a part of the program several times.
double: Java double keyword is used to declare a variable that can hold
64-bit floating-point number.
else: Java else keyword is used to indicate the alternative branches in an
if statement.
enum: Java enum keyword is used to define a fixed set of constants.
Enum constructors are always private or default.
extends: Java extends keyword is used to indicate that a class is derived
from another class or interface.
final: Java final keyword is used to indicate that a variable holds a
constant value. It is used with a variable. It is used to restrict the user from
updating the value of the variable.
finally: Java finally keyword indicates a block of code in a try-catch
structure. This block is always executed whether an exception is handled
or not.
float: Java float keyword is used to declare a variable that can hold a 32-
bit floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set
of instructions/functions repeatedly when some condition becomes true. If
the number of iteration is fixed, it is recommended to use for loop.
if: Java if keyword tests the condition. It executes the if block if the
condition is true.
implements: Java implements keyword is used to implement an
interface.
import: Java import keyword makes classes and interfaces available and
accessible to the current source code.
instanceof: Java instanceof keyword is used to test whether the object is
an instance of the specified class or implements an interface.
int: Java int keyword is used to declare a variable that can hold a 32-bit
signed integer.
interface: Java interface keyword is used to declare an interface. It can
have only abstract methods.
long: Java long keyword is used to declare a variable that can hold a 64-
bit integer.
native: Java native keyword is used to specify that a method is
implemented in native code using JNI (Java Native Interface).
new: Java new keyword is used to create new objects.
null: Java null keyword is used to indicate that a reference does not refer
to anything. It removes the garbage value.
package: Java package keyword is used to declare a Java package that
includes the classes.
private: Java private keyword is an access specifier. It is used to indicate
that a method or variable may be accessed only in the class in which it is
declared.
protected: Java protected keyword is an access specifier. It can be
accessible within the package and outside the package but through
inheritance only. It can't be applied with the class.
public: Java public keyword is an access specifier. It is used to indicate
that an item is accessible anywhere. It has the widest scope among all
other modifiers.
return: Java return keyword is used to return from a method when its
execution is complete.
short: Java short keyword is used to declare a variable that can hold a
16-bit integer.
static: Java static keyword is used to indicate that a variable or method is
a class method. The static keyword in Java is mainly used for memory
management.
strictfp: Java strictfp is used to restrict the floating-point calculations to
ensure portability.
super: Java super keyword is a reference variable that is used to refer to
parent class objects. It can be used to invoke the immediate parent class
method.
switch: The Java switch keyword contains a switch statement that
executes code based on test value. The switch statement tests the
equality of a variable against multiple values.
synchronized: Java synchronized keyword is used to specify the critical
sections or methods in multithreaded code.
this: Java this keyword can be used to refer the current object in a method
or constructor.
throw: The Java throw keyword is used to explicitly throw an exception.
The throw keyword is mainly used to throw custom exceptions. It is
followed by an instance.
throws: The Java throws keyword is used to declare an exception.
Checked exceptions can be propagated with throws.
transient: Java transient keyword is used in serialization. If you define
any data member as transient, it will not be serialized.
try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
void: Java void keyword is used to specify that a method does not have
a return value.
volatile: Java volatile keyword is used to indicate that a variable may
change asynchronously.
while: Java while keyword is used to start a while loop. This loop iterates
a part of the program several times. If the number of iteration is not fixed,
it is recommended to use the while loop.

Mathematical Functions in Java


Java Control Statements / Control Flow in Java
Java compiler executes the code from top to bottom. The statements in
the code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow
of Java code. Such statements are called control flow statements. It is one
of the fundamental features of Java, which provides a smooth flow of
program.
Java provides three types of control flow statements.
Decision Making statements
if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which
statement to execute and when. Decision-making statements evaluate the
Boolean expression and control the program flow depending upon the
result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of
the program is diverted depending upon the specific condition. The
condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement

1) Simple if statement:
It is the most basic statement among all control flow statements in Java.
It evaluates a Boolean expression and enables the program to enter a
block of code if the expression evaluates to true.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
The following example in which we have used the if statement in the
java code.
public class Student
{
public static void main (String [] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20

2) if-else statement
The if-else statement is an extension to the if-statement, which uses
another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Example.
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20

3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-
if statements. In other words, we can say that it is the chain of if-else
statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when all the conditions are false
}
Example.
public class Student
{
public static void main (String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("City is Meerut");
}
else if (city == "Noida")
{
System.out.println("City is Noida");
}
else if(city == "Agra")
{
System.out.println("City is Agra");
}
else
{
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else
statement inside another if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when condition 2 is false
}
}

Example.
public class Student
{
public static void main (String[] args)
{
String address = "Delhi, India";
if(address.endsWith("India"))
{
if(address.contains("Meerut"))
{
System.out.println("Your city is Meerut");
}
else if(address.contains("Noida"))
{
System.out.println("Your city is Noida");
}
else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in India");
}
}
}
Output:
Delhi

The switch Statement:


In Java, switch statements are similar to if-else-if statements. The switch
statement contains multiple blocks of code called cases and a single case
is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances
the readability of the program.

Points to be noted about switch statement:


The case variables can be int, short, byte, char, or enumeration. String
type is also supported since version 7 of Java
Cases cannot be duplicate
The default statement is executed when any of the case doesn't match
the value of expression. It is optional.
The break statement terminates the switch block when the condition is
satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression
will be of the same type as the variable. However, it will also be a constant
value.
The syntax to use the switch statement is given below.
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
The following example to understand the flow of the switch statement.
public class Student
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2
While using switch statements, we must notice that the case expression
will be of the same type as the variable. However, it will also be a constant
value. The switch permits only int, string, and Enum type variables to be
used.

Loop Statements

In programming, sometimes we need to execute the block of code


repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular
condition.
In Java, we have three types of loops that execute similarly. However,
there are differences in their syntax and condition checking time.
for loop
while loop
do-while loop

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the
loop variable, check the condition, and increment/decrement in a single
line of code. We use the for loop only when we exactly know the number
of times, we want to execute the block of code.
for(initialization; condition; increment/decrement)
{
//block of statements
}
The following example to understand the proper functioning of the for
loop in java.
public class Calculation
{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " +
sum);
}
}
Output:
The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like
array or collection. In the for-each loop, we don't need to update the loop
variable. The syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name)
{
//statements
}
The following example to understand the functioning of the for-each loop
in Java.
public class Calculation
{
public static void main (String[] args)
{
String names[] = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array
names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements
multiple times. However, if we don't know the number of iterations in
advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked
at the start of the loop. If the condition is true, then the loop body will be
executed; otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
while(condition)
{
//looping statements
}
Example.
public class Calculation
{
public static void main (String[] args)
{
int i = 0;
System.out.println("Printing the list of up to 10 even numbers
\n");
while(i<=10)
{
i = i + 2;
System.out.println(i);
}
}
}

Output:
Printing the list of up to 10 even numbers
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after
executing the loop statements. When the number of iterations is not
known and we have to execute the loop at least once, we can use do-
while loop.
It is also known as the exit-controlled loop since the condition is not
checked in advance. The syntax of the do-while loop is given below.
do
{
//statements
}
while (condition);
The following example to understand the functioning of the do-while loop
in Java.
public class Calculation
{
public static void main (String [] args)
{
int i = 0;
System.out.println("Printing the list of up to 10 even numbers
\n");
do
{
i = i + 2;
System.out.println(i);
}
while(i<=10);
}
}

Output:
Printing the list of up to 10 even numbers
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two types of
jump statements in Java, i.e., break and continue.

Java break statement


As the name suggests, the break statement is used to break the current
flow of the program and transfer the control to the next statement outside
a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.
The break statement cannot be used independently in the Java program,
i.e., it can only be written inside the loop or switch statement.

The break statement example with for loop


Consider the following example in which we have used the break
statement with the for loop.
public class BreakExample
{
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}

Output:
0
1
2
3
4
5
6

break statement example with labelled for loop


public class Calculation
{
public static void main (String[] args)
{
a:
for(int i = 0; i<= 10; i++)
{
b:
for(int j = 0; j<=15;j++)
{
c:
for (int k = 0; k<=20; k++)
{
System.out.println(k);
if(k==5)
{
break a;
}
}
}
}
}
}

Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop,
whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
The following example to understand the functioning of the continue
statement in Java.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i = 0; i<= 2; i++)
{
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}
}

Output:
0
1
2
3
5
1
2
3
5
2
3
5
To Print Patterns in Java
Java Comments
The Java comments are the statements in a program that are not
executed by the compiler and interpreter.
Why do we use comments in a code?
Comments are used to make the program more readable by adding the
details of the code.
It makes easy to maintain the code and to find the errors easily.
The comments can be used to provide information or explanation about
the variable, method, class, or any statement.
It can also be used to prevent the execution of program code while testing
the alternative code.

Types of Java Comments


There are three types of comments in Java.
Single Line Comment
Multi Line Comment
Documentation Comment

1) Java Single Line Comment


The single-line comment is used to comment only one line of the code. It
is the widely used and easiest way of commenting the statements.
Single line comments start with two forward slashes (//). Any text in front
of // is not executed by Java.
Syntax:
//This is single line comment
Let's use single line comment in a Java program.
public class CommentExample1
{
public static void main (String[] args)
{
int i=10; // i is a variable with value 10
System.out.println(i); //printing the variable i
}
}
Output:
10

2) Java Multi Line Comment


The multi-line comment is used to comment multiple lines of code. It can
be used to explain a complex code snippet or to comment multiple lines
of code at a time (as it will be difficult to use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /*
and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
Example of multi-line comment in a Java program.
public class CommentExample2
{
public static void main (String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
/* float j = 5.9;
float k = 4.4;
System.out.println( j + k ); */
}
}
Output:
10
Note: Usually // is used for short comments and /* */ is used for longer
comments.

3) Java Documentation Comment


Documentation comments are usually used to write large programs for a
project or software application as it helps to create documentation API.
These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The
documentation comments are placed between /** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

List of Java programs.


Questions Based on Logic & Calculation:

1. Write a program to calculate the Simple Interest.


2. Calculate the area and circumference of circle.
3. Calculate the area of a triangle after accepting three sides.
4. Accept the value of A, B & C then calculate the formula.
R = 6.5 (A + B)2 - 7.3 (B + C)(A + C)
5. Write a program to input the basic salary of a person. He get 15% of
the basic as HRA, 15% of the basic as Conveyance allowance and 10%
of the basic as Entertainment allowance. The total salary is calculated by
adding Basic + HRA + Conveyance + Entertainment Allowance. Calculate
and print the total salary of person.
6. Write a program to accept two numbers and swap them (i.e.
interchange the value of two variables, Ex. If a=10 and b=20 then after
swap a=20 and b=10).
7. Write a Java program to accept an amount from the user and hence
find in each case:
a) No of Rs. 100 notes and the remainder amount.
b) No of Rs. 50 notes and the remainder amount.
c) No of Rs. 20 notes and the remainder amount.
d) No of Rs. 10 notes and the remainder amount.
E.g. In Rs. 542; No of Rs. 100 = 5, Remainder = Rs. 42 +
No of Rs. 50 = 10, Remainder = Rs. 42
No of Rs. 20 = 27, Remainder = Rs. 2.
No of Rs. 10 = 54, Remainder = Rs. 2.
8. Write a program to accept a three-digit number N, then extract each
digits and stored them into three variables a, b and c.
9. Write a program with supporting documentation to enter any three real
numbers and calculate X where:
X = Product of integer portion/Sum of decimal portion

Questions Based on Condition:

10. Write a Program to check whether a given number is ODD or EVEN.


11. Write a Program to check whether a given number is POSITIVE or
NEGATIVE.
12. Write a program to check whether a number is divisible by 5 or not.
13. Write a Program to accept the age of a student and check whether the
student is TEENAGER or not.
14. Write a program to accept two numbers then display the HIGHEST
number among them.
15. Accept a number and check whether the number is divisible by both 2
and 3 or not.
16. Write a Program to check whether a given number is POSITIVE,
NEGATIVE or ZERO.
17. Write two separate programs to accept three numbers and find which
one is greater (one using if statement and another using ternary operator).
18. Accept a number and find out the given number is divisible by 5 or not,
if not then print the nearest number from the given number which is
divisible by 5.
19. Write a program to input the code of a particular item, quantity
purchased and rate. Then calculate the total price and print it along with
gift to be presented. The gifts to the customers are given in the following
manner:
Amount of Purchase (Rs.) Gift
Between 100 to 500 a key ring
Between 500 to 1000 A leather purse
Above 1000 A pocket calculator
20. A computer salesman gets commission on the following basis:
Sales Commission Rate
Rs. 0 - 20,000 3%
Rs. 20,001 - 50,000 12%
Rs. 50,001 and more 31%
After accepting the sales as input, calculate and print his commission
amount and rate of commission.
21. Write a program to enter the three sides of a triangle. Decide whether
it is a scalene, isosceles or equilateral triangle.
22. A library charges fine for books returned late. Following are the fines:
first five days 40 paisa per day, Six to ten days 65 paisa per day, above
10 days 80 paisa per day. Design a program to calculate the fine assuming
that a book is returned N days late.
23. The telephone department wishes to compute monthly telephone bills
for its customers using the following rules. Minimum Rs. 250 for first 80
message units, plus 60 paisa per unit for next 60 units, plus 50 paisa per
unit for next 60 units, plus 40 paisa per unit for any units above 200. Write
a program that calculates the monthly bill, with input MESSAGE (the
number of message units) and CUSTNO (the registration number of a
customer). Then Display the bill in following format.
CUSTOMER NO : MESSAGE UNITS : AMOUNT (Rs.) :
24. WAP to compute BI-monthly telephone charges for subscriber. Use
the following information:
Fixed BI-monthly rent: Rs.380
Free calls during two months: 120
Charge/call beyond free limits upto 100 calls: Rs.1
Charge per call in excess of 100 calls: Rs. 1.25
25. Write a program to input the weight of a parcel and calculate the
charge of sending it. 10 gm - Rs. 5, for each additional 10 gm or part there
of Rs. 4.
26. A security man paid at the hourly rate (R) for the first 40 hours of work
in a week. Thereafter, he is paid at 1.25 times of the hourly rate (R) for the
next 16 hours and at 1.5 times of the hourly rate (R) for the further hours
of work in the week. Taking the numbers of hours (H) and the rate per
hour (R) as input, the weekly wages (W) is to be calculated.
27. There are 55 employees in an organization. You have to display the
number of employees getting Net-Salary above 20000 by taking only
Basic Salary as input and following the table given below.

Basic Salary DA (% Basic Salary) IT (% Gross Salary)


Below 5000 8% 6%
5000 to < 10000 15% 9%
10000and above 18% 12%
Where DA and IT are Dearness Allowance and income Tax respectively.
Gross Salary = Basic Salary + DA
Net Salary = Gross Salary – IT

Questions Based on Loops or Nested Loops:

28. Display first ten natural numbers (using for, while and do-while).
29. Display the first ten odd numbers and the sum of them.
30. Write a program to Display the table of given number.
31. The present population of a country is PO and it increases by 5% every
year. The population (P) after n years is given by the formula: P = PO
(1.05) n. Write a program to find the population every year for the next ten
years.
32. Generate the following series
a) 1 2 4 7 11 16 22
b) 0 3 8 15 24 35
c) 0 1 1 2 3 5 8 13 (Fibonacci series)
d) 1 2 2 4 8 32
e) 2 3 4 6 6 9 8 12 10 15
f) 1 5 2 4 3 3 4 2 5 1
g) 0 7 26 63 124
33. Calculate the Sum of given series
a) S = 1 + 2 – 3 + 4 – 5 + 6 – 7 + 8 – 9 + ……………… + Nth
b) S = (X+1)2+(X+2)3+(X+3)4+(X+4)5+…………… +(X+N)N+1
c) S = (1+2) + (1+2+3) + (1+2+3+4) + ………… + (1+…………+n)
d) S = 1 + X + 2!X2 + 3!X3 + 4!X4 ………… n terms
e) S = X2 /2!+ X3 /3!+ X4 /4! + X5 /5! + X6 /6… n terms
f) S = 1x2 + 2x3 + 3x4 + 4x5 + ... + 19x20
34. Display the following Design(n terms) Using Loops:

1111
2222
3333
4444

0
12
345
6789

1
12
123
1234
12345

1
21
321
4321
54321

55555
4444
333
22
1

1
22
333
4444
55555

54321
5432
543
54
5
54321
4321
321
21
1

12345
1234
123
12
1
12345
2345
345
45
5

5
45
345
2345
12345

5
54
543
5432
54321

1
212
32123
4321234
543212345

1
121
12321
1234321
123454321

1
123
12345
1234567
123456789

1
222
33333
4444444
555555555
*
***
*****
*******

*
***
*****
*******
*****
***
*

*
* *
* *
* *
* *
* *
*

*
*+*
*+++*
*+++++*
*+++++++*
*+++++*
*+++*
*+*
*

*
***
*****
*******
* *
* *
*

Typical Logical Questions:

35. WAP to display the factorial of the first ten natural numbers.
36. Write a program to print all the factors of a number.
37. WAP to accept a number and check whether the number is perfect
number or not. A number is called perfect number, if the sum of all factors
(except number itself) of the number is equal to that number. (e.g. 6 is a
perfect number. Factors are 1, 2 & 3 and the sum is 1+2+3=6.)
38. WAP to generate all Perfect numbers up to 1000.
39. WAP to accept a number, check whether the number is prime number
or not. If number is prime, then display “PRIME NUMBER” or display “NOT
A PRIME NUMBER”.
40. WAP to display all prime numbers between 100 and 200.
41. WAP to accept a number then print the sum of digits and number of
digits present in it. (E.g. If the input number is 225, the sum of digits is 9
and number of digits is 3).
42. Write a program to accept a number then print the number in reverse
order. (E.g. If the input number is 245, the output will be 542)
43. Write a program to check whether a number is palindrome number or
not. (Palindrome means, If the reverse of the number is same of original
number e.g., 131 reverse no is also 131)
44. A number is called Armstrong number if the sum of cube of each digit
of the number is equal to that number. WAP to accept a number then
check whether the given number is Armstrong number or not. (E.g. 153 is
an Armstrong number because 153= 13 + 53 +33).
45. Write a program to display all three digits Armstrong number.
46. Write a program to check whether all digits of the given number are
same type or not (i.e., all are odd numbers, even or both present)
47. Write a program to accept a number and then add all digits until you
found a single digit number. If that single digit number is 1, then that
number is called lucky number. (e.g. if number is 2345 then sum of its
digits becomes 14, further sum of this digits is 5)

Java Basic Programs


1) Fibonacci Series in Java
2) Prime Number Program in Java
3) Palindrome Program in Java
4) Factorial Program in Java
5) Armstrong Number in Java
6) How to Generate Random Number in Java
7) How to Print Pattern in Java
8) How to Compare Two Objects in Java
9) How to Create Object in Java
10) How to Print ASCII Value in Java

Java Number Programs


1) How to Reverse a Number in Java
2) Java Program to convert Number to Word
3) Automorphic Number Program in Java
4) Peterson Number in Java
5) Sunny Number in Java
6) Tech Number in Java
7) Fascinating Number in Java
8) Keith Number in Java
9) Neon Number in Java
10) Spy Number in Java
11) ATM program Java
12) Autobiographical Number in Java
13) Emirp Number in Java
14) Sphenic Number in Java
15) Buzz Number Java
16) Duck Number Java
17) Evil Number Java
18) ISBN Number Java
19) Krishnamurthy Number Java
20) Bouncy Number in Java
21) Mystery Number in Java
22) Smith Number in Java
23) Strontio Number in Java
24) Xylem and Phloem Number in Java
25) nth Prime Number Java
26) Java Program to Display Alternate Prime Numbers
27) Java Program to Find Square Root of a Number Without sqrt Method
28) Java Program to Swap Two Numbers Using Bitwise Operator
29) Java Program to Find GCD of Two Numbers
30) Java Program to Find Largest of Three Numbers
31) Java Program to Find Smallest of Three Numbers Using Ternary
Operator
32) Java Program to Check if a Number is Positive or Negative
33) Java Program to Check if a Given Number is Perfect Square
34) Java Program to Display Even Numbers From 1 to 100
35) Java Program to Display Odd Numbers From 1 to 100
36) Java Program to Find Sum of Natural Numbers

Prepared by Er P K Tiwari

You might also like