Java Fundamentals Revision
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.
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.
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.
}
} //end of class
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.
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.
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
Loop Statements
Output:
Printing the list of up to 10 even numbers
2
4
6
8
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.
Output:
0
1
2
3
4
5
6
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.
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
*
***
*****
*******
*
***
*****
*******
*****
***
*
*
* *
* *
* *
* *
* *
*
*
*+*
*+++*
*+++++*
*+++++++*
*+++++*
*+++*
*+*
*
*
***
*****
*******
* *
* *
*
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)
Prepared by Er P K Tiwari