Java College Notes
Java College Notes
Java College Notes
INSTALLATION IN JAVA
package com.company;
public class Main{
public static void main(String args[]){
System.out.println(“Hello World”);
}
}
PROPERTIES OF CLASSES : -
COMMENTS IN JAVA
I. PRIMITIVE DATATYPES : -
LITERALS
KEYWORDS
S Constructor Description
N
1) Scanner(File It constructs a new Scanner that
source) produces values scanned from the
specified file.
2) Scanner(File It constructs a new Scanner that
source, String produces values scanned from the
charsetName) specified file.
3) Scanner(InputStrea It constructs a new Scanner that
m source) produces values scanned from the
specified input stream.
4) Scanner(InputStrea It constructs a new Scanner that
m source, String produces values scanned from the
charsetName) specified input stream.
5) Scanner(Readable It constructs a new Scanner that
source) produces values scanned from the
specified source.
6) Scanner(String It constructs a new Scanner that
source) produces values scanned from the
specified string.
7) Scanner(Readable It constructs a new Scanner that
ByteChannel produces values scanned from the
source) specified channel.
8) Scanner(Readable It constructs a new Scanner that
ByteChannel produces values scanned from the
source, String specified channel.
charsetName)
9) Scanner(Path It constructs a new Scanner that
source) produces values scanned from the
specified file.
10 Scanner(Path It constructs a new Scanner that
) source, String produces values scanned from the
charsetName) specified file.
Example 1
1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }
Output:
1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
Output:
Example 3
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
Output:
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int div = (a+b+c+d+e)/500;
int percentage = div * 100 ;
System.out.println(percentage);
}
}
PRACTICE SET 1
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int sum = (a+b+c+d+e);
System.out.println(sum);
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int cgpa = (a+b+c)/300;
System.out.println(cgpa);
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println("Hello " + a + " , have a
good day");
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float kilometers = sc.nextFloat();
float miles = kilometers * (0.62f) ;
System.out.println(miles);
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean a = sc.hasNextInt();
if(a == true){
System.out.println("Integer");
}
else{
System.out.println("Decimal");
}
}
}
a. Arithmetic Operators
b. Assignment Operators
c. Comparison Operators
d. Logical Operators
e. Bit wise Operators
ARITHMETIC OPERATORS
BINARY OPERATORS
UNARY OPERATORS
Syntax:
-(operand)
Illustration:
a = -10
Example:
// Main class
class GFG {
Output
Number = 20
Result = -20
Operator 2: ‘NOT’ Operator(!)
This is used to convert true to false or vice versa.
Basically, it reverses the logical state of an
operand.
Syntax:
!(operand)
Illustration:
cond = !true;
// cond < false
Example:
Output
Cond is: true
Var1 = 10
Var2 = 1
Now cond is: false
!(a < b) = true
!(a > b) = false
Operator 3: Increment(++)
It is used to increment the value of an integer. It
can be used in two separate ways:
Syntax:
num++
Illustration:
num = 5
num++ = 6
3.2: Pre-increment operator
Syntax:
++num
Illustration:
num = 5
++num = 6
Operator 4: Decrement ( — )
It is used to decrement the value of an integer. It
can be used in two separate ways:
num--
Illustration:
num = 5
num-- = 4 // Value will be decremented before
execution of next statement.
4.2: Pre-decrement operator
Syntax:
--num
Illustration:
num = 5
--num = 4 //output is 5, value is decremented
before execution of next statement
Operator 5: Bitwise Complement(~)
This unary operator returns the one’s complement
representation of the input value or operand, i.e,
with all bits inverted, which means it makes every
0 to 1, and every 1 to 0.
Syntax:
~(operand)
Illustration:
a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
Example:
// Main class
class GFG {
Output
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Example program in Java that implements all basic
unary operators for user input:
import java.util.Scanner;
// Initialize num
int num = 10;
// Unary plus
int result = +num;
System.out.println("The value of result after
unary plus is: " + result);
// Unary minus
result = -num;
System.out.println("The value of result after
unary minus is: " + result);
// Pre-increment
result = ++num;
System.out.println("The value of result after
pre-increment is: " + result);
// Post-increment
result = num++;
System.out.println("The value of result after
post-increment is: " + result);
// Pre-decrement
result = --num;
System.out.println("The value of result after
pre-decrement is: " + result);
// Post-decrement
result = num--;
System.out.println("The value of result after
post-decrement is: " + result);
Output
The value of result after unary plus is: 10
The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of re...
Explanation:
The above program implements all basic unary
operators in Java using user input. The program
uses the Scanner class from the java.util package
to read user input from the console. The following
steps describe how the program works in detail:
ASSIGNMENT OPERATORS
These operators are used to assign values to a
variable. The left side operand of the assignment
operator is a variable, and the right side operand
of the assignment operator is a value. The value on
the right side must be of the same data type of the
operand on the left side. Otherwise, the compiler
will raise an error. This means that the assignment
operators have right to left associativity, i.e., the
value given on the right-hand side of the operator
is assigned to the variable on the left. Therefore,
the right-hand side value must be declared before
using it or should be a constant. The general
format of the assignment operator is,
1. (=) operator:
This is the most straightforward assignment
operator, which is used to assign the value on the
right to the variable on the left. This is the basic
definition of an assignment operator and how it
functions.
Syntax:
num1 = num2;
Example:
a = 10;
ch = 'y';
// Java code to illustrate "=" operator
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num;
String name;
// Assigning values
num = 10;
name = "GeeksforGeeks";
Syntax:
num1 += num2;
Example:
a += 10
This means,
a = a + 10
// Java code to illustrate "+="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
int x = 5;
Method 1: x = x + 4.5
Method 2: x += 4.5
3. (-=) operator:
This operator is a compound of ‘-‘ and ‘=’
operators. It operates by subtracting the variable’s
value on the right from the current value of the
variable on the left and then assigning the result to
the operand on the left.
Syntax:
num1 -= num2;
Example:
a -= 10
This means,
a = a - 10
// Java code to illustrate "-="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
Syntax:
num1 *= num2;
Example:
a *= 10
This means,
a = a * 10
// Java code to illustrate "*="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
Syntax:
num1 /= num2;
Example:
a /= 10
This means,
a = a / 10
// Java code to illustrate "/="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 20, num2 = 10;
Syntax:
num1 %= num2;
Example:
a %= 3
This means,
a=a%3
// Java code to illustrate "%="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 5, num2 = 3;
COMPARISON OPERATORS
1. Relational Operators
2. Logical operators
3. Ternary Operators
RELATIONAL OPERATORS
Syntax:
Syntax:
var1 == var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 == var2 results in false
Example:
// Main class
class GFG {
Syntax:
var1 != var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
// Main class
class GFG {
Syntax:
var1 = 30
var2 = 20
// Main class
class GFG {
Syntax:
var1 = 10
var2 = 20
var1 < var2 results in true
Example:
// Main class
class GFG {
Syntax:
var1 = 20
var2 = 20
var3 = 10
// Main class
class GFG {
Syntax:
var1 = 10
var2 = 10
var3 = 9
// Main class
class GFG {
Advantages
There are several advantages of using relational
operators in Java, including:
Easy to understand: Relational operators are
simple and easy to understand, making it easy to
write code that performs comparisons.
Versatile: Relational operators can be used to
compare values of different data types, such as
integers, floating-point numbers, and strings.
Essential for making decisions: Relational
operators are essential for making decisions in a
program, as they allow you to control the flow of a
program based on the results of comparisons.
Efficient: Relational operators are efficient, as they
perform comparisons quickly and accurately.
Reusable code: The code that uses relational
operators can be reused in different parts of a
program, making it easier to maintain and update
the code.
Improved code readability: By using relational
operators, you can make your code more readable
and understandable, as the comparisons are
clearly stated in the code.
Debugging made easier: Relational operators make
debugging easier, as you can use them to check
the values of variables and to find out where a
problem is occurring in your code.
LOGICAL OPERATORS
a = 10, b = 20, c = 30
Condition 1: c > a
Condition 2: c > b
Output:
Condition 1: c > a
Condition 2: c > b
Output:
Condition 1: c > a
Condition 2: c > b
Output:
Syntax:
condition1: a < b
condition2: b == c
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50
Example:
import java.io.*;
class shortCircuiting {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 15;
// displaying b
System.out.println("Value of b : " + b);
// displaying b
System.out.println("Value of b : " + b);
}
}
Output:
Syntax:
condition1 || condition2
Example:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b > c
if(condition1 || condition2)
d=a+b+c
Illustration:
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1, c = 10, d = 30;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
System.out.println("Var4 = " + d);
Output
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true
Example:
import java.io.*;
class ShortCircuitingInOR {
public static void main (String[] args) {
// initializing variables
int a = 10, b = 20, c = 15;
// displaying b
System.out.println("Value of b: " +b);
// Using logical OR
// Short-circuiting effect as the first condition
is true
// so the second condition is never reached
// and so ++b (pre-increment) doesn't take
place and
// value of b remains unchanged
if((a < c) || (++b < c))
System.out.println("Inside if");
// displaying b
System.out.println("Value of b: " +b);
}
}
Output
Value of b: 20
Inside if
Value of b: 20
Syntax:
!(condition)
Example:
a = 10, b = 20
Illustartion:
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
Output
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false
Output
a: true
b: false
a && b: false
a || b: true
!a: false
!b: true
Explanation:
The code above is a Java program that implements
all logical operators with default values. The
program defines a class LogicalOperators with a
main method.
In the main method, two boolean variables a and b
are defined and assigned default values true and
false, respectively.
The program then prints the values of a and b to
the console using the System.out.println method.
This allows us to verify the values assigned to a
and b.
Next, the program calculates the result of the
logical operators && (and), || (or), and ! (not)
applied to a and b. The results of these operations
are also printed to the console using the
System.out.println method.
The && operator returns true if both operands are
true; otherwise, it returns false. In this case, the
result of a && b is false.
The || operator returns true if either operand is
true; otherwise, it returns false. In this case, the
result of a || b is true.
The ! operator negates the value of its operand. If
the operand is true, the result is false, and if the
operand is false, the result is true. In this case, the
results of !a and !b are false and true, respectively.
The output of the program shows the truth table
for all logical operators. This table provides a visual
representation of how these operators behave for
all possible combinations of true and false inputs.
Advantages of logical operators:
Short-circuit evaluation: One of the main
advantages of logical operators is that they
support short-circuit evaluation. This means that if
the value of an expression can be determined
based on the left operand alone, the right operand
is not evaluated at all. While this can be useful for
optimizing code and preventing unnecessary
computations, it can also lead to subtle bugs if the
right operand has side effects that are expected to
be executed.
Readability: Logical operators make code more
readable by providing a clear and concise way to
express complex conditions. They are easily
recognizable and make it easier for others to
understand the code.
Flexibility: Logical operators can be combined in
various ways to form complex conditions, making
the code more flexible. This allows developers to
write code that can handle different scenarios and
respond dynamically to changes in the program’s
inputs.
Reusability: By using logical operators, developers
can write code that can be reused in different parts
of the program. This reduces the amount of code
that needs to be written and maintained, making
the development process more efficient.
Debugging: Logical operators can help to simplify
the debugging process. If a condition does not
behave as expected, it is easier to trace the
problem by examining the results of each logical
operator rather than having to navigate through a
complex code structure.
Disadvantages of logical operators:
Limited expressiveness: Logical operators have a
limited expressive power compared to more
complex logical constructs like if-else statements
and switch-case statements. This can make it
difficult to write complex conditionals that require
more advanced logic, such as evaluating multiple
conditions in a specific order.
Potential for confusion: In some cases, the use of
logical operators can lead to confusion or
ambiguity in the code. For example, consider the
expression a or b and c. Depending on the
intended order of operations, this expression can
have different interpretations. To avoid this kind of
confusion, it is often recommended to use
parentheses to explicitly specify the order of
evaluation.
Boolean coercion: Logical operators can sometimes
lead to unexpected behavior when used with non-
Boolean values. For example, when using the or
operator, the expression a or b will evaluate to a if
a is truthy, and b otherwise. This can lead to
unexpected results if a or b are not actually
Boolean values, but instead have a truthy or false
interpretation that does not align with the
programmer’s intentions.
Overall, logical operators are an important tool for
developers and play a crucial role in the
implementation of complex conditions in a
program. They help to improve the readability,
flexibility, reusability, and debuggability of the
code.
TERNARY OPERATORS
Syntax:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Example:
num1 = 10;
num2 = 20;
res=(num1>num2) ? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, max;
Output
First num: 5
Second num: 10
Maximum is = 10
Example 2:
Below is the implementation of the above method:
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, res;
Example 3:
Implementing ternary operator on Boolean values:
// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";
System.out.println(result);
}
}
Output
True
BITWISE OPERATORS
1. Bitwise OR (|)
Example:
Example:
Example:
Example:
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that
number, i.e., 2’s complement of 10 will be -6.
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise not
// ~00000000 00000000 00000000
00000101=11111111 11111111 11111111
11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);
Time complexity:O(1)
class GFG {
public static void main (String[] args) {
String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};
// bitwise or
int c= a | b;
// bitwise and
int d= a & b;
// bitwise xor
int e= a ^ b;
// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;
System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b=
"+binary[f]);
System.out.println("~a= "+binary[g]);
}
}
Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)
Syntax:
import java.util.Scanner;
Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two
numbers, num1 and num2. It then performs the
following bitwise operations using the &, |, ^, ~,
<<, >>, and >>> operators:
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift
Advantages
The advantages of using Bitwise Operators in Java
are:
SHIFT OPERATORS
Sign Description
Signed Left Shift << The left shift operator moves
all bits by a given number of bits to the left.
Signed Right Shift>> The right shift operator
moves all bits by a given number of bits to the
right.
Unsigned Right Shift >>> It is the same as
the signed right shift, but the vacant leftmost
position is filled with 0 instead of the sign bit.
1. Signed Left Shift Operator in Java
This operator is represented by a symbol <<, read
as double less than.
Syntax:
class GFG {
public static void main(String[] args)
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte)(a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Calculating the value of number<<2 if number=2.
When the value of a number is shifted to the left
two places, the leftmost two bits are lost. The
number has a value of two. 0010 is the binary
representation of the number 2. In the following
example, the method for doing a left shift is
explained:
Example:
// Main class
class GFG {
System.out.println(Ans);
}
}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a
number in a given number of places to the right.
The >> sign represents the right shift operator,
which is understood as double greater than. When
you type x>>n, you tell the computer to move the
bits x to the right n places.
When we shift a number to the right, the least
significant bits (rightmost) are deleted, and the
sign bit is filled in the most considerable place
(leftmost).
Syntax:
Example:
class GFG
{
public static void main (String[] args) {
{
int number = 8;
class GFG {
public static void main (String[] args) {
char hex[]={
'0','1','2','3','4','5',
'6','7','8','9','a','b','c',
'd','e','f'
};
Syntax:
class GFG
{
public static void main (String[] args)
{
byte num1 = 8;
byte num2 = -8;
ASSOCIATIVITY OF OPERATORS
= += -= *= /= %=
assignment &= ^= |= <<= >>= right to left
>>>=
OUTPUT :
4.0
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int grade = sc.nextInt();
int newgrade = grade + 8;
System.out.println(grade);
}
}
COMPARE A GIVEN NUMBER TO ENTERED
NUMBER
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 10;
int b = sc.nextInt();
if(a>b){
System.out.println("Smaller");
}
else{
System.out.println("Bigger");
}
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v,u,a,s ;
v = sc.nextInt();
u = sc.nextInt();
a = sc.nextInt();
s = sc.nextInt();
int x = (v*v - u*u)/(2*a*s);
System.out.println(x);
}
}
STRINGS IN JAVA
Example:
// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
// this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.
System.out.println(str);
}
}
Output
example
Ways of Creating a String
There are two ways to create a string in Java:
String Literal
Using new Keyword
Syntax:
<String_Type> <string_variable> =
"<sequence_of_string>";
1. String literal
To make Java more memory efficient (because no
new objects are created if it exists already in the
string constant pool).
Example:
CharSequence Interface
CharSequence Interface is used for representing
the sequence of Characters in Java.
Classes that are implemented using the
CharSequence interface are mentioned below and
these provides much of functionality like substring,
lastoccurence, first occurence, concatenate ,
toupper, tolower etc.
String
StringBuffer
StringBuilder
1. String
String is an immutable class which means a
constant and cannot be changed once created and
if wish to change , we need to create an new object
and even the functionality it provides like toupper,
tolower, etc all these return a new object , its not
modify the original object. It is automatically
thread safe.
Syntax
Syntax:
Syntax:
Example:
Syntax:
class GFG {
public static void main(String[] args)
{
String s = "Sachin";
Output
Sachin
Here Sachin is not changed but a new object is
created with “Sachin Tendulkar”. That is why a
string is known as immutable.
class GFG {
public static void main(String[] args)
{
String name = "Sachin";
name = name.concat(" Tendulkar");
System.out.println(name);
}
}
Output
Sachin Tendulkar
Memory Allotment of String
Whenever a String Object is created as a literal,
the object will be created in the String constant
pool. This allows JVM to optimize the initialization
of String literal.
Example:
Example:
Example:
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String name = "GeeksforGeeks";
Output
String name = GeeksforGeeks
String newString = GeeksforGeeks
For example:
Output
TAT
TAT
TAT
TAT
String Pool in Java
String Pool in Java
Example 1:
// Driver Class
class GFG {
// main function
public static void main(String args[])
{
byte ascii[] = { 71, 70, 71 };
Output
GFG
FG
Example 2:
class GFG {
public static void main(String args[])
{
System.out.println(firstString);
System.out.println(secondString);
}
}
Output
Gfg
Gfg
STRING METHODS
Method Description Return Type
Example:
Java
public class Test {
public static void main(String[] args)
{
System.out.println("Hi geek, welcome
to \"GeeksforGeeks\".");
}
}
Output: Hi geek, welcome to "GeeksforGeeks".
Some Coding Examples of Java Escape Characters
Java code for the escape sequence \t:
Java
// \t -> It gives a tab between two words.
Output:
Good Morning Geeks!
Java code for the escape sequence \b :
Java
// The escape sequence \b is a backspace character
// It moves the cursor one character back with
// or without deleting the character(depending
upon compiler)
Output:
Good Morning Geeks!
How are you all?
Output:
Good Morning 'Geeks!' How are you all?
Java code for the escape sequence \”
Java
// This \" escape sequence is for printing a double
quotation mark on the text string
Output:
\- this is a backslash.
Explanation:It contains two backslashes, this
means after reading the first \ the compiler read
the next \ as a new character
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.toLowerCase());
}
}
CONVERTING SPACES TO UNDERSCORES IN
STRING
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.replace(" ", "_"));
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Yash Thanks a Lot";
System.out.println(letter.replace("Yash", a));
}
}
mport java.util.Scanner;
i
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Harry , This java course
is nice . Thanks ! ";
}
}
CONDITIONALS
1) If - Else Statements.
If-Else in Java
If- else together represents the set of Conditional
statements in Java that are executed according to
the condition which is true.
class IfElseDemo {
public static void main(String args[])
{
int i = 20;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
Output
i is greater than 15
Outside if-else block
Nested if statement in Java
In Java, we can use nested if statements to create
more complex conditional logic. Nested if
statements are if statements inside other if
statements.
Syntax:
if (condition1) {
// code block 1
if (condition2) {
// code block 2
}
}
Below is the implementation of Nested if
statements:
// Java Program to implementation
// of Nested if statements
// Driver Class
public class AgeWeightExample {
// main function
public static void main(String[] args) {
int age = 25;
double weight = 65.5;
Output
You are eligible to donate blood.
Note: The first print statement is in a block of “if”
so the second statement is not in the block of “if”.
The third print statement is in else but that else
doesn’t have any corresponding “if”. That means
an “else” statement cannot exist without an “if”
statement.
SWITCH - CASE STATEMENTS
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid
month";
break;
}
System.out.println(monthString);
}
}
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9:
futureMonths.add("September");
case 10: futureMonths.add("October");
case 11:
futureMonths.add("November");
case 12:
futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month
number");
} else {
for (String monthName : futureMonths)
{
System.out.println(monthName);
}
}
}
}
August
September
October
November
December
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
Number of Days = 29
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
OUTPUT :
I am 11
DETERMINE IF A STUDENT IS PASS OR FAIL
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int percentage = ((a+b+c)/300) * 100;
if(a>33 && b>33 && c>33 && percentage >
40){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}
import java.util.Scanner;
class Income
{
public static void main(String args[])
{
double tax=0,it;
Scanner sc=new Scanner(System.in);
System.out.println("Enter income ");
it=sc.nextDouble();
if(it<=200000)
tax=0;
else if(it<=300000)
tax=0.1*(it-200000);
else if(it<=500000)
tax=(0.2*(it-300000))+(0.1*100000);
else if(it<=1000000)
tax=(0.3*(it-500000))
+(0.2*200000)+(0.1*100000);
else
tax=(0.4*(it-1000000))
+(0.3*500000)+(0.2*200000)+(0.1*100000);
System.out.println("Income tax amount is
"+tax);
}
}
import java.util.*;
public class RockPaperScissor {
while(true) {
System.out.println("Computer has
chosen it's move.");
System.out.println();
System.out.println("Now it's your
turn to choose. Good Luck!");
System.out.println();
//input
String userMove;
if(userMove.equals(computerMove)) {
System.out.println("Its a
tie!");
}
if(computerMove.equals("Paper")) {
System.out.println("Computer won!");
System.out.println("You won!");
System.out.println("Congratulations!");
}
}
else if(userMove.equals("Paper"))
{
if(computerMove.equals("Rock")) {
System.out.println("You won!");
System.out.println("Congratulations!");
}
else
if(computerMove.equals("Scissors")) {
System.out.println("Computer won!");
else
if(userMove.equals("Scissors")) {
if(computerMove.equals("Paper")) {
System.out.println("You won!");
System.out.println("Congratulations!");
}
else
if(computerMove.equals("Rock")) {
System.out.println("Computer won!");
System.out.println();
String playAgain;
System.out.println("Do you want
to play again? ");
System.out.println("Type
'yes' or 'no' ");
playAgain = scn.nextLine();
if(playAgain.equals("yes") ||
playAgain.equals("Yes") || playAgain.equals("no") ||
playAgain.equals("No")) {
System.out.println();
System.out.println("*******************************
**********************************************");
System.out.println();
break;
}
System.out.println();
System.out.println("Invalid
Input");
System.out.println();
}
if(playAgain.equals("no") ||
playAgain.equals("No")) {
break;
}
}
}}
LOOPS IN JAVA
1. For Loops
2. While Loops
3. Do - While Loops
FOR LOOPS
Initialization Expression
Test Expression
Update Expression
1. Initialization Expression
In this expression, we have to initialize the loop
counter to some value.
Example:
int i=1;
2. Test Expression
In this expression, we have to test the condition. If
the condition evaluates to true then, we will
execute the body of the loop and go to the update
expression. Otherwise, we will exit from the for a
loop.
Example:
i <= 10
3. Update Expression:
After executing the loop body, this expression
increments/decrements the loop variable by some
value.
Example:
i++;
class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10
Dry-Running Example 1
The program will execute in the following manner.
Program starts.
i is initialized with value 1.
Condition is checked. 1 <= 5 yields true.
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 <= 5 yields true.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 <= 5 yields true.
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 <= 5 yields true.
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 <= 5 yields true.
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 <= 5 yields false.
Flow goes outside the loop. Program terminates.
Example 3: (The Program prints the sum of x
ranging from 1 to 20)
Java
Java
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times)
// first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
1234 5
1234 5
1234 5
1234 5
1234 5
Syntax:
for (T element:Collection obj/array)
{
// loop body
// statement(s)
}
Java
// Main Function
public static void main(String args[])
{
// String array
String array[] = { "Ron", "Harry",
"Hermoine" };
Example:
Java
// Java infinite loop
class GFG {
public static void main(String args[])
{
for (int i = 1; i >= 1; i++) {
System.out.println("Infinite Loop " + i);
}
}
}
Output
Infinite Loop 1
Infinite Loop 2
...
Syntax:
for(;;){
//code to be executed
}
Example:
Java
public class GFG {
public static void main(String[] args)
{
for (;;) {
System.out.println("infinitive loop");
}
}
}
Output
infinite loop
infinite loop
....
WHILE LOOP
Syntax:
while (test_expression)
{
// statements
update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and
‘}’ after while( condition ) then by default while
statement will consider the immediate one
statement to be inside its block.
while (test_expression)
// single statement in while only
Example:
i <= 10
2. Update Expression: After executing the loop
body, this expression increments/decrements the
loop variable by some value.
Example:
i++;
How Does a While loop execute?
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.
If Condition yields true, the flow goes into the
Body.
If Condition yields false, the flow goes outside the
loop
The statements inside the body of the loop get
executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone
outside.
Flowchart For while loop (Control Flow):
Flow chart while loop (for Control Flow
class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
System.out.println("Hello World");
// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.
class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;
DO - WHILE LOOPS
Syntax:
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression);
Note: The test_expression for the do-while loop
must return a boolean value , else we would get
compile-time error.
For example:
Illustration:
do {
// Checking condition
// Note: It is being checked after
// minimum 1 iteration
while (i < 0);
}
}
Output
Print statement
Output explanation:
i <= 10
B. Update Expression: After executing the loop
body, this expression increments/decrements the
loop variable by some value. For example:
i++;
Execution of do-While loop
Control falls into the do-while loop.
The statements inside the body of the loop get
executed.
Updation takes place.
The flow jumps to Condition
Condition is tested.
If Condition yields true, go to Step 6.
If Condition yields false, the flow goes outside the
loop
The flow goes back to Step 2.
Flowchart do-while loop:
Implementation:
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Do-while loop
do {
// Update expression
i++;
}
// Test expression
while (i < 6);
}
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Output explanation:
Program starts.
i is initialized with value 1.
Execution enters the loop
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 < 6 yields true.
Execution enters the loop.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 < 6 yields false.
The flow goes outside the loop.
Example 2
// Class
class GFG {
// Do-while loop
do {
// Execution statements(Body of loop)
// Summing up
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 176
import java.io.*;
class GFG {
public static void main (String[] args) {
int i=1;
do
// only single statement in do block
System.out.println("Hello GFG!");
// this condition is false so only do block will
execute
while(i>=3);
}
}
Output
Hello GFG!
Syntax :
break;
In Java, a break statement is majorly used for:
To exit a loop.
Used as a “civilized” form of goto.
Terminate a sequence in a switch statement.
Using break to exit a loop
Example:
Java
// Java program to demonstrate using
// break to exit a loop
class GFG {
public static void main(String[] args)
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Out of Loop");
}
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump
out of the target block. We cannot break to any
label which is not defined for an enclosing block.
Syntax:
break label;
Example:
Java
// Java program to demonstrates using break with
goto
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:
Java
// Java program to demonstrate using break to
terminate a
// sequence in a switch statement.
class GFG {
public static void main(String args[])
{
int i = 2;
switch (i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("Invalid number");
}
}
}
Output
i is two.
Continue:
continue;
Using continue to continue a loop
Example:
Java
// Java program to demonstrates the continue
// statement to continue a loop
class GFG {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is 2
// skip and continue
if (i == 2)
continue;
Example:
Java
// Java program to demonstrates labeled continue
statement
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
We can use a break with the switch We can not use a continue with the
statement. switch statement.
The break statement terminates the The continue statement brings the next
whole loop early. iteration early.
PATTERN PRINTING
import java.util.*;
import java.lang.*;
// required sum
return sum;
}
// driver function
public static void main(String argc[])
{
int n = 20;
System.out.println("Sum of first " + n +
" Even numbers is: " +
evenSum(n));
}
}
PRINTING MULLTIPLICATION TABLE OF A
GIVEN NO.
import java.util.Scanner;
import java.io.*;
class Easy
// array declaration
Output
10 50 60 80 90
The above syntax is equivalent to:
Output
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime =
Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " +
(endTime - startTime) + " ms");
// Type 2
startTime =
Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: "
+ (endTime - startTime) + " ms");
// Type 3
startTime =
Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating
collection.size() first :: " + (endTime - startTime) +
" ms");
// Type 4
startTime =
Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j
> size ; j--] :: " + (endTime - startTime) + " ms");
}
}
Output
ARRAYS IN JAVA
Arrays in Java
Java Arrays
-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type
and the name. type declares the element type of
the array. The element type determines the data
type of each element that comprises the array.
Like an array of integers, we can also create an
array of other primitive data types like char, float,
double, etc., or user-defined data types (objects of
a class). Thus, the element type for the array
determines what type of data the array will hold.
Example:
Example:
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new
will automatically be initialized to zero (for numeric
types), false (for boolean), or null (for reference
types). Do refer to default array values in Java.
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)
Arrays-in-Java
import java.io.*;
class GFG {
public static void main (String[] args) {
System.out.println("Array Size:"+arr.length);
}
}
Output
Array Size:4
The Student Array contains five memory spaces
each of the size of Student class in which the
address of five Student objects can be stored. The
Student objects have to be instantiated using the
constructor of the Student class, and their
references should be assigned to the array
elements in the following way.
Example 2:
Below is the implementation of the above
mentioned topic:
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
Example 3
An array of objects is also created like :
class Student
{
Output
Dharma
sanvi
Rupa
Ajay
What happens if we try to access elements outside
the array size?
JVM throws ArrayIndexOutOfBoundsException to
indicate that the array has been accessed with an
illegal index. The index is either negative or
greater than or equal to the size of an array.
System.out.println(
"Trying to access element outside the size
of array");
System.out.println(arr[5]);
}
}
Output
Output
10
20
Complexity of the above method:
Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space
required.
// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column
// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
MultiDimensional-Array
// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods.
For example, the below program passes the array
to method sum to calculate the sum of the array’s
values.
Output
sum of array values : 15
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
Output
123
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
class Test {
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];
// array of Strings
String[] strArray = new String[3];
System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation of the above method:
The string “[I” is the run-time type signature for
the class object “array with component type int.”
The only direct superclass of an array type is
java.lang.Object.
The string “[B” is the run-time type signature for
the class object “array with component type byte.”
The string “[S” is the run-time type signature for
the class object “array with component type
short.”
The string “[L” is the run-time type signature for
the class object “array with component type of a
Class.” The Class name is then followed.
Java Array Members
Now, as you know that arrays are objects of a
class, and a direct superclass of arrays is a class
Object. The members of an array type are all of the
following:
class Test {
public static void main(String args[])
{
int intArray[] = { 1, 2, 3 };
Output
false
123
Explanation of the above Program:
In this example, intArray and cloneArray are not
the same object (intArray == cloneArray is false),
but they share the same contents because
primitive values are deeply copied.
For arrays containing objects, the references are
copied, so the objects themselves are not
duplicated.
Clone-of-Array
class Test {
public static void main(String args[])
{
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };
Output
false
true
True
PRACTICE SET ON ARRAYS
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][] = new int[3][3] ;
int arr1[][] = new int[3][3] ;
int sum[][] = new int [3][3];
//INPUT OF ARRAY 1
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr[i][j] = sc.nextInt();
}
}
//INPUT OF ARRAY 2
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr1[i][j] = sc.nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
sum[i][j] = arr[i][j] + arr1[i][j] ;
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}
REVERSE AN ARRAY
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = {3,4,5};
for (int i =0;i<arr.length/2 ; i++) {
int temp = arr[i] ;
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};
return max;
}
// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is "
+ largest());
}
}
import java.util.*;
class Array {
public static void main(String[] args) {
int a[]={1,423,6,46,34,23,13,53,4};
SORTING AN ARRAY
import java.util.Arrays;
class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
METHODS IN JAVA
1. main(String args[])
Execution Process
Example
1. class Demo
2. {
3. static //static block
4. {
5. System.out.println("Static block");
6. }
7. public static void main(String args[]) //static met
hod
8. {
9. System.out.println("Static method");
10. }
11. }
Output:
Static block
Static method
Example
1. class DemoStaticBlock
2. {
3. Static //static block
4. {
5. System.out.println("Static block");
6. }
7. }
Output:
Error: Main method not found in the class Demo,
please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend
javafx.application.Application
Example
Output:
Java
Example
1. class OverloadMain
2. {
3. public static void main(int a) //overloaded main
method
4. {
5. System.out.println(a);
6. }
7. public static void main(String args[])
8. {
9. System.out.println("main method incoked");
10. main(6);
11. }
12. }
Output:
Predefined Method
User-defined Method
Predefined Method
Demo.java
Output:
User-defined Method
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
EvenOdd.java
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Output 1:
Output 2:
Addition.java
Output:
Static Method
Display.java
Output:
Instance Method
InstanceMethodExample.java
9. }
10. int s;
11. //user-defined method because we have not us
ed static keyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }
Output:
o Accessor Method
o Mutator Method
Example
Example
Student.java
Abstract Method
Syntax
Demo.java
Output:
Abstract method…
Factory method
Java
import java.io.*;
void add(double,double);
class Adder{
System.out.println(“sum =”+(a+b));
System.out.println(“sum=”+(a+b));
ad.add(5.4,7.2);
}}
Eg:
Java
class Adder{
System.out.println(“sum =”+(a+b));
System.out.println(“sum=”+(a+b+c));
ad.add(5,6);
ad.add(5.4,7.2);
}}
Geeks, now you would be up to why do we need
method overloading?
import java.io.*;
// Class 1
// Helper class
class Addition {
// Method 1
int sum = a + b;
return sum;
}
// Method 2
int sum = a + b + c;
return sum;
// Class 2
// Main class
class GFG {
// method
+ sum1);
System.out.println(
Output
Java
// Java Program to Illustrate Method Overloading
import java.io.*;
// Class 1
// Helper class
class Addition {
int sum = a + b + c;
return sum;
{
double sum = a + b + c;
return sum;
class GFG {
System.out.println(
+ sum3);
Output
sum of the three integer value :6
Java
import java.io.*;
// Class 1
// Helper class
class Geek {
// Method 1
// Method 2
// Class 2
// Main class
class GFG {
{
// Creating object of above class
geek.geekIdentity("Mohit", 1);
geek.geekIdentity(2, "shubham");
Output
geekName :Mohit Id :1
geekName :shubham Id :2
Example 4
Java
// ReturnType is Different
import java.io.*;
// Class 1
// Helper class
class Addition {
// Method 1
// Summing up
int sum = a + b;
return sum;
// Method 2
return sum;
// Class 2
// Main class
class GFG {
// Main driver method
try {
System.out.println(
System.out.println(
"sum of the three integer value :" +
sum2);
catch (Exception e) {
System.out.println(e);
OUTPUT
Syntax of Varargs
// method body
class Test1 {
for (int i : a)
System.out.println();
// Driver code
// one parameter
fun(100);
// four parameters
fun(1, 2, 3, 4);
// no parameter
fun();
}
Output
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
class Test2 {
+ a.length);
for (int i : a)
System.out.println();
}
fun2("CSPortal", 1, 2, 3, 4, 5);
fun2("forGeeks");
Output
String: GeeksforGeeks
100 200
String: CSPortal
12345
String: forGeeks
int fact(int n)
return 1;
else
return n*fact(n-1);
Working of Recursion
3= 3 *2*1 (6)
4= 4*3*2*1 (24)
5= 5*4*3*2*1 (120)
Below is the implementation of the factorial:
// recursive method
int fact(int n)
{
int result;
if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}
// Driver Class
class Recursion {
// Main function
public static void main(String[] args)
{
GFG f = new GFG();
System.out.println("Factorial of 3 is "
+ f.fact(3));
System.out.println("Factorial of 4 is "
+ f.fact(4));
System.out.println("Factorial of 5 is "
+ f.fact(5));
}
}
Output
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
2. Fibonacci Series
Fibonacci Numbers are the numbers is the integer
sequence where Fib(N) = Fib(N-2) + Fib(N-1).
Below is the example to find 3,4,5.
// Driver Function
class GFG {
// Main function
public static void main(String[] args)
{
// Fibonacci of 3
System.out.println("Fibonacci of " + 3 + " "
+ Fib(3));
// Fibonacci of 4
System.out.println("Fibonacci of " + 4 + " "
+ Fib(4));
// Fibonacci of 5
System.out.println("Fibonacci of " + 5 + " "
+ Fib(5));
}
}
Output
Fibonacci of 3 2
Fibonacci of 4 3
Fibonacci of 5 5
Stack Overflow error
If the base case is not reached or not defined, then
the stack overflow problem may arise. Let us take
an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8),
fact(7) and so on but the number will never reach
100. So, the base case is not reached. If the
memory is exhausted by these functions on the
stack, it will cause a stack overflow error.
class GFG {
static void printFun(int test)
{
if (test < 1)
return;
else {
System.out.printf("%d ", test);
// Statement 2
printFun(test - 1);
Output
321123
import java.io.*;
import java.util.Scanner;
class Program
{
/*function to find table of number*/
static void table(int no)
{
for (int i = 1; i<=10; i++)
{
System.out.print(i*no+" ");
}
}
public static void main(String[] args)
{
System.out.println("Table of 6=");
table(6);//calling function
System.out.println("\nTable of 5=");
table(5);//calling function
}
}
class GFG
{
// Returns sum of first
// n natural numbers
public static int recurSum(int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
// Driver code
public static void main(String args[])
{
int n = 5;
System.out.println(recurSum(n));
}
}
import java.io.*;
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
for (int i = 0; i < N; i++) {
// Print the number
System.out.print(num1 + " ");
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}
OOPs Concepts:
Class
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
1. Class:
2. Object:
3. Data Abstraction:
4. Encapsulation:
8. Message Passing:
// Class 1
// Helper class
class Employee {
// first attribute
int id;
// second attribute
int salary;
// third attribute
String name;
// Method 1
public void printDetails()
{
// Print and display commands
System.out.println("My id is " + id);
System.out.println("This is my name " +
name);
}
// Method 2
public int getSalary()
{
// Class 2
// Main class
class Custom {
Output
This is the custom class
My id is 23
This is my name Ritu bhatiya
My id is 25
This is my name Amit thripathi
Salary of robin : 150000$
ID : 23
ACCESS MODIFIERS
1. access modifiers
2. non-access modifiers
Private Y N N N
Default Y Y N N
Protecte Y Y Y N
d
Public Y Y Y Y
1) Private
class A{
private int data=40;
private void msg(){System.out.println("Hello
java");}
}
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except
nested class.
2) Default
If you don't use any modifier, it is treated as
default by default. The default modifier is
accessible only within package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its
method msg() is default so it cannot be accessed
from outside the package.
2) Protected
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
class A{
protected void msg(){System.out.println("Hello
java");}
}
Syntax
class ABC{
private variable;
// Class 1
// Helper class
class GetSet {
// Method 1 - Getter
public String getName() { return name; }
// Method 2 - Setter
public void setName(String N)
{
// Class 2
// Main class
class GFG {
Example 2
Java
// Java Program to Illustrate Getter and Setter
class GetSet {
// Member variable of this class
private int num;
// Method 1 - Setter
public void setNumber(int number)
{
// Checking if number is between 1 to 10
exclusive
if (number < 1 || number > 10) {
// Method 2 - Getter
public int getNumber() { return num; }
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();
CODE SYNTAX : -
class ABC{
private variable;
class GetSet {
// Member variable of this class
private int num;
// Method 1 - Setter
public void setNumber(int number)
{
// Checking if number is between 1 to 10
exclusive
if (number < 1 || number > 10) {
// Method 2 - Getter
public int getNumber() { return num; }
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();
// Calling method 1 inside main() method
obj.setNumber(5);
OUTPUT : -
CONSTRUCTORS IN JAVA
1. <class_name>(){}
CODE : -
Bike is created
Output:
0 null
0 null
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
o By constructor
o By assigning the values of one object into
another
o By clone() method of Object class
Output:
111 Karan
111 Karan
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+"
"+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Output:
111 Karan
111 Karan
// Given K trials
int K = 5;
int i, guess;
System.out.println(
"A number is chosen"
+ " between 1 to 100."
+ "Guess the number"
+ " within 5 trials.");
System.out.println(
"Guess the number:");
if (i == K) {
System.out.println(
"You have exhausted"
+ " K trials.");
System.out.println(
"The number was " + number);
}
}
// Driver Code
public static void
main(String arg[])
{
// Function Call
guessingNumberGame();
}
}
OUTPUT : -
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
System.out.println(b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}
Output
100
600
super keyword
super is a reserved keyword in java i.e, we can’t
use it as an identifier.
super is used to refer super-class’s instance as well
as static members.
super is also used to invoke super-class’s method
or constructor.
super keyword in java programming language
refers to the superclass of the class where the
super keyword is currently being used.
The most common use of super keyword is that it
eliminates the confusion between the superclasses
and subclasses that have methods with same
name.
super can be used in various contexts as given
below:
class Parent {
// instance variable
int a = 10;
// static variable
static int b = 20;
}
Output
10
20
Similarities in this and super
We can use this as well as super anywhere except
static area. Example of this is already shown above
where we use this as well as super inside public
static void main(String[]args) hence we get
Compile Time Error since cannot use them inside
static area.
We can use this as well as super any number of
times in a program.
Both are non-static keyword.
Example
class RRR {
// instance variable
int a = 10;
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
System.out.println(a);
}
Output
100
600
9000
class Parent {
// instance variable
int a = 36;
// static variable
static float x = 12.2f;
}
System.out.println(x);
}
public static void main(String[] args)
{
new Base().GFG();
}
}
Output
1
60.3
class RR {
int first = 22;
int second = 33;
Output
22
33
22
33
1
2
1
2
a = this.first
b = this.second
Here, what is happening is that the value of
instance variable(i.e, first) and the value of static
variable(i.e, second) are assigned to the garcia
method’s local variables a and b respectively.
Hence value of a and b comes out to be 22 and 33
respectively. Next we have new RR().louis(1, 2)
hence here flow goes to the louis method of RR
class and in that we have:
this.first = m
this.second = n
Here, above what happens is that the value of the
louis method’s local variables i.e, m and n are
assigned to the instance as well as static variables
i.e, first and second respectively.
Hence, the value of first and second variables are
same which we have passed into the louis method
i.e, 1 and 2 respectively.
class Vehicle {
Vehicle() { System.out.println("Vehicle is
created."); }
}
Bike(String brand)
{
super(); // it calls Vehicle(), the parent class
// constructor of class Bike
this();
System.out.println("Bike brand is " + brand);
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
For example :
// class A
class A
{
int x = 10;
}
// class B
class B extends A
{
int x = 20;
}
// Driver class
public class Test
{
public static void main(String args[])
{
A a = new B(); // object of type B
Output:
10
Explanation :
ABSTRACTION : -
ABSTRACT CLASS : -
Points to Remember
running safely
Understanding the real scenario of Abstract
class
File: TestAbstraction1.java
drawing circle
File: TestBank.java
File: TestAbstraction2.java
10. }
11. //Creating a Test class which calls abstract and
non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
bike is created
running safely..
gear changed
1. class Bike12{
2. abstract void run();
3. }
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Output:I am a
I am b
I am c
I am d
INTERFACES IN JAVA
// A simple interface
interface Player
{
final int id = 10;
int move();
}
Relationship Between Class and Interface
A class can extend another class similar to this an
interface can extend another interface. But only a
class can extend to another interface, and vice-
versa is not allowed.
Difference Between Class and Interface
Class Interface
Implementation:
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Cannot be
Cannot be
instantiated, but it
Instantiation instantiated, as it is
can be invoked if
absolutely abstract
main () exist
Abstract keyword
Interface keyword
used to declare the
used to declare
abstract class.
interface. Also,
Keywords Also, the abstract
interface can be
Used class can be
implemented by
extended by using
using the keyword
the keyword
“implements”
“extends”
Example 1:
// Class 1
// First Parent class
class Parent1 {
// Class 2
// Second Parent Class
class Parent2 {
// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {
Example 2:
GrandParent
/ \
/ \
Parent1 Parent2
\ /
\ /
Test
The code is as follows
void fun() {
// Class 2
// First Parent class
class Parent1 extends GrandParent {
void fun() {
// Class 3
// Second Parent Class
class Parent2 extends GrandParent {
void fun() {
// Class 4
// Inheriting from multiple classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {
Example 3:
// Interface 1
interface PI1 {
// Default method
default void show()
{
// Interface 2
interface PI2 {
// Default method
default void show()
{
// Main class
// Implementation class code
class TestClass implements PI1, PI2 {
Output
Default PI1
Default PI2
Now Executing showOfPI1() showOfPI2()
Default PI1
Default PI2
Example 4:
// Default method
default void show()
{
// Print statement
System.out.println("Default GPI");
}
}
// Interface 2
// Extending the above interface
interface PI1 extends GPI {
}
// Interface 3
// Extending the above interface
interface PI2 extends GPI {
}
// Main class
// Implementation class code
class TestClass implements PI1, PI2 {
Output
Default GPI
interface intfA {
void m1();
}
interface intfB {
void m2();
}
class GFG {
public static void main(String[] args)
{
sample ob1 = new sample();
Example
Dog IS_A Animal
Car IS_A Vehicle
Employee IS_A Person
Surgeon IS_A Doctor etc.
Below is the implementation of the above method:
// Parent Class
class Person1 {
// Variables
int id;
String name;
// Java Methods
void set_Person(int id, String name)
{
try {
this.id = id;
this.name = name;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
void disp_Person()
{
System.out.print(id + "\t" + name + "\t");
}
}
// Child Class
class Employee1 extends Person1 {
int sal;
String desgn;
void set_Emp(int id, String name, String desgn,
int sal)
{
try {
set_Person(id, name);
this.desgn = desgn;
this.sal = sal;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
void disp_Emp()
{
disp_Person();
System.out.print(desgn + "\t" + sal);
}
// Main function
public static void main(String args[])
{
// Single-Level inheritance
// Class B ---> Class A, which means that class B is
derived from Class A
class A {
int a;
void set_A(int x) {
a = x;
}
}
// Multilevel inheritance
// Class C ---> Class B ---> Class A
// Class C is derived from Class B which in
correspondence derived from Class A
class A {
int a;
void set_A(int x) {
a = x;
}
}
// Child of Class A
class B extends A {
int b;
void set_B(int x) {
b = x;
}
}
// Hierarchical inheritance
// Class C ---> Class A <--- Class B
// Both Class B and C inherits Class A
class A {
int a;
void set_A(int x) {
a = x;
System.out.println("Setting A's value to = "
+ x);
}
}
B b = new B();
b.set_B(10);
b.set_A(15);
}
}
Output
Setting C's value to = 5
Setting A's value to = 50
Setting B's value to = 10
Setting A's value to = 15
4. Inheritance in Interfaces
// Java program to demonstrate inheritance in
// interfaces.
import java.io.*;
interface intfA {
void geekName();
}
Rohit
JIIT
An interface can also extend multiple interfaces.
// Java program to demonstrate multiple
inheritance
// in interfaces
import java.io.*;
interface intfA {
void geekName();
}
interface intfB {
void geekInstitute();
}
Output
Rohit
JIIT
CSE
Example
// Method 1
void name() {
// Print statement
System.out.println("This is the GFG class");
}
// Method 2
// Main drive method
public static void main(String[] args) {
Example:
// Class 1
// Helper class
class First {
// Class 2
// Main class
class Second extends First {
// Method overloading
void check(String name)
{
// Printing the name of the class method
having the
// parameter
System.out.println("This is the class " +
name);
}
// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");
Output
This is the class Second
This is the class First
This is the class First
Real-life Example
// Interface
interface salary {
void insertsalary(int salary);
}
// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary()
{ System.out.println(this.salary); }
}
// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary()
{ System.out.println(this.salary); }
}
ob1.insertsalary(200000);
ob1.printSalary();
}
}
Output
100000
200000
COMPILED LANGUAGES : -
INTERPRETED LANGUAGES : -
JAVA PACKAGES
Built-in Packages
Syntax :
Import a Class
If you find a class you want to use, for example,
the Scanner class, which is used to get user
input, write the following code:
Example
import java.util.Scanner;
Example
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
}}
Import a Package
There are many packages to choose from. In the
previous example, we used the Scanner class from
the java.util package. This package also contains
date and time facilities, random-number generator
and other utility classes.
To import a whole package, end the sentence with
an asterisk sign (*). The following example will
import ALL the classes in the java.util package:
Example
import java.util.*;
User-defined Packages
To create your own package, you need to
understand that Java uses a file system directory to
store them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
System.out.println("This is my package!");
}}
This is my package!
import package.name.*;
Example: Importing java.util package
// Main Class
class GFG {
// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");
package FirstPackage ;
Implementation: To Create a Class Inside A
Package
// Print message
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
Again, in order to generate the above-desired
output first do use the commands as specified use
the following specified commands
Procedure:
Hi Everyone
Hello
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new
MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
3.1. New
A NEW Thread (or a Born Thread) is a thread that’s
been created but not yet started. It remains in this
state until we start it using the start() method.
NEW
Copy
3.2. Runnable
When we’ve created a new thread and called the
start() method on that, it’s moved from NEW to
RUNNABLE state. Threads in this state are either
running or ready to run, but they’re waiting for
resource allocation from the system.
RUNNABLE
Copy
Note that in this example, it’s not always
guaranteed that by the time our control reaches
t.getState(), it will be still in the RUNNABLE state.
3.3. Blocked
A thread is in the BLOCKED state when it’s
currently not eligible to run. It enters this state
when it is waiting for a monitor lock and is trying to
access a section of code that is locked by some
other thread.
t1.start();
t2.start();
Thread.sleep(1000);
System.out.println(t2.getState());
System.exit(0);
}
}
BLOCKED
Copy
3.4. Waiting
A thread is in WAITING state when it’s waiting for
some other thread to perform a particular action.
According to JavaDocs, any thread can enter this
state by calling any one of the following three
methods:
object.wait()
thread.join() or
LockSupport.park()
Note that in wait() and join() – we do not define any
timeout period as that scenario is covered in the
next section.
try {
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
System.out.println(WaitingState.t1.getState())
;
}
}
Copy
Let’s discuss what we’re doing here:
WAITING
Copy
3.5. Timed Waiting
A thread is in TIMED_WAITING state when it’s
waiting for another thread to perform a particular
action within a stipulated amount of time.
thread.sleep(long millis)
wait(int timeout) or wait(int timeout, int nanos)
thread.join(long millis)
LockSupport.parkNanos
LockSupport.parkUntil
To read more about the differences between wait()
and sleep() in Java, have a look at this dedicated
article here.
TIMED_WAITING
Copy
3.6. Terminated
This is the state of a dead thread. It’s in the
TERMINATED state when it has either finished
execution or was terminated abnormally.
@Override
public void run() {
// No processing in this block
}
}
Copy
Here, while we’ve started thread t1, the very next
statement Thread.sleep(1000) gives enough time
for t1 to complete and so this program gives us the
output as:
TERMINATED
Copy
In addition to the thread state, we can check the
isAlive() method to determine if the thread is alive
or not. For instance, if we call the isAlive() method
on this thread:
Assert.assertFalse(t1.isAlive());
Copy
It returns false. Put simply, a thread is alive if and
only if it has been started and has not yet died.
Thread(ThreadGroup
Allocates a new Thread
group, Runnable
object.
target)
Methods Action
Performed
Returns an
estimate of
the number
of active
threads in the
activeCount()
current
thread’s
thread group
and its
subgroups
Determines if
the currently
running
checkAccess() thread has
permission to
modify this
thread
Throws
CloneNotSup
portedExcepti
on as a
clone()
Thread can
not be
meaningfully
cloned
Methods Action
Performed
Returns a
reference to
currentThread() the currently
executing
thread object
Prints a stack
trace of the
current
dumpStack()
thread to the
standard
error stream
Copies into
the specified
array every
active thread
enumerate(Thread[] tarray) in the current
thread’s
thread group
and its
subgroups
Returns a
map of stack
getAllStackTraces()
traces for all
live threads
Returns the
context
getContextClassLoader() ClassLoader
for this
Thread
Methods Action
Performed
Returns the
default
handler
invoked when
getDefaultUncaughtExceptionHand a thread
ler() abruptly
terminates
due to an
uncaught
exception
Returns the
getId() identifier of
this Thread
Returns this
getName() thread’s
name
Returns this
getPriority() thread’s
priority
Returns an
array of stack
trace
elements
getStackTrace()
representing
the stack
dump of this
thread
thread
Returns the
thread group
getThreadGroup() to which this
thread
belongs
Returns the
handler
invoked when
this thread
getUncaughtExceptionHandler() abruptly
terminates
due to an
uncaught
exception
Returns true
if and only if
the current
thread holds
holdsLock(Object obj)
the monitor
lock on the
specified
object
Interrupts this
interrupt()
thread
interrupted
Tests if this
isAlive() thread is
alive
Tests if this
thread is a
isDaemon()
daemon
thread
Tests whether
this thread
isInterrupted()
has been
interrupted
Waits at most
millis
join(long millis) milliseconds
for this
thread to die
method is
called;
otherwise,
this method
does nothing
and returns
Sets the
context
setContextClassLoader(ClassLoade
ClassLoader
r cl)
for this
Thread
Marks this
thread as
either a
setDaemon(boolean on)
daemon
thread or a
user thread
thread
Changes the
name of this
thread to be
setName(String name)
equal to the
argument
name.
Set the
handler
invoked when
setUncaughtExceptionHandler( Thr this thread
ead.UncaughtExceptionHandler abruptly
eh) terminates
due to an
uncaught
exception
Changes the
setPriority(int newPriority) priority of this
thread
subject to the
precision and
accuracy of
system
timers and
schedulers
Causes this
thread to
begin
execution;
the Java
start()
Virtual
Machine calls
the run
method of
this thread
Returns a
string
representatio
n of this
thread,
toString()
including the
thread’s
name,
priority, and
thread group
willing to
yield its
current use of
a processor
equals() Method
finalize() Method
getClass() Method
hashCode() Method
notify() Method
notifyAll() Method
toString() Method
wait() Method
Example: Java program to demonstrate usage of
Thread class
// Importing package
package generic;
// Class 1
// Helper class implementing Runnable interface
class Helper implements Runnable {
//
public void run() {
// Print statement
System.out.println("thread2 going to
sleep for 5000");
// Print statement
System.out.println("Thread2
interrupted");
}
}
}
// Class 2
// Helper class extending Runnable interface
public class Test implements Runnable {
// Method 1
// run() method of this class
public void run() {
// Method 2
// Main driver method
public static void main(String[] args) {
System.out.println("Thread1 name:
" + thread1.getName());
System.out.println("Thread1 ID: "
+ thread1.getId());
// Fetching the priority and state of thread1
System.out.println("Priority of thread1 =
" + thread1.getPriority());
try {
thread2.join();
}
catch (InterruptedException e) {
thread2.yield();
Thread.enumerate(tarray);
// Display commands
System.out.println("List of active
threads:");
System.out.printf("[");
System.out.println(thread);
}
// Display commands
System.out.printf("]\n");
System.out.println(Thread.getAllStackTraces()
);
ClassLoader classLoader =
thread1.getContextClassLoader();
System.out.println(classLoader.toString());
System.out.println(thread1.getDefaultUncaug
htExceptionHandler());
thread2.setUncaughtExceptionHandler(thread
1.getDefaultUncaughtExceptionHandler());
thread1.setContextClassLoader(thread2.getCo
ntextClassLoader());
thread1.setDefaultUncaughtExceptionHandler
(thread2.getUncaughtExceptionHandler());
ThreadGroup grp =
thread1.getThreadGroup();
System.out.println("ThreadGroup to
which thread1 belongs " + grp.toString());
System.out.println(thread1.getUncaughtExcep
tionHandler());
System.out.println("Does thread1 holds
Lock? " + thread1.holdsLock(obj2));
Thread.dumpStack();
}
}
Output:
3
main
Thread1 name: Thread-0
Thread1 ID: 10
Priority of thread1 = 5
RUNNABLE
Is thread2 interrupted? false
Is thread2 alive? true
Is thread1 a daemon thread? true
Is thread1 interrupted? false
thread1 waiting for thread2 to join
thread2 going to sleep for 5000 ms
thread2 going to sleep for 5000 ms
Thread2 interrupted
New name set for thread 1child thread xyz
Thread[child thread xyz, 5, main]
List of active threads:
[Thread[main, 5, main]
Thread[Thread-1, 5, main]
null
]
{Thread[Signal Dispatcher, 9,
system]=[Ljava.lang.StackTraceElement;@339097
52,
Thread[Thread-1, 5,
main]=[Ljava.lang.StackTraceElement;@55f96302,
Thread[main, 5,
main]=[Ljava.lang.StackTraceElement;@3d4eac69,
Thread[Attach Listener, 5,
system]=[Ljava.lang.StackTraceElement;@42a579
93,
Thread[Finalizer, 8,
system]=[Ljava.lang.StackTraceElement;@75b84c
92,
Thread[Reference Handler, 10,
system]=[Ljava.lang.StackTraceElement;@6bc7c0
54}
sun.misc.Launcher$AppClassLoader@73d16e93
null
Printing stack trace elements for thread1:
ThreadGroup to which thread1 belongs
java.lang.ThreadGroup[name=main, maxpri=10]
java.lang.ThreadGroup[name=main, maxpri=10]
Does thread1 holds Lock? false
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown
Source)
at generic.Test.main(Test.java:111)
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in
main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "
+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "
+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "
+ t3.getPriority());
// 2
System.out.println("t1 thread priority : "
+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "
+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Main thread
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Output
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:
Example
// Main class
// ThreadDemo
// Extending Thread class
class GFG extends Thread {
// Method 1
// run() method for the thread that is
// invoked as threads are started
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// main thread priority is set to 6 now
Thread.currentThread().setPriority(6);
Compile-time
Run-time
Logical
// Class 1
class StackOverflow {
// Class 2
// Main class
public class GFG {
Example 2
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
Output
8 is the smallest Number
Checked exceptions
Unchecked exceptions
CHECKED EXCEPTIONS : -
Example:
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
Output:
To fix the above program, we either need to
specify a list of exceptions using throws, or we
need to use a try-catch block. We have used
throws in the below program. Since
FileNotFoundException is a subclass of
IOException, we can just specify IOException in the
throws list and make the above program compiler-
error-free.
Example:
UNCHECKED EXCEPTIONS : -
Example:
// Main class
class GFG {
Example:
try {
// Some I/O operation here
} catch( final IOException ex ) {
throw new RuntimeException( "I/O operation
failed", ex );
}
1. ArrayIndexOutOfBoundsException: This
exception is thrown when you attempt to access an
array index that is out of bounds.
2. NullPointerException: This exception is thrown
when you attempt to access a null object
reference.
3. ArithmeticException: This exception is thrown
when you attempt to divide by zero or perform an
invalid arithmetic operation.
Conclusion : -
Example Exception
// Main class
class GFG {
Errors Exceptions
Unchecked exceptions
Errors can occur at occur at runtime whereas
compile time. checked exceptions occur
at compile time
IOException Unchecked
Exceptions :
java.lang.OutOfMemor ArrayIndexOutOfBoundEx
yError ception,
NullPointerException,
ArithmeticException.
ERRORS IN JAVA
Java Error
1. class StackExample {
2. public static void check(int i)
3. {
4. if (i == 0)
5. return;
6. else {
7. check(i++);
8. }
9. }
10. }
11. public class Main {
12.
13. public static void main(String[] args)
14. {
15. StackExample.check(5);
16. }
17. }
Code Explanation
Exception Error
class DivByZero {
int var2 = 5;
int var3 = 0;
"Division of va1"
+ ans1);
System.out.println(
"Division of va1"
+ ans2);
at DivByZero.main(File.java:14)
class RTErrorDemo {
{
int arr[] = new int[5];
// Array size is 5
arr[9] = 250;
at RTErrorDemo.main(File.java:10)
class MisspelledVar {
int Sum = a + b;
System.out.println(
+ sum);
1 error
class PrintingSentence {
String s = "GeeksforGeeks";
System.out.println("Welcome to " + s)
}
}
System.out.println("Welcome to " + s)
1 error
class MissingParenthesis {
System.out.println("Printing 1 to 5 \n");
int i;
System.out.println(i + "\n");
} // class ends
1 error
class IncorrectLoop {
int a = 7, ans;
int i;
ans = a * i;
System.out.println(ans + "\n");
2 errors
int reversednum = 0;
int remainder;
while (num != 0) {
= reversednum * 10
+ remainder;
num /= 10;
+ reversednum);
Output:
class IncorrectMessage {
int a = 2, b = 8, c = 6;
System.out.println(
System.out.println(
// been System.out.println
// to make logic
else
System.out.println(
Output:
Syntax Error:
int x, y;
z = x + y; // z is undefined, y in uninitialized.
Java Exceptions
When executing Java code, different errors can
occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable
things.
When an error occurs, Java will normally stop and
generate an error message. The technical term for
this is: Java will throw an exception (throw an
error).
try {
System.out.println(myNumbers[10]); // error!
}}
Example
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
}}
Finally
The finally statement lets you execute code,
after try...catch, regardless of the result:
Example
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
}
}}
Example
else {
}}
The output will be:
Example
checkAge(20);
Types of Exceptions
Java defines several types of exceptions that relate
to its various class libraries. Java also allows users
to define their own exceptions.
Built-in Exceptions
Checked Exception
Unchecked Exception
User-Defined Exceptions
Let us discuss the above-defined listed exception
that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are
available in Java libraries. These exceptions are
suitable to explain certain error situations.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases,
users can also create exceptions, which are called
‘user-defined Exceptions’.
1. printStackTrace()
This method prints exception information in the
format of the Name of the exception: description of
the exception, stack trace.
Example:
//program to print the exception information using
printStackTrace() method
import java.io.*;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
Output
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
2. toString()
The toString() method prints exception information
in the format of the Name of the exception:
description of the exception.
Example:
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}
Output
java.lang.ArithmeticException: / by zero
3. getMessage()
The getMessage() method prints only the
description of the exception.
Example:
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
How Does JVM Handle an Exception?
Default Exception Handling: Whenever inside a
method, if an exception has occurred, the method
creates an Object known as an Exception Object
and hands it off to the run-time system(JVM). The
exception object contains the name and
description of the exception and the current state
of the program where the exception has occurred.
Creating the Exception Object and handling it in
the run-time system is called throwing an
Exception. There might be a list of the methods
that had been called to get to the method where
an exception occurred. This ordered list of methods
is called Call Stack. Now the following procedure
will happen.
// Class
// ThrowsExecp
class GFG {
Output : -
Example:
// Method 1
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found
// within this method.
static int divideByZero(int a, int b)
{
return i;
}
int res = 0;
// Method 2
// Found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[])
{
int a = 1;
int b = 0;
Output
/ by zero
How Programmer Handle an Exception?
Customized Exception Handling: Java exception
handling is managed via five keywords: try, catch,
throw, throws, and finally. Briefly, here is how they
work. Program statements that you think can raise
exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch
block) and handle it in some rational manner.
System-generated exceptions are automatically
thrown by the Java run-time system. To manually
throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be
specified as such by a throws clause. Any code that
absolutely must be executed after a try block
completes is put in a finally block.
Example:
// Class
class GFG {
Output
program output
Unchecked exception
class NestedTry {
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
Output
ArrayIndexOutOfBoundsException
Element at such index does not exists
Example 2:
class Nesting {
// main method
public static void main(String args[])
{
// main try-block
try {
// try-block2
try {
// try-block3
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
// handles ArrayIndexOutOfBoundsException if
any
catch (ArrayIndexOutOfBoundsException e4)
{
System.out.print("ArrayIndexOutOfBoundsE
xception");
System.out.println(" main try-block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-
block");
}
}
}
Output
ArrayIndexOutOfBoundsException main try-block
1. public Exception()
Parameters
a. message
It is of type string for the error message or
detail message.
Parameters
1. message
It is of type string for the error message or
detail message.
2. cause
The cause is saved so that
the Throwable.getCause() method can
retrieve it. The null value defines that the
cause is nonexistent or unknown.
Parameters
1. cause
Parameters
1. message
It is a detailed message.
2. cause
The cause is saved so that
the Throwable.getCause() method can
retrieve it. The null value defines that the
cause is nonexistent or unknown.
3. enableSuppression
It is a Boolean value that defines whether
the suppression is enabled or not.
4. writableStackTrace
It is a Boolean value that defines whether
the stack trace is writable or not.
CustomExceptionExample1.java
20. {
21.
22. // create method checkEligibility() to ch
eck whether the given is valid for exam or not
23. static void checkEligibility (int age) th
rows InvalidAgeException
24. {
25. // use conditional statement to check
age
26. if(age < 18){
27. // we throw InvalidAgeException w
hen the age is less than 18
28. throw new InvalidAgeException("
You are not eligible for the exam.");
29. }else {
30. System.out.println("You are eligibl
e for the exam.");
31. }
32. }
33.
34. // main() method start
35. public static void main(String args[])
36. {
37. // create scanner class object to take
input from user
38. Scanner scan = new Scanner(Syste
m.in);
39.
40. // declare variable age to store the us
er input
41. int age;
42.
43. // take input from the user
44. System.out.println("Please enter you
r age:");
45. age = scan.nextInt();
46.
47. scan.close();
48.
49. try
50. {
51. // call method checkEligibility() to
check whether the user is eligible for exam or
not
52. checkEligibility(age);
53. }
54. catch (InvalidAgeException exceptio
n)
55. {
56. System.out.println("We found an e
xcaption:");
57.
58. // printing the message from Invali
dAgeException object
59. System.out.println(exception);
60.
61. }
62. }
63. }
Output:
Description:
CustomExceptionExample2.java
22. {
23. // create method checkExistence() to ch
eck whether the given language already exists
in the list or not
24. static void checkExistence (ArrayList<
String> languages, String language) throws A
lreadyExistException
25. {
26. // use conditional statement to check
the existence of the language
27. if(languages.contains(language)){
28. // we throw AlreadyExistException
when the language is already exist in the list
29. throw new AlreadyExistException
(language +" is already exist in the list.");
30. }else {
31. languages.add(language);
32. System.out.println(language + " is
added to the ArrayList successfully.");
33. for(int i = 0; i < languages.size();
i++) {
34. System.out.println(languages.g
et(i));
35. }
36. }
37. }
38.
39. // main() method start
40. public static void main(String args[])
41. {
42. // declare ArrayList with some langua
ges
43. ArrayList<String> languages = new
ArrayList<>(Arrays.asList("Java", "Python", "Ja
vaScript"));
44.
45. // create scanner class object to take
input from user
46. Scanner scan = new Scanner(Syste
m.in);
47.
48. // declare variable lang to store the u
ser input
49. String lang;
50.
51. // take input from the user
52. System.out.println("Enter language t
o enter in the ArrayList:");
53. lang = scan.nextLine();
54.
55. scan.close();
56.
57. try
58. {
59. // call method checkExistence() to
check whether the language is already exist in
the list or not
60. checkExistence(languages, lang);
61. }
62. catch (AlreadyExistException except
ion)
63. {
64. System.out.println("We found an e
xcaption:");
65.
66. // printing the message from Alrea
dyExistException object
67. System.out.println(exception);
68.
69. }
70. }
71. }
Output:
Description:
throw keyword
cannot
propagate
checked
throws keyword
Propagati exceptions. It is
is used to
on of only used to
4. propagate the
Exception propagate the
checked
s unchecked
Exceptions only.
Exceptions that
are not checked
using the
throws keyword.
Examples
1. Java throw
java.lang.ArithmeticException
at GFG.main(GFG.java:10)
2. Java throws
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
if (f != null) {
System.out.println("Closing FileWriter");
f.close();
}
}
Introduction
The Java platform includes a collections framework.
A collection is an object that represents a group of
objects (such as the classic Vector class). A
collections framework is a unified architecture for
representing and manipulating collections,
enabling collections to be manipulated
independently of implementation details.
The primary advantages of a collections framework
are that it:
Collection Interfaces
The collection interfaces are divided into two
groups. The most basic
interface, java.util.Collection, has the following
descendants:
java.util.Set
java.util.SortedSet
java.util.NavigableSet
java.util.Queue
java.util.concurrent.BlockingQueue
java.util.concurrent.TransferQueue
java.util.Deque
java.util.concurrent.BlockingDeque
java.util.SortedMap
java.util.NavigableMap
java.util.concurrent.ConcurrentMap
java.util.concurrent.ConcurrentNavigableMap
Be of a particular type.
Be not null.
Obey some arbitrary predicate.
Collection Implementations
Classes that implement the collection interfaces
typically have names in the form of
<Implementation-style><Interface>. The general
purpose implementations are summarized in the
following table:
Hash
Balan
Interf Hash Resizab Linked Table +
ced
ace Table le Array List Linked
Tree
List
HashS TreeSe LinkedHash
Set
et t Set
LinkedL
List ArrayList
ist
ArrayDe LinkedL
Deque
que ist
HashM TreeM LinkedHash
Map
ap ap Map
The general-purpose implementations support all
of the optional operations in the collection
interfaces and have no restrictions on the elements
they may contain. They are unsynchronized, but
the Collections class contains static factories
called synchronization wrappers that can be used
to add synchronization to many unsynchronized
collections. All of the new implementations
have fail-fast iterators, which detect invalid
concurrent modification, and fail quickly and
cleanly (rather than behaving erratically).
The AbstractCollection, AbstractSet, AbstractList, A
bstractSequentialList and AbstractMap classes
provide basic implementations of the core
collection interfaces, to minimize the effort
required to implement them. The API
documentation for these classes describes
precisely how each method is implemented so the
implementer knows which methods must be
overridden, given the performance of the basic
operations of a specific implementation.
Concurrent Collections
Applications that use collections from more than
one thread must be carefully programmed. In
general, this is known as concurrent programming.
The Java platform includes extensive support for
concurrent programming. See Java Concurrency
Utilities for details.
Collections are so frequently used that various
concurrent friendly interfaces and implementations
of collections are included in the APIs. These types
go beyond the synchronization wrappers discussed
previously to provide features that are frequently
needed in concurrent programming.
These concurrent-aware interfaces are available:
BlockingQueue
TransferQueue
BlockingDeque
ConcurrentMap
ConcurrentNavigableMap
LinkedBlockingQueue
ArrayBlockingQueue
PriorityBlockingQueue
DelayQueue
SynchronousQueue
LinkedBlockingDeque
LinkedTransferQueue
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentSkipListSet
ConcurrentHashMap
ConcurrentSkipListMap
Design Goals
The main design goal was to produce an API that
was small in size and, more importantly, in
"conceptual weight." It was critical that the new
functionality not seem too different to current Java
programmers; it had to augment current facilities,
rather than replace them. At the same time, the
new API had to be powerful enough to provide all
the advantages described previously.
To keep the number of core interfaces small, the
interfaces do not attempt to capture such subtle
distinctions as mutability, modifiability, and
resizability. Instead, certain calls in the core
interfaces are optional, enabling implementations
to throw an UnsupportedOperationException to
indicate that they do not support a specified
optional operation. Collection implementers must
clearly document which optional operations are
supported by an implementation.
To keep the number of methods in each core
interface small, an interface contains a method
only if either:
N Method Descri
o ption
.
1 public boolean It is
add(E e) used to
insert
an
element
in this
collecti
on.
2 public boolean It is
addAll(Collectio used to
n<? extends E> insert
c) the
specifie
d
collecti
on
element
s in the
invokin
g
collecti
on.
3 public boolean It is
remove(Object used to
element) delete
an
element
from
the
collecti
on.
4 public boolean It is
removeAll(Colle used to
ction<?> c) delete
all the
element
s of the
specifie
d
collecti
on from
the
invokin
g
collecti
on.
5 default boolean It is
removeIf(Predic used to
ate<? super E> delete
filter) all the
element
s of the
collecti
on that
satisfy
the
specifie
d
predicat
e.
6 public boolean It is
retainAll(Collect used to
ion<?> c) delete
all the
element
s of
invokin
g
collecti
on
except
the
specifie
d
collecti
on.
7 public int size() It
returns
the
total
number
of
element
s in the
collecti
on.
8 public void It
clear() remove
s the
total
number
of
element
s from
the
collecti
on.
9 public boolean It is
contains(Object used to
element) search
an
element
.
1 public boolean It is
0 containsAll(Coll used to
ection<?> c) search
the
specifie
d
collecti
on in
the
collecti
on.
1 public Iterator It
1 iterator() returns
an
iterator.
1 public Object[] It
2 toArray() convert
s
collecti
on into
array.
1 public <T> T[] It
3 toArray(T[] a) convert
s
collecti
on into
array.
Here,
the
runtime
type of
the
returne
d array
is that
of the
specifie
d array.
1 public boolean It
4 isEmpty() checks
if
collecti
on is
empty.
1 default It
5 Stream<E> returns
parallelStream() a
possibly
parallel
Stream
with the
collecti
on as
its
source.
1 default It
6 Stream<E> returns
stream() a
sequent
ial
Stream
with the
collecti
on as
its
source.
1 default It
7 Spliterator<E> generat
spliterator() es a
Splitera
tor over
the
specifie
d
element
s in the
collecti
on.
1 public boolean It
8 equals(Object matche
element) s two
collecti
ons.
1 public int It
9 hashCode() returns
the
hash
code
number
of the
collecti
on.
Iterator interface
N Method Description
o.
1 public It returns true
boolean if the iterator
hasNext( has more
) elements
otherwise it
returns false.
2 public It returns the
Object element and
next() moves the
cursor pointer
to the next
element.
3 public It removes
void the last
remove() elements
returned by
the iterator. It
is less used.
Iterable Interface
1. Iterator<T> iterator()
Collection Interface
The Collection interface is the interface which is
implemented by all the classes in the collection
framework. It declares the methods that every
collection will have. In other words, we can say
that the Collection interface builds the foundation
on which the collection framework depends.
List Interface
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//
Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It
uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It
maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is
fast because no shifting is required.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
Stack
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
PriorityQueue
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue
<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue eleme
nts:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two eleme
nts:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
ArrayDeque
ArrayDeque class implements the Deque interface.
It facilitates us to use the Deque. Unlike queue, we
can add or delete the elements from both the
ends.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String
>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
Set Interface
HashSet
1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Vijay
Ravi
Ajay
LinkedHashSet
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<
String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
TreeSet
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
Illustration:
class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;
Output
Array 1:[]
Array 2:[]
Array 1:[1, 2, 3, 4, 5]
Array 2:[1, 2, 3, 4, 5]
Explanation of the above Program:
ArrayList is a dynamic array and we do not have to
specify the size while creating it, the size of the
array automatically increases when we
dynamically add and remove items. Though the
actual library implementation may be more
complex, the following is a very basic idea
explaining the working of the array when the array
becomes full and if we try to add an item:
Creates a bigger-sized memory on heap memory
(for example memory of double size).
Copies the current memory elements to the new
memory.
The new item is added now as there is bigger
memory available now.
Delete the old memory.
1. ArrayList()
This constructor is used to build an empty array
list. If we wish to create an empty ArrayList with
the name arr, then, it can be created as:
3. ArrayList(int capacity)
This constructor is used to build an array list with
the initial capacity being specified. Suppose we
wish to create an ArrayList with the initial size
being N, then, it can be created as:
// Main class
class GFG {
Output
[Geeks, For, Geeks]
2. Changing Elements
After adding the elements, if we wish to change
the element, it can be done using the set()
method. Since an ArrayList is indexed, the element
which we wish to change is referenced by the
index of the element. Therefore, this method takes
an index and the updated element which needs to
be inserted at that index.
Below is the implementation of the above
approach:
// main class
class GFG {
// Main class
class GFG {
Output
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
4. Iterating the ArrayList
There are multiple ways to iterate through the
ArrayList. The most famous ways are by using the
basic for loop in combination with a get() method
to get the element at a specific index and the
advanced for a loop.
Example
// Main class
class GFG {
System.out.println();
Output
Geeks For Geeks
Geeks For Geeks
5. Get Elements
class GFG {
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList();
// add the number
list.add(9);
list.add(5);
list.add(6);
System.out.println(list);
// get method
Integer n= list.get(1);
System.out.println("at indext 1 number is:"+n);
}
}
Output
[9, 5, 6]
at indext 1 number is:5
6. Add Elements Between Two Numbers
Output
[1, 2, 4]
[1, 2, 3, 4]
7. ArrayList Sort
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(2);
list.add(4);
list.add(3);
list.add(1);
System.out.println("Before sorting list:");
System.out.println(list);
Collections.sort(list);
System.out.println("after sorting list:");
System.out.println(list);
}
}
Output
Before sorting list:
[2, 4, 3, 1]
after sorting list:
[1, 2, 3, 4]
8. Size of Elements
list.add(1);
list.add(2);
list.add(3);
list.add(4);
int b = list.size();
System.out.println("The size is :" + b);
}
}
Output
The size is :4
Complexity of Java ArrayList
Inserting
Element in O(1) O(N)
ArrayList
Operation Time Space
Complexit Complexit
y y
Removing
Element from O(N) O(1)
ArrayList
Traversing
Elements in O(N) O(N)
ArrayList
Replacing
Elements in O(1) O(1)
ArrayList
Conclusion
Implementation:
System.out.println(current_Date);
// print the time and date
}
}
Output
Fri Nov 20 07:12:42 UTC 2020
Conversion of GMT form to IST using two classes
called TimeZone, it also comes under util package
of Java, and SimpleDateFormat, which comes
under Text package of Java.
Implementation:
formatDate.setTimeZone(TimeZone.getTimeZ
one("IST"));
// converting to IST or format the Date as IST
System.out.println(formatDate.format(date));
// print formatted date and time
}
}
Output
20/11/2020 12:42:41 IST
Method 2: Using LocalDateTime class
Implementation:
Implementation:
LocalDateTime d = LocalDateTime.now();
ZonedDateTime UTCtime =
d.atZone(ZoneId.of("UTC"));
//"d" is the current date and
//"ZonedDateTime" accepts "d" as UTC
//"atZone" specifies the time zone
// converting to IST
ZonedDateTime ISTtime =
UTCtime.withZoneSameInstant(
ZoneId.of("Asia/Kolkata"));
//"withZoneSameInstant" convert the time
// to given time zone
System.out.println(ISTtime);
// print the time and date
}
}
Output
2020-11-20T12:42:42.723246+05:30[Asia/Kolkata]
Method 3: Using Clock class
Implementation:
import java.time.*;
class GFG {
public static void main (String[] args)
{
System.out.println(Clock.systemUTC().instant(
));
//"Clock" is the class
//"systemUTC()" is the method which
represent the time in UTC form
}
}
Output
2020-11-20T07:12:37.598048Z
Constructors
boolean a = d3.after(d1);
System.out.println("Date d3 comes after " +
"date d2: " + a);
boolean b = d3.before(d2);
System.out.println("Date d3 comes before "+
"date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);
Output:
METHOD DESCRIPTION
Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
Program 2: Java program to demonstrate
getMaximum() method.
Output:
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
Program 3: Java program to demonstrate the
getMinimum() method.
Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add()
method.
Output:
java.lang.Object
java.util.Calendar
java.util.GregorianCalendar
Prior to the institution of the Gregorian calendar,
New Year's Day was March 25. To avoid confusion,
this calendar always uses January 1. A manual
adjustment may be made if desired for dates that
are prior to the Gregorian changeover and which
fall between January 1 and March 24.
Week Of Month
For example,
if getFirstDayOfWeek() is SUNDAY and getMinimal
DaysInFirstWeek() is 4, then the first week of
January 1998 is Sunday, January 4 through
Saturday, January 10. These days have
a WEEK_OF_MONTH of 1. Thursday, January 1
through Saturday, January 3 have
a WEEK_OF_MONTH of 0.
If getMinimalDaysInFirstWeek() is changed to 3,
then January 1 through January 3 have
a WEEK_OF_MONTH of 1.
Field Default
Value
ERA AD
YEAR 1970
MONTH JANUARY
DAY_OF_MONTH 1
the first
DAY_OF_WEEK day of
week
WEEK_OF_MONTH 0
DAY_OF_WEEK_IN_MONT 1
H
AM_PM AM
HOUR, HOUR_OF_DAY,
MINUTE, SECOND, 0
MILLISECOND
Example:
// begin output
System.out.println("Current Time");
System.out.println("DAY_OF_WEEK_IN_M
ONTH: "
+
calendar.get(Calendar.DAY_OF_WEEK_IN_
MONTH));
System.out.println("AM_PM: " +
calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " +
calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " +
calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " +
calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " +
calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " +
calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+
(calendar.get(Calendar.ZONE_OFFSET)/(6
0*60*1000))); // in hours
System.out.println("DST_OFFSET: "
+
(calendar.get(Calendar.DST_OFFSET)/(60
*60*1000))); // in hours
Since:
JDK1.1
See Also:
Calendar.Builder
Field Summary
Fields
Modifier Field and Description
and Type
static int AD
Value of the ERA field indicating the
common era (Anno Domini), also
known as CE.
static int BC
Value of the ERA field indicating the
period before the common era
(before Christ), also known as BCE.
Constructors
Constructor and Description
GregorianCalendar()
Constructs a default GregorianCalendar using
the current time in the default time zone with
the default FORMAT locale.
GregorianCalendar(int year, int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given
date set in the default time zone with the default
locale.
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute)
Constructs a GregorianCalendar with the given
date and time set for the default time zone with
the default locale.
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute,
int second)
Constructs a GregorianCalendar with the given
date and time set for the default time zone with
the default locale.
GregorianCalendar(Locale aLocale)
Constructs a GregorianCalendar based on the
current time in the default time zone with the
given locale.
GregorianCalendar(TimeZone zone)
Constructs a GregorianCalendar based on the
current time in the given time zone with the
default FORMAT locale.
GregorianCalendar(TimeZone zone, Locale aL
ocale)
Constructs a GregorianCalendar based on the
current time in the given time zone with the
given locale.
Method Summary
Field Detail
BC
See Also:
AD
See Also:
Constructor Detail
GregorianCalendar
public GregorianCalendar()
GregorianCalendar
Parameters:
GregorianCalendar
Parameters:
GregorianCalendar
Parameters:
GregorianCalendar
Parameters:
GregorianCalendar
Parameters:
GregorianCalendar
Parameters:
hourOfDay - the value used to set
the HOUR_OF_DAY calendar field in the calendar.
Method Detail
setGregorianChange
Parameters:
getGregorianChange
Returns:
isLeapYear
Determines if the given year is a leap year.
Returns true if the given year is a leap year. To
specify BC year numbers, 1 - year number must
be given. For example, year BC 4 is specified as -
3.
Parameters:
Returns:
getCalendarType
Overrides:
Returns:
"gregory"
Since:
1.8
See Also:
Locale
extensions, Locale.Builder.setLocale(Locale), Local
e.Builder.setUnicodeLocaleKeyword(String, String)
equals
Overrides:
Parameters:
Returns:
See Also:
Calendar.compareTo(Calendar)
hashCode
Overrides:
Returns:
See Also:
Object.equals(java.lang.Object), System.identityHa
shCode(java.lang.Object)
add
Adds the specified (signed) amount of time to the
given calendar field, based on the calendar's
rules.
Specified by:
Parameters:
field - the calendar field.
Throws:
IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.
See Also:
Calendar.roll(int,int), Calendar.set(int,int)
roll
Specified by:
Parameters:
Throws:
IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.
See Also:
add(int,int), Calendar.set(int,int)
roll
Overrides:
Parameters:
Throws:
IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.
Since:
1.2
See Also:
getMinimum
Specified by:
Parameters:
Returns:
See Also:
getMaximum
Specified by:
Parameters:
Returns:
See Also:
getGreatestMinimum
Specified by:
Parameters:
Returns:
See Also:
getLeastMaximum
Specified by:
Parameters:
Returns:
See Also:
getActualMinimum
Overrides:
Parameters:
Returns:
Since:
1.2
See Also:
getActualMaximum
Overrides:
Parameters:
Returns:
Since:
1.2
See Also:
clone
Overrides:
Returns:
See Also:
Cloneable
getTimeZone
Overrides:
Returns:
setTimeZone
Sets the time zone with the given time zone value.
Overrides:
Parameters:
isWeekDateSupported
Overrides:
Returns:
true (always)
Since:
1.7
See Also:
getWeekYear
Returns the week year represented by
this GregorianCalendar. The dates in the weeks
between 1 and the maximum week number of the
week year have the same week year value that
may be one year before or after
the YEAR (calendar year) value.
Overrides:
Returns:
Throws:
Since:
1.7
See Also:
isWeekDateSupported(), getWeeksInWeekYear(), C
alendar.getFirstDayOfWeek(), Calendar.getMinimal
DaysInFirstWeek()
setWeekDate
Overrides:
Parameters:
Throws:
Since:
1.7
See Also:
isWeekDateSupported(), Calendar.getFirstDayOfW
eek(), Calendar.getMinimalDaysInFirstWeek()
getWeeksInWeekYear
For example, if this GregorianCalendar's date is
December 31, 2008 with the ISO 8601 compatible
setting, this method will return 53 for the period:
December 29, 2008 to January 3, 2010
while getActualMaximum(WEEK_OF_YEAR) will
return 52 for the period: December 31, 2007 to
December 28, 2008.
Overrides:
Returns:
Since:
1.7
See Also:
computeFields
Specified by:
See Also:
Calendar.complete()
computeTime
Specified by:
Throws:
See Also:
Calendar.complete(), Calendar.computeFields()
toZonedDateTime
Since this object supports a Julian-Gregorian
cutover date and ZonedDateTime does not, it is
possible that the resulting year, month and day
will have different values. The result will represent
the correct date in the ISO calendar system, which
will also be the same value for Modified Julian
Days.
Returns:
Since:
1.8
from
public
static GregorianCalendar from(ZonedDateTime zdt)
Since ZonedDateTime does not support a Julian-
Gregorian cutover date and uses ISO calendar
system, the return GregorianCalendar is a pure
Gregorian calendar and uses ISO 8601 standard
for week definitions, which has MONDAY as
the FirstDayOfWeek and 4 as the value of
the MinimalDaysInFirstWeek.
Parameters:
Returns:
Throws:
IllegalArgumentException - if the zoned date-time
is too large to represent as a GregorianCalendar
Since:
1.8
API Specification
// Single-Line Comment
/*
* Multiple-Line comment
*/
/**
* JavaDoc comment
*/
By writing a number of comments, it does not
affect the performance of the Java program as all
the comments are removed at compile time.
JavaDoc Format: –
It has two parts: – a description which is followed
by block tags.
Some Integrated Development Environments (IDE)
automatically generate the JavaDoc file like
NetBeans, IntelliJ IDEA, Eclipse, etc.
Generation of JavaDoc: –
To create a JavaDoc you do not need to compile
the java file. To create the Java documentation API,
you need to write Javadoc followed by file name.
JavaDoc Tags
@autho author_nam
Describes an author
r e
Example 1 : –
package exa;
import java.util.Scanner;
/**
*
* @author Yash
*/
public class Example {
/**
* This is a program for adding two numbers in java.
* @param args
*/
public static void main(String[] args)
{
/**
* This is the main method
* which is very important for
* execution for a java program.
*/
int x, y;
Scanner sc = new Scanner(System.in);
/**
* Declared two variables x and y.
* And taking input from the user
* by using Scanner class.
*
*/
x = sc.nextInt();
y = sc.nextInt();
/**
* Storing the result in variable sum
* which is of the integer type.
*/
int sum = x + y;
/**
* Using standard output stream
* for giving the output.
* @return null
*/
System.out.println("Sum is: " + sum);
}
}
javadoc exa
Screenshot of javadoc: –
ANNONATIONS IN JAVA
/**
* Indicates that the annotated method is a test
method.
* This annotation should be used only on
parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
Note that the annotation type declaration is itself
annotated. Such annotations are called meta-
annotations. The first
(@Retention(RetentionPolicy.RUNTIME)) indicates
that annotations with this type are to be retained
by the VM so they can be read reflectively at run-
time. The second
(@Target(ElementType.METHOD)) indicates that
this annotation type can be used to annotate only
method declarations.
Here is a sample program, some of whose methods
are annotated with the above interface:
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;
// Interface
interface Age {
int x = 21;
void getAge();
}
// Main class
class AnonymousDemo {
oj1.getAge();
}
}
Output
Age is 21
Lambda Expressions:
Lambda expressions basically express instances of
functional interfaces (An interface with single
abstract method is called functional interface. An
example is java.lang.Runnable). lambda
expressions implement the only abstract function
and therefore implement functional interfaces
lambda expressions are added in Java 8 and
provide below functionalities.
class Test {
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x) ->
System.out.println(2 * x);
Output
10
Table of difference:
It is a method without
It is a class without
name.(anonymous
name.
function)
an interface that
interface which contains
contains any number
a single abstract method.
of abstract methods.
Inside Anonymous
Inside Lambda
inner class, “this”
Expression, “this” always
always refers to
refers to current outer
current anonymous
class object that is,
inner class object but
enclosing class object.
not to outer object.
At the time of
At the time of compilation, no
compilation, a separate .class file will be
separate .class file will generated. It simply
be generated. convert it into private
method outer class.
object.
GENERICS IN JAVA
Why Generics?
The Object is the superclass of all other classes,
and Object reference can refer to any object. These
features lack type safety. Generics add that type of
safety feature. We will discuss that type of safety
feature in later examples.
Generic Class
Like C++, we use <> to specify parameter types in
generic class creation. To create objects of a
generic class, we use the following syntax.
Java
// Java program to show working of user defined
// Generic classes
Java
// Java program to show multiple
// type parameters in Java Generics
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
obj.print();
}
}
Output
GfG
15
Generic Functions:
We can also write generic functions that can be
called with different types of arguments based on
the type of arguments passed to the generic
method. The compiler handles each method.
Java
// Java program to show working of user defined
// Generic functions
class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getNa
me()
+ " = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer
argument
genericDisplay(11);
Java
// Java program to show working
// of user-defined Generic classes
error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they
are the references to different types because their
type parameters differ. Generics add type safety
through this and prevent errors.
Type Parameters in Java Generics
The type parameters naming conventions are
important to learn generics thoroughly. The
common type parameters are as follows:
T – Type
E – Element
K – Key
N – Number
V – Value
Advantages of Generics:
Programs that use Generics has got many benefits
over non-generic code.
Java
// Java program to demonstrate that NOT using
// generics can cause run time exceptions
import java.util.*;
class Test
{
public static void main(String[] args)
{
// Creatinga an ArrayList without any type
specified
ArrayList al = new ArrayList();
al.add("Sachin");
al.add("Rahul");
al.add(10); // Compiler allows this
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
Java
// Using Java Generics converts run time exceptions
into
// compile time exception.
import java.util.*;
class Test
{
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new
ArrayList<String> ();
al.add("Sachin");
al.add("Rahul");
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}
Output:
Java
// We don't need to typecast individual members of
ArrayList
import java.util.*;
class Test {
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList<String> al = new
ArrayList<String>();
al.add("Sachin");
al.add("Rahul");
Java
public class GFG {
swap(j, j + 1, a);
}
}
}
for (T i : a)
{
System.out.print(i + ", ");
}
System.out.println();
}
}
Output
Sorted Integer array : 6, 22, 41, 50, 58, 100,
Sorted Character array : a, c, d, g, t, v, x,
Sorted String array : Abhinay, Bharat, Chandu,
Kalam, Rohit, Sam, Virat,
Here, we have created a generics method. This
same method can be used to perform operations
on integer data, string data, and so on.
class GFG {
public static void main(String[] args)
{
File Created!
In Java, the concept Stream is used in order to
perform I/O operations on a file. So at first, let us
get acquainted with a concept known as Stream in
Java.
Streams in Java
In Java, a sequence of data is known as a stream.
This concept is used to perform I/O operations on a
file.
There are two types of streams :
1. Input Stream:
The Java InputStream class is the superclass of all
input streams. The input stream is used to read
data from numerous input devices like the
keyboard, network, etc. InputStream is an abstract
class, and because of this, it is not useful by itself.
However, its subclasses are used to read data.
There are several subclasses of the InputStream
class, which are as follows:
AudioInputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
StringBufferInputStream
ObjectInputStream
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using
FileInputStream.
Methods of InputStream
S Method Description
No
.
2. Output Stream:
The output stream is used to write data to
numerous output devices like the monitor, file, etc.
OutputStream is an abstract superclass that
represents an output stream. OutputStream is an
abstract class and because of this, it is not useful
by itself. However, its subclasses are used to write
data.
ByteArrayOutputStream
FileOutputStream
StringBufferOutputStream
ObjectOutputStream
DataOutputStream
PrintStream
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using
FileOutputStream.
Methods of OutputStream
S. Method Description
No.
1. Byte Stream:
This stream is used to read or write byte data. The
byte stream is again subdivided into two types
which are as follows:
Byte Input Stream: Used to read byte data from
different devices.
Byte Output Stream: Used to write byte data to
different devices.
2. Character Stream:
This stream is used to read or write character data.
Character stream is again subdivided into 2 types
which are as follows:
Returns an array of
list() the files in the String[]
directory.
Creates a new
mkdir() Boolean
directory.
Create a File
Read from a File
Write to a File
Delete a File
Now let us study each of the above operations in
detail.
1. Create a File
try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has
occurred.");
e.printStackTrace();
}
}
}
Output
An error has occurred.
2. Read from a File: We will use the Scanner class
in order to read contents from a file. Following is a
demonstration of how to read contents from a file
in Java :