Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Apollo Java

Uploaded by

vikasmoni084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Apollo Java

Uploaded by

vikasmoni084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 211

Java Programming Tutorial for Beginners

Java is a high-level programming language originally developed by Sun Microsystems and


released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX. This tutorial gives a complete understanding of Java. This reference
will take you through simple and practical approaches while learning Java Programming
language.

Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:

• Desktop Applications such as acrobat reader, media player, antivirus, etc.

• Web Applications.

• Enterprise Applications such as banking applications.

• Mobile

• Embedded System

• Smart Card

• Robotics

• Games, etc.

History and Versions of Java

History

• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language

project in June 1991. The small team of sun engineers called Green Team.
• Initially it was designed for small, embedded systems in electronic appliances like set-

top boxes.

• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

• After that, it was called Oak and was developed as a part of the Green project.

• Why Oak? Oak is a symbol of strength and chosen as a national tree of many

countries like the U.S.A., France, Germany, Romania, etc.

• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak

Technologies.

• Why had they choose the name Java for Java language? The team gathered to

choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",

"jolt", "DNA", etc. They wanted something that reflected the essence of the

technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to

say. According to James Gosling, "Java was one of the top choices along with Silk".

Since Java was so unique, most of the team members preferred Java than other

names.

• Java is an island in Indonesia where the first coffee was produced (called Java coffee).

It is a kind of espresso bean. Java name was chosen by James Gosling while having a

cup of coffee nearby his office.

• Notice that Java is just a name, not an acronym.

• Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary

of Oracle Corporation) and released in 1995.

• In 1995, Time magazine called Java one of the Ten Best Products of 1995.

• JDK 1.0 was released on January 23, 1996. After the first release of Java, there have

been many additional features added to the language. Now Java is being used in

Windows applications, Web applications, enterprise applications, mobile applications,

cards, etc. Each new version adds new features in Java.


JAVA VERSIONS

Version Release Details

JDK Alpha and Beta 1995

JDK 1.0 23rd Jan 1996

JDK 1.1 19th Feb 1997

J2SE 1.2 8th Dec 1998

J2SE 1.3 8th May 2000

J2SE 1.4 6th Feb 2002

J2SE 5.0 30th Sep 2004

Java SE 6 11th Dec 2006

Java SE 7 28th July 2011

Java SE 8 18th Mar 2014

Java SE 9 21st Sep 2017

Java SE 10 20th Mar 2018

Java SE 11 September 2018

Java SE 12 March 2019


Java SE 13 September 2019

Java SE 14 March 2020

Java SE 15 September 2020

Java SE 16 March 2021

Java SE 17 September 2021

Java SE 18 March 2022

Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version
is release in March month and an odd version released in September month.

Java Installation

Java is a high-level programming language originally developed by Sun Microsystems and


released in 1995. Java is one of the world’s most important and widely used computer
languages. Today, it is still the first and best choice for developing web-based applications.
Simply put: much of the modern world runs on Java code. Java really is that important. Java
has continually adapted to changes in the programming environment and to changes in the
way that programmers program. Java runs on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java.
This reference will take you through simple and practical approaches while learning Java
Programming language.

Java Installation Process

Step 1:Go to the Google search -> Java jdk download.


Step 2:Click -> JDK Download button.

Step 3:Choose the JDK for your operating system.Click -> Download the "exe" installer
Step 4:Click -> "Accept License Agreement"

Step 5:Click ->Download


Step 6: 1. Click -> Next to start installing process

Step 7:JDK installation process take some time


Step 8: Copy JDK installed directory path. Then go to This PC -> Right Click -> Properties
Step 9: Click -> "Advanced system settings" on the left Side.

Step 10: Click -> Environment variables Button


Step 11: Select the system variable -> Path -> Click Edit ->
Step 12: You will see a TABLE listing for all existing PATH entries. Click -> "New" -> paste
your path -> then click ok
Step 13:Start -> Enter cmd (or) Command Prompt -> Choose Command Prompt -> Type
javac,next type java and press Enter
Step 14:Go to the Google -> Intellij download.

Step 15:Click -> Intellij link -> Click -> Download


Step 16:Click -> Choose Community Download -> Click download.

Step 17: You can see, intellij IDEA is installed directory ("C:\Program Files\…). Accept the
defaults and follow the screen instructions to install intellij IDEA.Click -> Next.
Step 18:Click -> Next .
Step 19:Click -> install .
Step 20:intellij IDEA Installing
Step 21:Click -> Finish
Step 22:Start -> Enter intellij IDEA -> Open intellij IDEA
Basic Program in Java

Let's create the Hello World java Program.

class basic {..}


In Java, every program begins with a class definition. In the program, basic is the name of the
class, and the class definition is:
class basic
{
......
......
}

For now, just remember that every Java program has a class definition, and the name of the
class should match the file name in Java.

public static void main(String[] args) { ... }


This is the main method. Every program in Java must contain the main method. The Java
compiler starts executing the code from the main method.For now, just remember that the
main function is the entry point of your Java application, and it's mandatory in a Java
program.The signature of the main method in Java is
public static void main(String[] args)
{
...
..
...
}

System.out.println("Welcome Back");
The code above is a print statement. It prints the text Welcome Back to standard output (your
screen). The text inside the quotation marks is called string in java.Notice the print statement
is inside the main function, which is inside the class definition

Source Code
//01 Hello World
public class basic {
public static void main(String args[])
{
System.out.println("Welcome Back");
}
}

Output
Welcome Back

Command Line Arguments in Java

A command-line argument is nothing but the information that we pass after typing the name
of the Java program during the program execution. The command requires no arguments. The
code illustrates that args length gives us the number of command line arguments. If we
neglected to check args length, the command would crash if the user ran it with too few
command-line arguments.

A command-line argument is information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java
program is quite easy. They are stored as strings in the String array passed to main ( ).

Source Code
//02 Command Line Arguments in Java
import java.lang.*;

class command
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output
ram
sam
ravi

Single and Multi Line Comments in Java

The comments are the statements that are not executed by the compiler and interpreter. It
can be used to provide information or explanation about the variable, method, class or any
statement. It can also be used to hide program code for a specific time.

1. Single Line comments are started by // and may be positioned after a statement on the
same line, but not before.

Example:
//single line comment

2. Multi-Line comments are defined between /* and */. They can span multiple lines and may
even been positioned between statements.

Example:
/*
Multi
Line
Comment
*/

Source Code
//03 Single and Multi Line Comment in Java
import java.lang.*;

class comments
{
public static void main(String args[])
{
System.out.println("Welcome To Tutor Joes");
/*
In publishing and graphic design, Lorem ipsum is a placeholder te
xt commonly used to demonstrate the visual form of a document or a typeface withou
t relying on meaningful content. Lorem ipsum may be used as a placeholder before f
inal copy is available.
*/
}
}

Output
Welcome To Tutor Joes

Variables in Java

A variable in simple terms is a storage place which has some memory allocated to it.
Basically, a variable used to store some form of data. Different types of variables require
different amounts of memory, and have some specific set of operations which can be applied
on them.

Syntax:
Datatype variable_name = variable_value;

Example:
To store the numeric value 25 in a variable named "a":
int a = 25;

Variables Rules:

• Variable name don’t start variable name with digits.

• Beginning with underscore is valid but not recommended.

• Special character not allowed in the name of variable.

• Blank or White spaces are not allowed.

• Don’t use keywords to name of you variable.

Source Code
//04
import java.lang.*;

class variables
{
public static void main(String args[])
{
String name="Tutor Joes";
int age=25;
float percent=25.25f;
char gender='M';
boolean married=false;
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Percent : "+percent);
System.out.println("Gender : "+gender);
System.out.println("Married : "+married);
}
}

Output
Name : Tutor Joes
Age : 25
Percent : 25.25
Gender : M
Married : false

Type Casting in Java

Type casting is a way of converting data from one data type to another data type. This
process of data conversion is also known as type conversion.

There are two types of casting in Java as follows:

1. Widening Casting (automatically)


2. Narrowing Casting (manually)

1. Widening Casting (automatically)

• This type of casting takes place when two data types are automatically converted. It is

also known as Implicit Conversion. This involves the conversion of a smaller data type

to the larger type size.

• byte -> short -> char -> int -> long -> float -> double

2. Narrowing Casting (manually)

• if you want to assign a value of larger data type to a smaller data type, you can

perform Explicit type casting or narrowing. This is useful for incompatible data types

where automatic conversion cannot be done.

• double -> float -> long -> int -> char -> short -> byte

Source Code
//04 Type Casting in Java
/*
Widening Casting
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting
double -> float -> long -> int -> char -> short -> byte
*/
import java.lang.*;

class casting
{
public static void main(String args[])
{
int a=10;
double b=a,d=25.5385;
int c=(int)d;
System.out.println("Int : "+a);
System.out.println("Double : "+b);
System.out.println("Double : "+d);
System.out.println("Int : "+c);

}
}

Output
Int : 10
Double : 10.0
Double : 25.5385
Int : 25

Arithmetic Operators in Java

The Java programming language supports various arithmetic operators for all floating-point
and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), /
(division), and % (modulo).

1. Addition(+): This operator is a binary operator and is used to add two operands.

2. Subtraction(-): This operator is a binary operator and is used to subtract two

operands.

3. Multiplication(*): This operator is a binary operator and is used to multiply two

operands.

4. Division(/): This is a binary operator that is used to divide the first operand(dividend)

by the second operand(divisor) and give the quotient as result.

5. Modulus(%): This is a binary operator that is used to return the remainder when the

first operand(dividend) is divided by the second operand(divisor).


The arithmetic operators perform addition, subtraction, multiplication, division, and modulus
operations.

Source Code
//Arithmetic Operators
public class Arithmetic {
public static void main(String args[])
{
int a=123,b=10;
System.out.println("Addition : "+(a+b));
System.out.println("Subtraction : "+(a-b));
System.out.println("Multiplication : "+(a*b));
System.out.println("Division : "+(a/b));
System.out.println("Modulus : "+(a%b));

}
}

Output
Addition : 133
Subtraction : 113
Multiplication : 1230
Division : 12
Modulus : 3

Arithmetic Assignment operators in Java

The five arithmetic assignment operators are a form of short hand. Various textbooks call
them "compound assignment operators" or "combined assignment operators". Their usage
can be explaned in terms of the assignment operator and the arithmetic operators.

Compound Operator Sample Expression Expanded Form


+= x+=2 x=x+2

-= y -=6 y=y-6

*= z *=7 z=z*7

/= a /=4 a=a/4

%= b %=9 b= b%9

An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =

Source Code
public class Assignment
{
public static void main(String args[])
{
int a=123;
System.out.println(a);
a+=10;
System.out.println(a);
a-=10;//a=a-10
System.out.println(a);
a*=10;
System.out.println(a);
a/=10;
System.out.println(a);
a%=10;
System.out.println(a);
}
}
Output
123
133
123
1230
123
3

Relational Operators in Java

Relational Operators are a bunch of binary operators that are used to check for relations
between two operands including equality, greater than, less than, etc. They return a boolean
result after the comparison and are extensively used in looping statements as well as
conditional if-else statements and so on.Relational operator checks the relationship between
two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Operator uses

== equality operator

!= non-equality operator

< less than operator

> greater than operator

<= less than or equal to operator

>= greater than or equal to operator


Source Code
public class relational {
public static void main(String args[])
{
int a=100,b=50;
System.out.println("Equal to : "+(a==b));
System.out.println("Not Equal to : "+(a!=b));
System.out.println("Greater than : "+(a>b));
System.out.println("Less than : "+(a<b));
System.out.println("Greater than or equal to : "+(a>=b));
System.out.println("Less than or equal to : "+(a<=b));
}
}

Output
Equal to : false
Not Equal to : true
Greater than : true
Less than : false
Greater than or equal to : true
Less than or equal to : false

Logical Operators in Java

A logical operator (sometimes called a "Boolean operator") in Java programming is an


operator that returns a Boolean result that's based on the Boolean result of one or two other
expressions. Sometimes, expressions that use logical operators are called "compound
expressions" because the effect of the logical operators is to let you combine two or more
condition tests into a single expression.

Logical operators when we test more than one condition to make decisions. These are: &&
(meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).
Operator Example Meaning

&& (Logical AND) expression1 && expression2 true only if both expression1 and expr

|| (Logical OR) expression1 || expression2 true if either expression1 or expression2

! (Logical NOT) !expression true if expression is false and vice versa

Source Code
public class Logical {
public static void main(String args[])
{
int m1=25,m2=75;
System.out.println("And && : "+(m1>=35 && m2>=35));
System.out.println("Or || : "+(m1>=35 || m2>=35));

}
}

Output
And && : false
Or || : true

Conditional or Ternary Operators in Java

The conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. When using a Java ternary
construct, only one of the right-hand side expressions, i.e. either expression1 or expression2,
is evaluated at runtime.Condition? expression1: expression2;
• if condition is true, expression1 is executed.
• And, if condition is false, expression2 is executed.
The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the
name ternary operator.

Source Code
public class Conditional {
public static void main(String args[])
{
//Conditional or Ternary Operators in Java ?:
int a=45,b=35,c;
c=a>b?a:b;
System.out.println("The Greatest Number is : "+c);

}
}

Output
The Greatest Number is : 45

Unary Operators in Java

Unary Operators can be simply defined as an operator that takes only one operand and does
a plain simple job of either incrementing or decrementing the value by one. Added, Unary
operators also perform Negating operations for expression, and the value of the boolean can
be inverted.

1. Unary Plus, denoted by "+"

2. Unary minus, denoted by "-"

3. Unary Increment Operator, denoted by "++"


Post-Increment: Value is first processed then incremented. In post increment, whatever the
value is, it is first used for computing purpose, and after that, the value is incremented by one.

Pre-Increment: On the contrary, Pre-increment does the increment first, then the computing
operations are executed on the incremented value.

Post-Decrement: While using the decrement operator in post form, the value is first used
then updated.

Pre-Decrement: With prefix form, the value is first decremented and then used for any
computing operations.

Unary operators called increment (++) and decrement (--) operators. These operators
increment and decrement value of a variable by 1.

Source Code
public class Unary {
public static void main(String args[])
{
//Unary Operators in Java ++ --
int a=10;
System.out.println(a);
//a++; //a=a+1
System.out.println(a++);
System.out.println(a);
System.out.println(++a);

}
}

Output
10
10
11
12
Bitwise & Shift Operators in Java

A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left. The bitwise operators are the operators used to perform the operations on the
data at the bit-level. When we perform the bitwise operations, then it is also known as bit-
level programming. It consists of two digits, either 0 or 1.

Operator Description

| Bitwise OR

& Bitwise AND

^ Bitwise XOR

~ Bitwise complement

<< Left shift

>> Signed right shift

>>> Unsigned right shift

Source Code
public class Bitwise {
public static void main(String args[])
{
//Bitwise & Shift Operators in Java
int a=25,b=45;
System.out.println("Bitwise And : "+(a&b));
System.out.println("Bitwise Or : "+(a|b));
System.out.println("Bitwise Xor : "+(a^b));
System.out.println("Bitwise Not : "+(~a));

}
}

Output
Bitwise And : 9
Bitwise Or : 61
Bitwise Xor : 52
Bitwise Not : -26

Scanner Class in Java

The following is how to properly use the java.util.Scanner class to interactively read user input
from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other
languages as well as in Unix and Linux). It idiomatically demonstrates the most common
things that are requested to be done.

The Scanner class is used to read Java user input. Scanner is part of the java.util package, so it
can be imported without downloading any external libraries. Scanner reads text from
standard input and returns it to a program.

Once the Scanner class is imported into the Java program, you can use it to read the input of
various data types. Depending on whether you want to read the input from standard input
and output.

Source Code
import java.util.Scanner;

public class getting_inputs {


public static void main(String args[])
{
//a2+b2+2ab
Scanner in =new Scanner(System.in);
//int a,b,c;
float a,b,c;
System.out.println("Enter 2 Nos : ");
//a=in.nextInt();
// b=in.nextInt();
a=in.nextFloat();
b=in.nextFloat();
c=(a*a)+(b*b)+(2*a*b);
System.out.println("Result : "+c);

}
}
/*
in.nextInt();
in.nextFloat();
in.nextDouble();
in.next();
in.nextLine();
*/

Output
Enter 2 Nos :
12
34
Result : 2116
Enter 2 Nos :
2.4
3.2
Result : 31.36

IF Statement in Java
The if statement is Java's conditional branch statement. It can be used to route program
execution through two different paths. The if statement is the most basic of all the control
flow statements. It tells your program to execute a certain section of code only if a particular
test evaluates to true. The if statement is written with the if keyword, followed by a condition
in parentheses, with the code to be executed in between curly brackets.

Syntax:
if( condition )
{
// body of the statements;
}

Source Code
import java.util.Scanner;

public class if_statement {


public static void main(String args[]) {
int age;
System.out.println("Enter Your Age : ");
Scanner in = new Scanner(System.in);
age=in.nextInt();
if(age>=18)
{
System.out.println("You are Eligible For Vote...");
}
}
}

Output
Enter Your Age :
23
You are Eligible For Vote...

IF ELSE Statement in Java


The Java if-else statement also tests the condition.The condition is any expression that
returns a boolean value. An if statement executes code conditionally depending on the result
of the condition in parentheses. When condition in parentheses is true it will enter to the
block of if statement which is defined by curly braces like open braces and close braces.

Opening bracket till the closing bracket is the scope of the if statement. The else block is
optional and can be omitted.It runs if the if statement is false and does not run if the if
statement is true because in that case if statement executes.

Syntax:
if( condition )
{
// body of the statement if condition is true ;
}
else
{
// body of the statement if condition is false ;
}

Source Code
import java.util.Scanner;

public class if_else_statement {


public static void main(String args[]) {
int year;
System.out.println("Enter Year : ");
Scanner in = new Scanner(System.in);
year = in.nextInt();
if (year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)) {
System.out.println("Year " + year + " is a leap year");
} else {
System.out.println("Year " + year + " is not a leap year");
}

}
}

Output
Enter Year :
1900
Year 1900 is a leap year
Enter Year :
2022
Year 2022 is not a leap year

ELSE IF Ladder in Java

Use if to specify a block of code to be executed, if a specified condition is true. Use else to
specify a block of code to be executed, if the same condition is false. Use else if to specify a
new condition to test, if the first condition is false.

The else if condition is checked only if all the conditions before it (in previous else if
constructs, and the parent if constructs) have been tested to false.

Example: The else if condition will only be checked if i is greater than or equal to 2.

• If its result is true, its block is run, and any else if and else constructs after it will be

skipped.

• If none of the if and else if conditions have been tested to true, the else block at the

end will be run.

Syntax :
if ( condition 1 )
{
// block of statement to be executed if condition is true ;
}
else if ( condition 2 )
{
// block of statement to be executed if the condition1 is false condition2 is true ;
}
else
{
block of statement to be executed if the condition1 is false condition2 is False ;
}

Source Code
import java.util.Scanner;

/*
Else If Ladder
90-100 Grade-A
80-89 Grade-B
70-79 Grade-C
<70 Grade-D
*/
public class else_if {
public static void main(String args[]) {
float avg;
System.out.println("Enter The Average Mark : ");
Scanner in = new Scanner(System.in);
avg = in.nextFloat();
if (avg >= 90 && avg <= 100) {
System.out.println("Grade A");
} else if (avg >= 80 && avg <= 89) {
System.out.println("Grade B");
} else if (avg >= 70 && avg <= 79) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
}
}
Output
Enter The Average Mark :
84
Grade B

Nested If in Java

A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. when you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else
and that is not already associated with an else.

Syntax:
if(Expression 1)
{
// Executes when the Expression 1 is true
if(Expression 2)
{
// Executes when the Expression 2 is true
}
}

Source Code
import java.util.Scanner;

public class nested_if {


public static void main(String args[])
{
/*
Nested if Statement
A company insures its drivers in the following cases:
a. If the driver is married.
b. If the driver is unmarried, male & above 30 years of age.
c. If the driver is unmarried, female & above 25 years of ag
e.
*/
Scanner in =new Scanner(System.in);
System.out.println("Enter The Marital Status M/U: ");
char marital=in.next().charAt(0);
if(marital=='u' || marital=='U' )
{
System.out.println("Enter The Gender M/F: ");
char gender=in.next().charAt(0);
System.out.println("Enter The Age : ");
int age=in.nextInt();
if((gender=='M'||gender=='m')&& age>=30)
{
System.out.println("You are Eligible for Insurance");
}
else if((gender=='F'||gender=='f')&& age>=25)
{
System.out.println("You are Eligible for Insurance");
}
else
{
System.out.println("You are Not Eligible for Insurance");
}

}
else if(marital=='m' || marital=='M' )
{
System.out.println("You are Eligible for Insurance");
}
else {
System.out.println("Invalid Input");
}
}
}
Output
Enter The Marital Status M/U:
u
Enter The Gender M/F:
f
Enter The Age :
23
You are Not Eligible for Insurance

Switch Statement in Java

The switch statement is Java's multi-way branch statement. It is used to take the place of
long if-else chains, and make them more readable. However, unlike if statements, one may
not use inequalities; each value must be concretely defined.

There are three critical components to the switch statement:

• Case: This is the value that is evaluated for equivalence with the argument to the

switch statement.

• Default:This is an optional, catch-all expression, should none of the case statements

evaluate to true.

• Abrupt completion of the case statement; usually break: This is required to prevent

the undesired evaluation of further case statements

Syntax:
switch ( expression )
{
case 1 :
// Block of Statement
break;
case 2 :
// Block of Statement
break;
case 3 :
// Block of Statement
break;
case 4 :
// Block of Statement
break;
.
.
default :
// Block of Statement
break;
}

Source Code
import java.util.Scanner;

//Switch Case Statement in Java


public class switch_demo {
public static void main(String args[]) {
int a,b,c,ch;
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
System.out.println("Enter Your Choice : ");
Scanner in =new Scanner(System.in);
ch=in.nextInt();
System.out.println("Enter 2 Nos : ");
a=in.nextInt();
b=in.nextInt();
switch (ch)
{
case 1:
c=a+b;
System.out.println("Addition : " +c);
break;
case 2:
c=a-b;
System.out.println("Subtraction : "+c);
break;
case 3:
c=a*b;
System.out.println("Multiplication : "+c);
break;
case 4:
c=a/b;
System.out.println("Division : "+c);
break;
default:
System.out.println("Invalid Selection");
break;
}
}
}

Output
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter Your Choice :
3
Enter 2 Nos :
12
8
Multiplication : 96

Group Switch Statement in Java


The switch statement is Java's multi-way branch statement. It is used to take the place of
long if-else chains, and make them more readable. However, unlike if statements, one may
not use inequalities; each value must be concretely defined. The break statement is optional.
If you omit the break, execution will continue on into the next case. It is sometimes desirable
to have multiple cases without break statements between them. For example, consider the
following program:

Syntax:
switch(expression)
{
case 1 :
case 2 :
case 3 :
case 4 :
// code inside the combined case
break;
case 5 :
case 6 :
// code inside the combined case value
break;
.
.
default :
// code inside the default case .
}

Source Code
import java.util.Scanner;

//Group Switch
public class group_switch {
public static void main(String args[]) {
char c;
System.out.println("Enter The Character : ");
Scanner in =new Scanner(System.in);
c=in.next().charAt(0);
switch (c)
{
case 'a':
case 'e':
case 'i':
case '0':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
System.out.println(c + " is a Vowels");
break;
default:
System.out.println(c + " is Consonant");
break;
}

}
}

Output
Enter The Character :
u
u is a Vowels

While Loop in Java

The while loop is Java's most fundamental loop statement. It repeats a statement or block
while its controlling expression is true.The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional expression is true. When
condition becomes false, control passes to the next line of code immediately following the
loop.

• If the condition to true, the code inside the while loop is executed.

• The condition is evaluated again.

• This process continues until the condition is false.

• When the condition to false, the loop stops.

Syntax:
while(Condition)
{
// body of loop;
// Increment (or) Decrement;
}

Source Code
import java.util.Scanner;

public class while_loop {


public static void main(String args[])
{
System.out.println("Enter The Limit : ");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
int i=1;
while(i<=n)
{
System.out.println(i);
i++;
}
}
}
Output
Enter The Limit :
10

1
2
3
4
5
6
7
8
9
10

Do While Loop in Java

The do-while loop always executes its body at least once, because its conditional expression
is at the bottom of the loop.The do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise,
the loop terminates.

• The first body of the loop is executed.

• The condition check to true, the body of the loop inside the do statement is executed

again.

• The condition is check again.

• This process continues until the condition is false.

• When the condition to false, the loop stops.

Syntax:
do
{
// body of loop;
// Increment (or) Decrement;
} while(Condition) ;

Source Code
import java.util.Scanner;

public class do_while {


public static void main(String args[])
{
System.out.println("Enter The Limit : ");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
int i=2;
do {
System.out.println(i);
i=i+2;
}while (i<=n);
}
}

Output
Enter The Limit :
20

2
4
6
8
10
12
14
16
18
20
For Loop in Java

The for loop in Java is an entry-controlled loop. A for loop is a repetition control structure
which allows us to write a loop that is executed a specific number of times. The three
components of the for loop (separated by ;) are variable declaration/initialization (here int i =
0), the condition (here i < 100), and the increment statement (here i++).

The variable declaration is done once as if placed just inside the { on the first run. Then the
condition is checked, if it is true the body of the loop will execute, if it is false the loop will
stop. Assuming the loop continues, the body will execute and finally when the } is reached the
increment statement will execute just before the condition is checked again.

The curly braces are optional (you can one line with a semicolon) if the loop contains just one
statement. But, it's always recommended to use braces to avoid misunderstandings and
bugs. The for loop components are optional. If your business logic contains one of these
parts, you can omit the corresponding component from your for loop.

Syntax:
for( initial ; condition ; increment / decrement)
{
// body of loop;
}

Source Code
import java.util.Scanner;

public class for_loop {


public static void main(String args[])
{
System.out.println("Enter The Limit : ");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println(i);
}
}
}

Output
Enter The Limit :
10

1
2
3
4
5
6
7
8
9
10

Enhanced for loop in Java

The enhanced style for can only cycle through an array sequentially, from start to finish.It is
also known as the enhanced for loop. The enhanced for loop was introduced in Java 5 as a
simpler way to iterate through all the elements of a Collection (Collections are not covered in
these pages). It can also be used for arrays, as in the above example, but this is not the
original purpose.

Enhanced for loops are simple but inflexible. They can be used when you wish to step through
the elements of the array in first-to-last order, and you do not need to know the index of the
current element.

Syntax:
for( Datatype item : array )
{
// body of loop;
}

Datatype : The Datatype of the array/collection


Item : Each item of array/collection is assigned to this variable
Array : An array or a collection

Source Code
public class Enhanced_for {
public static void main(String args[])
{
int numbers[]={10,20,30,40,50,60,70};
for(int n : numbers)
{
System.out.println(n);
}
}
}

Output
10
20
30
40
50
60
70

Nested For Loop in Java

The for loop in Java is an entry-controlled loop. A for loop is a repetition control structure
which allows us to write a loop that is executed a specific number of times. The three
components of the for loop (separated by ;) are variable declaration/initialization (here int i =
0), the condition (here i < 100), and the increment statement (here i++).

The variable declaration is done once as if placed just inside the { on the first run. Then the
condition is checked, if it is true the body of the loop will execute, if it is false the loop will
stop. Assuming the loop continues, the body will execute and finally when the } is reached the
increment statement will execute just before the condition is checked again.

Any looping statement having another loop statement inside called nested loop. The same
way for looping having more inner loop is called 'nested for loop'..

Syntax:
for( initial ; Condition ; increment / decrement ) // Outer Loop Statements
{
for( initial ; Condition ; increment / decrement ) // Inner Loop Statements
{
....
}
}

Source Code
public class nested_for {
public static void main(String args[]) {

for(int i=1;i<=5;i++)//1<=5 2<=5


{
for(int j=1;j<=5;j++)
{
System.out.print("*");
}
System.out.println("");
}
}
}

Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Break & Continue in Java

By using break,you can force immediate termination of a loop, bypassing the conditional
expression and any remaininh code in the body of the loop.When a break statement is
encountered inside a loop, the loop is immediately terminated and the program control
resumes at the next statement following the loop.

The continue statement performs such an action. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional expression that
controls the loop.

Source Code
public class break_continue {
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
if(i==5)
continue;
System.out.println(i);
if(i==8)
break;
}
}
}

Output
1
2
3
4
6
7
8

Factorial in Java

To find the factorial of a number. Factorial is the process multiplying all the natural numbers
below the given number.

The using for the for loop. A for loop is a repetition control structure which allows us to write
a loop that is executed a specific number of times. The three components of the for loop
(separated by ;) are variable declaration/initialization (i = 0), the condition ( i < 100), and the
increment statement ( i++).

Source Code
import java.util.Scanner;

public class Factorial {


public static void main(String args[])
{
//1.Write a program to find the factorial of given number.
Scanner in =new Scanner(System.in);
System.out.println("Enter The Number : ");
int n=in.nextInt();//5
int f=1;
for(int i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("Factorial of "+n+" is "+f);
}
}
Output
Enter The Number :
5
Factorial of 5 is 120

Sum and Average of N Numbers in Java

The average is the outcome from the sum of the numbers divided by the count of the
numbers being averaged by using for the for loop. A for loop is a repetition control structure
which allows us to write a loop that is executed a specific number of times. The loop enables
us to perform n number of steps together in one line. In for loop, a loop variable is used to
control the loop.
Example:
10,20,30,40,50.
Sum of given numbers = 150.
Average of given numbers = 30.

Source Code
import java.util.Scanner;
//Write a program to find the sum and average of given n numbers.
public class sum_avg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter The Limit: ");
int n=in.nextInt();
int sum=0,a;
for(int i=1;i<=n;i++)
{
System.out.println("Enter The Number "+i+": ");
a=in.nextInt();
sum+=a;//sum=sum+a;
}
System.out.println("The sum of given numbers is : "+sum);
System.out.println("The Average of given numbers is : "+sum/n);
}
}

Output
The sum of given numbers is : 150
The Average of given numbers is : 30

Fibonacci Series in Java

The Fibonacci series is a series of elements where, the previous two elements are added to
get the next element by using for the for loop. A for loop is a repetition control structure
which allows us to write a loop that is executed a specific number of times. The loop enables
us to perform n number of steps together in one line. In for loop, a loop variable is used to
control the loop.

Source Code
import java.util.Scanner;
//Write a program to find the fibonacci series of given number.
public class Fibonacci {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter The Number : ");
int n=in.nextInt();//5
int a=-1,b=1,c;
for(int i=1;i<=n;i++)//1<=5 2<=5 3<=5 4<=5 5<=5 6<=5
{
c=a+b;//-1+1=>0 1+0=>1 0+1=1 1+1=2 1+2=3
System.out.println(c); //0 1 1 2 3
a=b;//1 0 1 1 2
b=c;//0 1 1 2 3
}
}
}
Output
Enter The Number :
8
0
1
1
2
3
5
8
13

Reverse of n digit number in Java

A number can be written in reverse order using for the while loop. While loop is also known as
a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple
times depending upon a given boolean condition. It can be viewed as a repeating if statement.
The while loop is mostly used in the case where the number of iterations is not known in
advance.

First,the remainder of the num divided by 10 is stored in the variable digit .The digit contains
the last digit of num , example 5. digit is then added to the variable reversed after multiplying
it by 10. Multiplication by 10 adds a new place in the reversed number.

Source Code
import java.util.Scanner;
public class reverse_number {
//Write a program to find the reverse of N digit Number
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter The Number : ");
int n = in.nextInt();
int reverse=0, rem;
while(n!=0)
{
rem=n%10;
reverse=(reverse*10)+rem;
n=n/10;
}
System.out.println("Reversed Number: "+reverse);
}
}

Output
Enter The Number : 52967
Reversed Number: 76925

Number is Palindrome or Not in Java

Java program to check for a Palindrome number.Get an input number or string. Get the
reverse of the input number or string Compare the two numbers and string same or Not
same.

The if statement is Java's conditional branch statement. It can be used to route program
execution through two different paths. The if statement is the most basic of all the control
flow statements. It tells your program to execute a certain section of code only if a particular
test evaluates to true. The if statement is written with the if keyword, followed by a condition
in parentheses, with the code to be executed in between curly brackets.

The below program checks for a Palindrome number using a loop. A for loop is a repetition
control structure which allows us to write a loop that is executed a specific number of times.
The loop enables us to perform n number of steps together in one line. In for loop, a loop
variable is used to control the loop.

Source Code
import java.util.Scanner;
public class number_palindrome {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter The Number : ");
int n = in.nextInt();
int temp=n;
int reverse=0, rem;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
if(temp==reverse)
{
System.out.println(reverse+" Number is Palindrome");
}else {
System.out.println(reverse+" Number is Not a Palindrome");
}

}
}

Output
Enter The Number : 64546
64546 Number is Palindrome
Enter The Number : 4654
4564 Number is Not a Palindrome

Armstrong Number in Java


An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.
Armstrong Number is a positive number if it is equal to the sum of cubes of its digits is called
Armstrong number and if its sum is not equal to the number then its not a Armstrong number
using if else statements. The if statement is the most basic of all the control flow statements.
It tells your program to execute a certain section of code only if a particular test evaluates to
true. The if statement is written with the if keyword, followed by a condition in parentheses,
with the code to be executed in between curly brackets. Armstrong Number Program is very
popular in java.

Examples:
153 => (1*1*1)+(5*5*5)+(3*3*3) = 153 is Armstrong Number
453 => (4*4*4)+(5*5*5)+(3*3*3) = 216 is Not Armstrong Number

Source Code
import java.util.Scanner;

public class ArmstrongNumber {


//Write a program to check whether the given 3 digit number is armstrong or no
t
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 Digit Number : ");
int number = in.nextInt();//123
int temp = number;//123
int digit1, digit2, digit3;

digit3=temp%10;//3
temp=temp/10;//12

digit2=temp%10;//2
temp=temp/10;//1

digit1=temp%10;//1
int result=(digit1 * digit1 * digit1)+( digit2 * digit2 * digit2)+(digit3
* digit3 * digit3);
if(number==result){
System.out.println(number + " is armstrong Number");
}else{
System.out.println(number + " is not an armstrong Number");
}

}
}

Output
Enter 3 Digit Number : 371
371 is armstrong Number
Enter 3 Digit Number : 634
634 is not an armstrong Number

Armstrong Number between 100-999 in Java

An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.
Armstrong Number is a positive number if it is equal to the sum of cubes of its digits is called
Armstrong number and if its sum is equal to the number then its a Armstrong number using
for if statement. The if statement is the most basic of all the control flow statements. It tells
your program to execute a certain section of code only if a particular test evaluates to true.
The if statement is written with the if keyword, followed by a condition in parentheses, with
the code to be executed in between curly brackets. Armstrong Number Program is very
popular in java.

Source Code
public class Armstrong_Numbers {
//Write a program to find the armstrong number from 100-999
public static void main(String[] args)
{
int digit1,digit2,digit3,result,temp;
for(int number = 100; number <= 999; number++)
{
temp = number;
digit3=temp%10;//3
temp=temp/10;//12

digit2=temp%10;//2
temp=temp/10;//1

digit1=temp%10;//1
result=(digit1 * digit1 * digit1)+( digit2 * digit2 * digit2)+(digit3
* digit3 * digit3);

if(number==result){
System.out.println(number + " is armstrong Number");
}
}
}
}

Output
153 is armstrong Number
370 is armstrong Number
371 is armstrong Number
407 is armstrong Number

Multiplication tables in Java

Printing the multiplication table upto the given Number using for the for loop. A for loop is a
repetition control structure which allows us to write a loop that is executed a specific number
of times. The loop enables us to perform n number of steps together in one line. The three
components of the for loop (separated by ;) are variable declaration/initialization (i = 0), the
condition ( i < n), and the increment statement ( i++).
Source Code
import java.util.Scanner;
//Write a program to print the multiplication tables
public class multiplication {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter The Table : ");
int t = in.nextInt();
System.out.print("Enter The Limit : ");
int n = in.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println(t + " x " + i + " = " + (t * i));
}
}
}

Output
Enter The Limit : 10
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Factor of the given number in Java


The numbers that are completely divisible by the given number (it means the remainder
should be 0) called as factors of a given number using for the for loop and if condition
statement. A for loop is a repetition control structure which allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n number of steps
together in one line. In for loop, a loop variable is used to control the loop. The if statement is
the most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true. The if statement is written with the
if keyword, followed by a condition in parentheses, with the code to be executed in between
curly brackets.
Example :
limit = 5
5 1 => 5%1 = 0
5 2 => 5%2 = 0
5 3 => 5%3 = 1
5 4 => 5%4 = 2
5 5 => 5%5 = 0

Source Code
import java.util.Scanner;

public class factor {


//Write a program to find the factor of the given number.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter The Number : ");
int n = in.nextInt();
for(int i=1;i<=n;i++)
{
if(n%i==0){
System.out.println(i);
}
}
}
}
Output
Enter The Number : 10
1
2
5
10

Number is prime or not in Java

A prime number is a whole number greater than 1. It has exactly two factors, that is, 1 and
the number itself. Using for the for loop and if condition statement. A for loop is a repetition
control structure which allows us to write a loop that is executed a specific number of times.
The loop enables us to perform n number of steps together in one line. The if statement is the
most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true. The if statement is written with the
if keyword.

Source Code
import java.util.Scanner;

public class prime {


//Write a program to check the given number is prime or not.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter The Number : ");
int n = in.nextInt();
int f = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
f++;
}
}
if (f == 2) {
System.out.println(n + " is a Prime Number");
} else {
System.out.println(n + " is not a Prime Number");
}

}
}

Output
Enter The Number : 17
17 is a Prime Number
Enter The Number : 10
10 is not a Prime Number

Prime Number between 100-999 in Java

A prime number is a whole number greater than 1. It has exactly two factors, that is, 1 and
the number itself. Using for the for loop and if condition statement. A for loop is a repetition
control structure which allows us to write a loop that is executed a specific number of times.
The loop enables us to perform n number of steps together in one line. The if statement is the
most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true. The if statement is written with the
if keyword.

Source Code
import java.util.Scanner;
public class prime_numbers {
//Write a program to print the prime numbers between 1 to 999
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int f = 0;
for(int n=1;n<=999;n++) {
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
f++;
}
}
if (f == 2) {
System.out.println(n + " is a Prime Number");
}
f=0;
}

}
}

Output
2 is a Prime Number
3 is a Prime Number
5 is a Prime Number
7 is a Prime Number
11 is a Prime Number
13 is a Prime Number
17 is a Prime Number
19 is a Prime Number
23 is a Prime Number
29 is a Prime Number
31 is a Prime Number
37 is a Prime Number
41 is a Prime Number
43 is a Prime Number
47 is a Prime Number
53 is a Prime Number
59 is a Prime Number
61 is a Prime Number
67 is a Prime Number
71 is a Prime Number
73 is a Prime Number
79 is a Prime Number
83 is a Prime Number
89 is a Prime Number
97 is a Prime Number
101 is a Prime Number
103 is a Prime Number
107 is a Prime Number
109 is a Prime Number
113 is a Prime Number
127 is a Prime Number
131 is a Prime Number
137 is a Prime Number
139 is a Prime Number
149 is a Prime Number
151 is a Prime Number
157 is a Prime Number
163 is a Prime Number
167 is a Prime Number
173 is a Prime Number
179 is a Prime Number
181 is a Prime Number
191 is a Prime Number
193 is a Prime Number
197 is a Prime Number
199 is a Prime Number
211 is a Prime Number
223 is a Prime Number
227 is a Prime Number
229 is a Prime Number
233 is a Prime Number
239 is a Prime Number
241 is a Prime Number
251 is a Prime Number
257 is a Prime Number
263 is a Prime Number
269 is a Prime Number
271 is a Prime Number
277 is a Prime Number
281 is a Prime Number
283 is a Prime Number
293 is a Prime Number
307 is a Prime Number
311 is a Prime Number
313 is a Prime Number
317 is a Prime Number
331 is a Prime Number
337 is a Prime Number
347 is a Prime Number
349 is a Prime Number
353 is a Prime Number
359 is a Prime Number
367 is a Prime Number
373 is a Prime Number
379 is a Prime Number
383 is a Prime Number
389 is a Prime Number
397 is a Prime Number
401 is a Prime Number
409 is a Prime Number
419 is a Prime Number
421 is a Prime Number
431 is a Prime Number
433 is a Prime Number
439 is a Prime Number
443 is a Prime Number
449 is a Prime Number
457 is a Prime Number
461 is a Prime Number
463 is a Prime Number
467 is a Prime Number
479 is a Prime Number
487 is a Prime Number
491 is a Prime Number
499 is a Prime Number
503 is a Prime Number
509 is a Prime Number
521 is a Prime Number
523 is a Prime Number
541 is a Prime Number
547 is a Prime Number
557 is a Prime Number
563 is a Prime Number
569 is a Prime Number
571 is a Prime Number
577 is a Prime Number
587 is a Prime Number
593 is a Prime Number
599 is a Prime Number
601 is a Prime Number
607 is a Prime Number
613 is a Prime Number
617 is a Prime Number
619 is a Prime Number
631 is a Prime Number
641 is a Prime Number
643 is a Prime Number
647 is a Prime Number
653 is a Prime Number
659 is a Prime Number
661 is a Prime Number
673 is a Prime Number
677 is a Prime Number
683 is a Prime Number
691 is a Prime Number
701 is a Prime Number
709 is a Prime Number
719 is a Prime Number
727 is a Prime Number
733 is a Prime Number
739 is a Prime Number
743 is a Prime Number
751 is a Prime Number
757 is a Prime Number
761 is a Prime Number
769 is a Prime Number
773 is a Prime Number
787 is a Prime Number
797 is a Prime Number
809 is a Prime Number
811 is a Prime Number
821 is a Prime Number
823 is a Prime Number
827 is a Prime Number
829 is a Prime Number
839 is a Prime Number
853 is a Prime Number
857 is a Prime Number
859 is a Prime Number
863 is a Prime Number
877 is a Prime Number
881 is a Prime Number
883 is a Prime Number
887 is a Prime Number
907 is a Prime Number
911 is a Prime Number
919 is a Prime Number
929 is a Prime Number
937 is a Prime Number
941 is a Prime Number
947 is a Prime Number
953 is a Prime Number
967 is a Prime Number
971 is a Prime Number
977 is a Prime Number
983 is a Prime Number
991 is a Prime Number
997 is a Prime Number

Perfect Number in Java

A perfect number is a positive integer that is equal to the sum of its positive divisors,
excluding the number itself. Using for the for loop and if condition statement. A for loop is a
repetition control structure which allows us to write a loop that is executed a specific number
of times. The loop enables us to perform n number of steps together in one line. The if
statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test evaluates to true.
Example :
6 is a perfect number because 6 is divisible by 1, 2 and 3 and the sum of these values is 1 + 2
+ 3 = 6. Remember, we have to exclude the number itself.

Source Code
import java.util.Scanner;
public class perfect {
//Write a program to check the given number is perfect number or not.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter The Number : ");
int n = in.nextInt();//6
int sum=0;
for (int i = 1; i <n; i++) {
if(n%i==0){
sum+=i;//1+2+3
}
}
if(sum==n){
System.out.println(n + " is a Perfect Number");
}else {
System.out.println(n + " is not a Perfect Number");
}
}
}

Output
Enter The Number : 6
6 is a Perfect Number
Enter The Number : 13
13 is not a Perfect Number

Strong Number in Java

A strong number is a number whose sum of the factorial of its digits is equal to that number
using while and for loop. a while loop allows a part of the code to be executed multiple times
depending upon a given boolean condition. It can be viewed as a repeating if statement. The
while loop is mostly used in the case where the number of iterations is not known in advance.
A for loop is a repetition control structure which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.
Example : 1
234
= 2! + 3! + 4!
= 2 + 6 + 24
= 32
So , 234 is not a strong number.
Example : 2
145
= 1! + 4! + 5!
= 1 + 24 + 120
= 145
So , 145 is not a strong number.

Source Code
import java.util.Scanner;
public class strong {
//Write a program to check the given number is Strong number or not.
public static void main(String args[])
{
int num,originalNum,rem,fact,i,sum=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number : ");
num=in.nextInt();
originalNum=num;
while (num>0)//145>0 14>0 1>0
{
rem=num%10;
//System.out.println("Reminder : "+rem);
fact=1;
for(i=1;i<=rem;i++){
fact*=i;//fact=fact*i
}
//System.out.println("fact : "+fact);
sum+=fact;
num=num/10;
}
if (sum == originalNum) {
System.out.println(originalNum + " is STRONG NUMBER");
} else {
System.out.println(originalNum + " is not a STRONG NUMBER");
}
}
}

Output
Enter a number :
145
145 is STRONG NUMBER
Enter a number :
234
234 is not a STRONG NUMBER

Array in Java

An array is a collection of elements of the same type placed in contiguous memory locations
that can be individually referenced by using an index to a unique identifier.

Array Type : Type of the array. This can be primitive (int, long, byte) or Objects (String,
MyObject, etc).

Index : Index refers to the position of a certain Object in an array.

Length : Every array, when being created, needs a set length specified. This is either done
when creating an empty array (new int[3]) or implied when specifying values ({1, 2, 3}).

Syntax:
Datatype variable_name [ ] ;
(or)
Datatype [ ] variable_name ;

Example :
Int [ ] array = new int [ 5 ] ;

Source Code
import java.util.Scanner;
public class One_Array {
//Arrays in Java
public static void main(String args[])
{
int a[]={10,20,30,40,50,60,70,80,90,100};
//Accessing Elements in array
System.out.println(a[2]);

//Print all Elements using for loop


for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
//Print all Elements using Enhanced for loop
for(int element : a)
{
System.out.println(element);
}

int b[]; // Declaring array


b=new int[10]; // Allocating Memory to Array
int [] c =new int[10]; //Combining Both Statement

//Buy default all element have zero value


for(int element : b)
{
System.out.println(element);
}

for(int i=0;i<3;i++)
{
Scanner in =new Scanner(System.in);
System.out.println("Enter The Number");
c[i]=in.nextInt();
}
for(int element : c)
{
System.out.println(element);
}

}
}

Output
//Accessing Elements in array
30
//Print all Elements using for loop
10
20
30
40
50
60
70
80
90
100

//Print all Elements using Enhanced for loop


10
20
30
40
50
60
70
80
90
100

//Buy default all element have zero value


0
0
0
0
0
0
0
0
0
0
//User input array values
Enter The Number
1
Enter The Number
2
Enter The Number
3
1
2
3
0
0
0
0
0
0
0

Count odd or even numbers in Java

Check the Number even or odd using array ,looping and if condition. To count the even and
odd numbers in an array first user is allowed to enter size and elements of one dimensional
array using nextInt() method of Scanner class. A number which is divisible by 2 and generates
a remainder of 0 is called an even number.A number which is divisible by 2 and generates a
remainder of 1 is called an odd number.

Source Code
import java.util.Scanner;

public class even_odd {


//Write a program to count even and odd numbers in an array
public static void main(String[] args) {
int e = 0, o = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter The Limit : ");
int n = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter a[" + i + "] value : ");
a[i] = in.nextInt();
}
for (int element : a) {
if (element % 2 == 0) {
e++;
} else {
o++;
}
}
System.out.println("Total Even Nos : " + e);
System.out.println("Total Odd Nos : " + o);
}
}

Output
Enter The Limit :
5
Enter a[0] value :
10
Enter a[1] value :
34
Enter a[2] value :
53
Enter a[3] value :
41
Enter a[4] value :
45
Total Even Nos : 2
Total Odd Nos : 3

Ascending Order in Java


Ascending order is an arranged in a series that begins with the least or smallest and ends
with the greatest or largest. To define an array named a with n number of integer values.
Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in
Java in ascending order using the Arrays.
Example:
{2, 3, 7, 8, 9, 33, 87} are numbers arranged in ascending order. While arranging numbers in
ascending order, we write the smallest value first and then we move forward towards the
larger values.

Source Code
import java.util.Arrays;

public class ascendingOrder {


public static void main(String args[])
{
// Ascending order
int[] a = new int[]{8, 2, 9, 7, 33, 3, 87};
System.out.println("Before Sort : "+Arrays.toString(a));
int temp;
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("After Sort : "+Arrays.toString(a));
}
}
Output
Before Sort : [8, 2, 9, 7, 33, 3, 87]
After Sort : [2, 3, 7, 8, 9, 33, 87]

Insert an element (specific position) into an array in Java

Java Program to Insert an Element in a Specified Position in a Given Array. An array is a


collection of similar data elements stored at contiguous memory locations. Enter size of array
and then enter all the elements of that array. Now enter the element you want to insert and
position where you want to insert that element. We shift all the elements in the array from
that location by one and hence insert the element easily.

Source Code
import java.util.Arrays;
public class Insert_element_array {
public static void main(String args[])
{
//Program to insert a element in specific index of an array
int[] a = {10,20,30,40,50,60,70,80,90,100};
int index = 2;
int value = 55;
System.out.println("Before Insert "+Arrays.toString(a) );

for(int i=a.length-1;i>index;i--)
{
a[i]=a[i-1];
}
a[index]=value;
System.out.println("After Insert "+Arrays.toString(a) );
}
}
Output
Before Insert [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
After Insert [10, 20, 55, 30, 40, 50, 60, 70, 80, 90]

Find the duplicate values of an array in Java

One of the most common ways to find duplicates is by using the brute force method, which
compares each element of the array to every other element.Declare and initialize an
array.Duplicate elements can be found using Nested loops. Any looping statement having
another loop statement inside called nested loop. The same way for looping having more
inner loop is called nested for loop.

The outer loop will iterate through the array from 0 to length of the array. The outer loop will
select an element.If a match is found which means the duplicate element is found then,
display the element.

Source Code
public class duplicate_array {
public static void main(String args[]) {
//Write a program to print the duplicate element in an array
int[] a = {1, 2, 5, 5, 6, 6, 7, 2};

for (int i = 0; i < a.length - 1; i++) {


for (int j = i + 1; j < a.length; j++)
{
if ((a[i] == a[j]) && (i != j)) {
System.out.println("Duplicate Element : " + a[j]);
}
}
}

}
}
Output
Duplicate Element : 2
Duplicate Element : 5
Duplicate Element : 6

Two Dimension Arrays in Java

The Java Program is 2D array is organized as matrices which can be represented as the
collection of rows and column. It is possible to define an array with more than one dimension.
Instead of being accessed by providing a single index, a multidimensional array is accessed by
specifying an index for each dimension.

The declaration of multidimensional array can be done by adding [] for each dimension to a
regular array declaration. For instance, to make a 2-dimensional int array, add another set of
brackets to the declaration, such as int[][]. This continues for 3-dimensional arrays (int[][][])
and so forth.

Syntax:
Datatype variable_name [ ] [ ] ;
(or)
Datatype [ ][ ] variable_name ;

Source Code
public class Two_Array {
public static void main(String args[]) {
//Two Dimension array in Java
int a[][] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(" "+a[i][j]);
}
System.out.println("");
}
//Array Declaration
int [][]b=new int[10][10];
int [][][]c=new int[10][10][10];
b[0][0]=10;

}
}

Output
10 20 30
40 50 60
70 80 90

Jagged-Array in Java

A jagged array is an array of arrays such that member arrays can be of different row sizes and
column sizes. Jagged subarrays may also be null. For instance, the following code declares
and populates a two dimensional int array whose first subarray is of four length, second
subarray is of three length, and the last subarray is a fours length array:

Example :
int [ ] [ ] a = { { 10,20,30,40 } , { 10,20,30 } , { 10,20,30,50 } } ;

Source Code
public class jagged_Array {
public static void main(String args[]) {
//Jagged Array using For Loop in Java Programming
int a[][] = {
{10, 20, 30, 40},//4
{10, 20, 30},//3
{10, 20, 30, 50}//4
};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" "+a[i][j]);
}
System.out.println("");
}
}
}

Output
10 20 30 40
10 20 30
10 20 30 50

Jagged-Array Using For Each Loop in Java

A jagged array is an array of arrays such that member arrays can be of different row sizes and
column sizes. Jagged subarrays may also be null. For instance, the following code declares
and populates a two dimensional int array whose first subarray is of four length, second
subarray is of three length, and the last subarray is a fours length array:
Example :
int [ ] [ ] a = { { 10,20,30,40 } , { 10,20,30 } , { 10,20,30,50 } } ;

Source Code

public class jagged_Array_for {


public static void main(String args[])
{

//Jagged Array using En hanced For Loop in Java Programming


int a[][]={
{10,20,30,40},
{10,20,30},
{10,20,30,50}
};
for(int k[]:a) {
for(int l:k)
{
System.out.print(" "+l);
}
System.out.println("");
}

}
}

Output
10 20 30 40
10 20 30
10 20 30 50

ASCII in Java

Computer manufacturers agreed to use one code called the ASCII (American Standard Code
for Information Interchange).There are 128 standard ASCII characters, numbered from 0 to
127. Extended ASCII adds another 128 values and goes to 255. The ASCII values to print using
to the for loop. A for loop is a repetition control structure which allows us to write a loop that
is executed a specific number of times. The three components of the for loop (separated by ;)
are variable declaration/initialization , the condition , and the increment statement.

Source Code
public class ascii {
public static void main(String args[])
{
/*
ASCII - American Standard Code For Information Interchange
Computers can only understand numbers,
so an ASCII code is the numerical representation of a character such a
s 'a' or '@' etc.

The first 32 characters in the ASCII-table


are unprintable control codes and are used to control peripherals such
as printers.

Codes 32-127 are common for all the different variations of the ASCII
table, they are
called printable characters, represent letters, digits, punctuation ma
rks,
and a few miscellaneous symbols.

65-90 A-Z
97-122 a-z
48-57 0-9
Space 32
*/
for(int i=65;i<=90;i++)
{
System.out.println(i+" "+(char)i);
}

}
}

Output
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z

String in Java

A string is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created. String is slow and consumes more memory
when we concatenate too many strings because every time it creates new instance. String
class overrides the equals() method of Object class. So you can compare the contents of two
strings by equals() method.

Source Code
public class stringsConcept {
public static void main(String args[])
{
//String in Java
String a="Tutor Joes";
String b="tutor Joes";
System.out.println("A : "+a);
System.out.println("B : "+b);
System.out.println("A HashCode "+a.hashCode());
System.out.println("B HashCode "+b.hashCode());
System.out.println("Equals : "+a.equals(b));
System.out.println("Equals Ignore Case: "+a.equalsIgnoreCase(b));
System.out.println("Length: "+a.length());
System.out.println("CharAt: "+a.charAt(0));
System.out.println("Uppercase: "+a.toUpperCase());
System.out.println("Lowercase: "+a.toLowerCase());
System.out.println("Replace: "+a.replace("Joes","Stanley"));
System.out.println("Contains : " + a.contains("Joes"));
System.out.println("Empty : " + a.isEmpty());
System.out.println("EndWith : " + a.endsWith("es"));
System.out.println("StartWith : " + a.startsWith("Tut"));
System.out.println("Substring : " + a.substring(5));
System.out.println("Substring : " + a.substring(0, 5));
char[] carray = a.toCharArray();
for(char c : carray){
System.out.print(c+ " ");
}
String c=" Tutor ";
System.out.println("Length: "+c.length());
System.out.println("C:"+c);
System.out.println("C Trim :"+c.trim());
System.out.println("C Trim Length:"+c.trim().length());

}
}

Output
A : Tutor Joes
B : tutor Joes
A HashCode : -1314220131
B HashCode : 987282301
Equals : false
Equals Ignore Case: true
Length : 10
CharAt : T
Uppercase : TUTOR JOES
Lowercase : tutor joes
Replace : Tutor Stanley
Contains : true
Empty : false
EndWith : true
StartWith : true
Substring : Joes
Substring : Tutor
T u t o r J o e s
Length : 7
C : Tutor
C Trim : Tutor
C Trim Length : 5

StringBuffer & StringBuilder in Java

StringBuffer
The StringBuffer and StringBuilder classes are suitable for both assembling and modifying
strings; i.e they provide methods for replacing and removing characters as well as adding
them in various. Java StringBuilder class is used to create mutable (modifiable) string.

Key Points:

• Used to created mutable (modifiable) string.

• Mutable: Which can be changed?

• Is thread-safe i.e. multiple threads cannot access it simultaneously.

Methods:

• public synchronized StringBuffer append ( String s )


• public synchronized StringBuffer insert ( int offset, String s )

• public synchronized StringBuffer replace ( int startIndex, int endIndex, String str )

• public synchronized StringBuffer delete ( int startIndex, int endIndex )

• public synchronized StringBuffer reverse ()

StringBuilder
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. The StringBuffer and
StringBuilder classes are suitable for both assembling and modifying strings; i.e they provide
methods for replacing and removing characters as well as adding them in various.

Source Code
public class stringBuffer_stringBuilder {
public static void main(String args[])
{
//StringBuffer & StringBuilder in Java

StringBuilder buffer =new StringBuilder("Tutor");


System.out.println(buffer);
buffer.append(" Joes");
System.out.println(buffer);
buffer.insert(10," Computer");
System.out.println(buffer);
buffer.replace(9,11,"@@@");
System.out.println(buffer);
buffer.delete(9,11);
System.out.println(buffer);
buffer.reverse();
System.out.println(buffer);
System.out.println(buffer.charAt(2));
System.out.println(buffer.length());
System.out.println(buffer.substring(0));
System.out.println(buffer.substring(0,5));
buffer.setCharAt(0,'@');
System.out.println(buffer);
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

}
}

Output
Tutor
Tutor Joes
Tutor Joes Computer
Tutor Joe@@@Computer
Tutor Joe@Computer
retupmoC@eoJ rotuT
t
18
retupmoC@eoJ rotuT
retup
@etupmoC@eoJ rotuT
16
16
34

Count Vowels,Capital letters,small letters,numbers and


space in Java

The count to Uppercase, Lowercase, Space, Number, Vowels and Symbols in a String. The
using for the ASCII (American Standard Code for Information Interchange) Number. Codes 32-
127 are common for all the different variations of the ASCII table, they are called printable
characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols.

Source Code
public class countCharacter {
public static void main(String args[])
{
//Program to Count Uppercase,Lowercase,Space,Number,Vowels and Symbols in
a String
StringBuilder a = new StringBuilder("Ram-age is 12@");
System.out.println(a);
int upper = 0, lower = 0, space = 0, number = 0, vowels = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
lower++;
}
if (a.charAt(i) >= 65 && a.charAt(i) <= 90) {
upper++;
}
if (a.charAt(i) == 32) {
space++;
}
if (a.charAt(i) >= 48 && a.charAt(i) <= 57) {
number++;
}
if (a.charAt(i) == 'A' || a.charAt(i) == 'E' || a.charAt(i) == 'I' ||
a.charAt(i) == 'O' ||
a.charAt(i) == 'U' || a.charAt(i) == 'a' || a.charAt(i) == 'e'
|| a.charAt(i) == 'i' ||
a.charAt(i) == 'o' || a.charAt(i) == 'u') {
vowels++;
}
}
System.out.println("Uppercase : "+upper);
System.out.println("Lowercase : "+lower);
System.out.println("Space : "+space);
System.out.println("Number : "+number);
System.out.println("Vowels : "+vowels);
System.out.println("Symbols : "+(a.length()-(upper+lower+space+number
)));
}
}

Output
Ram-age is 12@
Uppercase : 1
Lowercase : 7
Space : 2
Number : 2
Vowels : 4
Symbols : 2

Reverse a String in Java

A string is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created. Initialize an empty string to the reversedString
. String reverse in java using for loop. In this article, you will learn how to make a java program
to reverse a string using for loop. A for loop is a repetition control structure which allows us to
write a loop that is executed a specific number of times.

Source Code
public class Reverse {
public static void main(String args[])
{
//Program to reverse a given string
StringBuilder a = new StringBuilder("Tutor Joes Computer Education");
System.out.println(a);
StringBuilder b=new StringBuilder();
for(int i=a.length()-1;i>=0;i--)
{
b.append(a.charAt(i));
}
System.out.println(b);
}
}

Output
Tutor Joes Computer Education
noitacudE retupmoC seoJ rotuT

Convert the given string into uppercase in Java

The string in converts all characters of the string into upper case letter. The string to be any
length and calculate its length. scan string character by character and keep checking the
index. If a character in an index is in lower case, then subtract 32 to convert it in upper case.

Source Code
public class uppercase {
public static void main(String args[]) {
//Program to Convert string to Uppercase
StringBuilder a = new StringBuilder("abc");
System.out.println("Original Input : "+a);
for(int i=0;i<a.length();i++)//97-122
{
if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
int c=(int)a.charAt(i)-32;//97-32=65 98-32=66 99-32=67
a.setCharAt(i,(char)c);//ABC
}
}
System.out.println("Uppercase Output: "+a);

}
}
Output
Original Input : abc
Uppercase Output : ABC

Convert the given string into lowercase in Java

The string in converts all characters of the string into lower case letter. The string to be any
length and calculate its length. scan string character by character and keep checking the
index. If a character in an index is in upper case, then add 32 to convert it in lower case.

Source Code
public class lowercase {
public static void main(String args[]) {
//Program to Convert string to LowerCase
StringBuilder a = new StringBuilder("ABCD");
System.out.println("Original Input : "+a);
for(int i=0;i<a.length();i++)//97-122
{
if (a.charAt(i) >= 65 && a.charAt(i) <= 90) {
int c=(int)a.charAt(i)+32;//65+32=97 66+32=98 67+32=99 68+32=100
a.setCharAt(i,(char)c);//abcd
}
}
System.out.println("Lowercase Output: "+a);

}
}

Output
Original Input : ABCD
Lowercase Output: abcd
Convert the given string into Capitalized Each Word in Java

The capitalize a word is to make its first character is upper case, and the rest is lower case
using looping and if statement. A for loop is a repetition control structure which allows us to
write a loop that is executed a specific number of times. The if statement allows you to
control if a program enters a section of code or not based on whether a given condition is true
or false. The Using ASCII Numbers convert the string into Capitalized Each Word. There are
128 standard ASCII characters, numbered from 0 to 127. Extended ASCII adds another 128
values and goes to 255.
Example :
Input : tuTor joes
Output : Tutor Joes

Source Code
public class Capitalized {
public static void main(String args[]) {
//Program to convert the given string into Capitalized Each Word.
StringBuilder a = new StringBuilder("tuTor joes coMputer education");
System.out.println("Original String : "+a);

if (a.charAt(0) >= 97 && a.charAt(0) <= 122) {


int c = (int) a.charAt(0) - 32;
a.setCharAt(0, (char) c);
}
for (int i = 1; i < a.length(); i++) {

if (a.charAt(i) == 32) {
i++;
if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
int c = (int) a.charAt(i) - 32;
a.setCharAt(i, (char) c);
}
}else {
if (a.charAt(i) >= 65 && a.charAt(i) <= 90) {
int c = (int) a.charAt(i) + 32;
a.setCharAt(i, (char) c);
}
}
}

System.out.println("Capitalized Each Word String : "+a);

}
}

Output
Original String : tuTor joes coMputer education
Capitalized Each Word String : Tutor Joes Computer Education

Convert the given string into toggle case word in Java

ToggleCase is text that is converted to mixed case version of the text using looping and if
statement. A for loop is a repetition control structure which allows us to write a loop that is
executed a specific number of times. The if statement allows you to control if a program
enters a section of code or not based on whether a given condition is true or false. The Using
ASCII Numbers convert the string into Capitalized Each Word. There are 128 standard ASCII
characters, numbered from 0 to 127. Extended ASCII adds another 128 values and goes to
255.
Example :
Input : Tutor Joes
Output : tUTOR jOES

Source Code
public class toogle {
public static void main(String args[]) {
//Program convert the given string into tOGGLE cASE wORD
StringBuilder a = new StringBuilder("Tutor Joes Computer Education");
System.out.println("Original String : "+a);

for (int i = 0; i < a.length(); i++) {


if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
int c = (int) a.charAt(i) - 32;
a.setCharAt(i, (char) c);
} else if (a.charAt(i) >= 65 && a.charAt(i) <= 90) {
int c = (int) a.charAt(i) + 32;
a.setCharAt(i, (char) c);
}
}
System.out.println("tOGGLE cASE wORD Output : "+a);
}
}

Output
Original String : Tutor Joes Computer Education
tOGGLE cASE wORD Output : tUTOR jOES cOMPUTER eDUCATION

Math Functions in Java

The Java Math class has many methods that allows you to perform mathematical tasks on
numbers. The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square and root. The java.lang.Math contains a set of
basic math functions for obtaining the absolute value, highest and lowest of two values,
rounding of values.

Methods:

• abs() : absolute value of return to the positive value

• sqrt() : The square root of the argument

• max() : Maximum of the two values passed in the argument

• min() : Minimum of the two values passed in the argument


• ceil() : Rounds float value up to an integer value

• floor() : Rounds float value down to an integer value

• pow() : Value of the first parameter raised to the second parameter

Source Code
public class MathFunctions {
public static void main(String[] args)
{
//Built-in Math Function in Java
System.out.println("Absolute value : " +Math.abs(-45));
System.out.println("Round value : " +Math.round(2.288));
System.out.println("Ceil value : " +Math.ceil(2.588));
System.out.println("Floor value : " +Math.floor(2.588));

double a = 2;
double b = 3;
System.out.println("Maximum number of a and b is: " +Math.max(a, b));
System.out.println("Square root of b is: " + Math.sqrt(b));
System.out.println("Power of a and b is: " + Math.pow(a, b));
System.out.println("Logarithm of a is: " + Math.log(a));
System.out.println("log10 of a is: " + Math.log10(a));
System.out.println("Sine value of a is: " +Math.sin(a));
System.out.println("Cosine value of a is: " +Math.cos(a));
System.out.println("Tangent value of a is: " +Math.tan(a));

}
}

Output
Absolute value : 45
Round value : 2
Ceil value : 3.0
Floor value : 2.0
Maximum number of a and b is : 3.0
Square root of b is : 1.7320508075688772
Power of a and b is : 8.0
Logarithm of a is : 0.6931471805599453
log10 of a is : 0.3010299956639812
Sine value of a is : 0.9092974268256817
Cosine value of a is : -0.4161468365471424
Tangent value of a is : -2.185039863261519

Types of Methods in Java

A Java method is a collection of statements that are grouped together to perform an


operation. A method in Java is a block of code that, when called, performs specific actions
mentioned in it. For instance, if you have written instructions to draw a circle in the method, it
will do that task.

You can insert values or parameters into methods, and they will only be executed when
called. They are also referred to as functions. The primary uses of methods in Java are:

• It allows code re-usability (define once and use multiple times)

• You can break a complex program into smaller chunks of code

• It increases code readability

Two Types of Methods :


1. User-defined Methods: We can create our own method based on our requirements.
2. Standard Library Methods: These are built-in methods in Java that are available to use.

Syntax:
Access_ specifier Return_type Method_name ( Parameter list )
{
// body of method ;
}

Access specifier :

• Public : You can access it from any class


• Private : You can access it within the class where it is defined

• Protected : Accessible only in the same package or other subclasses in another

package

Return type :

• Int : Int as the return type if the method returns value.

• Void : Void as the return type if the method returns no value.

Parameter list :

• It is a list of arguments (data_type variable_name) that will be used in the method.

Method body :

• This is the set of instructions enclosed within curly brackets.

Source Code
class Methods {
//No Return W/o args
public void add() {
int a = 123;
int b = 10;
System.out.println("Addition : " + (a + b));
}

//No Return With Args


public void sub(int x, int y) {
System.out.println("Subtraction : " + (x - y));
}
//Return Without Args
public int mul() {
int a = 123;
int b = 10;
return a * b;
}

//Return With Args


public float div(int x, int y) {
return (x / y);
}

//Recursion Function
public int factorial(int n)//5! =1*2*3*4*5=120
{
if(n==1)
return 1;
else
return (n*factorial(n-1));
}
/*
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)

return 1;
return 2*1;
return 3*2;
return 4*6;
return 5*24;

* */

//Type of User Define Methods in Java


public class functions {
public static void main(String args[]) {
Methods o = new Methods();
o.add();
o.sub(123, 10);
System.out.println("Muli : "+o.mul());
System.out.println("Division : "+o.div(123,10));
}
}

Output
Addition : 133
Subtraction : 113
Muli : 1230
Division : 12.0

Returning Arrays from Method in Java

An array is a collection of similar data elements stored at contiguous memory locations. It is


the simplest data structure where each data element can be accessed directly by only using
its index number. The method returning the array must have the return type as an array of
the same data type as that of the array being returned.

Source Code
import java.util.Arrays;
import java.util.Scanner;

public class function_array {

public static int[] sortArray() {


Scanner in = new Scanner(System.in);
System.out.println("Enter The Limit : ");
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter The Value " + i + " : ");
a[i] = in.nextInt();
}
Arrays.sort(a);
// returning array
return a;
}

//Returning Arrays from Method


public static void main(String args[]) {
int arr[] = sortArray();
for (int a : arr)
System.out.println(a);
}

Output
Enter The Limit :
5
Enter The Value 0 :
10
Enter The Value 1 :
11
Enter The Value 2 :
12
Enter The Value 3 :
13
Enter The Value 4 :
14
10
11
12
13
14

Static Member Function in Java

The static keyword is used on a class, method, or field to make them work independently of
any instance of the class.Static fields are common to all instances of a class. They do not need
an instance to access them. Static methods can be run without an instance of the class they
are in. However, they can only access static fields of that class.

Source Code
class Mathematical {
public static int power(int base, int power) {
int result = 1;
for (int i = 1; i <= power; i++) {
result *= base;
}
return result;
}
}
public class staticExample {
//Static Member Function in Java
public static void main(String args[]) {
System.out.println("Power : " + Mathematical.power(2, 3));
}
}

Output
Power : 8

Convert Decimal To Binary in Java


The convert decimal to binary is by dividing the given decimal number recursively by 2. Then,
the remainders are noted down till we get 0 as the final quotient. After this step, these
remainders are written in reverse order to get the binary value of the given decimal number.

Source Code
import java.util.Scanner;

public class decimal_binary {


public static void decimal2Binary(int n)
{
int[] binaryNum = new int[1000];

int i = 0;
while (n > 0)
{
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
System.out.print(binaryNum[j]);
}
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
System.out.println("Enter The Decimal No : ");
int n = in.nextInt();
System.out.println("Decimal No : " + n);
System.out.print("Binary No : ");
decimal2Binary(n);
}
}

Output
Enter The Decimal No :
10
Decimal No : 10
Binary No : 1010

Introduction of Object Oriented Programming in Java

OOP stands for Object-Oriented Programming.. The popular object-oriented languages


are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for


example, object, classes, abstraction, inheritance, polymorphism, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts.

• Object - Any entity that has state and behaviour is known as an object.

• Class - Collection of objects is called class. It is a logical entity.

• Inheritance - When one object acquires all the properties and behaviours of a parent

object, it is known as inheritance.

• Polymorphism - If one task is performed in different ways, it is known as

polymorphism.

• Abstraction- Hiding internal details and showing functionality is known as

abstraction.

• Encapsulation - Binding (or wrapping) code and data together into a single unit are

known as encapsulation.
Class & object in Java

A class is often defined as the blueprint or template for an object. We can create multiple
objects from a class.

An object is an identifiable entity with some characteristics, state and behaviour.

Memory is allocated when we create the objects of a class type. A class contains properties
and methods to define the state and behaviour of its object. It defines the data and the
methods that act upon that data.

Example :
A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
eating. An object is an instance of a class.

Syntax Of Class :
class class_name
{
Variables ;
Methods ;
}

Syntax Of Object :
Class_Name ReferenceVariable ( or ) Object = new Class_Name ( ) ;

Source Code
//Class & Object in Java
class Rectangle
{
int length, width;

void getDetails(int x, int y) {


length = x;
width = y;
}
int area() {
int a = length * width;
return a;
}
}
public class class_object {
public static void main(String args[]) {
Rectangle o1 =new Rectangle();
o1.length=10;
o1.width=20;
System.out.println("Area of Rectangle : "+o1.area());

Rectangle o2=new Rectangle();


o2.getDetails(20,30);
System.out.println("Area of Rectangle : "+o2.area());

}
}

Output
Area of Rectangle : 200
Area of Rectangle : 600

Data Hiding Getter & Setter in Java

A class is a non-primitive or user-defined data type in Java, while an object is an instance of a


class. They are getters and setters; the standard way to provide access to data in Java
classes. Setters and Getters allow for an object to contain private variables which can be
accessed and changed with restrictions.

Source Code
//Data Hiding Getter and Setter in Java

class ShapeRectangle {
private int length, width;
//Getter Method
int getLength() {
return length;
}

int getWidth() {
return width;
}

//Setter Method
void setLength(int l) {
if (l > 0)
length = l;
else
length = 0;
}

void setWidth(int w) {
if (w > 0)
width = w;
else
width = 0;
}

int area() {
int a = length * width;
return a;
}
}

public class get_set {


public static void main(String args[]) {
ShapeRectangle o = new ShapeRectangle();
o.setLength(-10);
o.setWidth(20);
System.out.println("Length : " + o.getLength());
System.out.println("Width : " + o.getWidth());
System.out.println("Area of Rectangle : " + o.area());
}
}

Output
Area of Rectangle : 200
Area of Rectangle : 600

Constructor in Java

Constructors are special methods named after the class and without a return type, and are
used to construct objects. Constructors, like methods, can take input parameters.
Constructors are used to initialize objects. Abstract classes can have constructors also.

Constructors are different from methods:

• Constructors can only take the modifiers public, private, and protected, and cannot be

declared abstract, final, static, or synchronized.

• Constructors do not have a return type

• Constructors MUST be named the same as the class name.

Types of constructor :

• Default constructor

• Parametrized constructor

• Copy constructor

• Constructor Overloading

Source Code
//Constructor in Java
class RectangleShape {
int length, width;

public RectangleShape() {
System.out.println("Constructor Called");
length=2;
width=10;
}

int area() {
int a = length * width;
return a;
}
}

public class constructor {


public static void main(String args[]) {
RectangleShape o1 = new RectangleShape();
System.out.println("Area of Rectangle : " + o1.area());

}
}

Output
Constructor Called
Area of Rectangle : 20

Parametrized Constructor & Constructor Overloading in


Java

Parameterized constructors
The parameterized constructors are the constructors having a specific number of arguments
to be passed. The purpose of a parameterized constructor is to assign user-wanted specific
values to the instance variables of different objects.

Example :
When we create the object like this Student s = new Student ( “Joes” , 15 ) then the new
keyword invokes the Parameterized constructor with int and string parameters public
Student( String n , String a ) after object creation.

Constructor overloading
Constructors are special methods named after the class and without a return type, and
are used to construct objects. Constructors, like methods, can take input parameters.
Constructors are used to initialize objects. Constructor overloading in Java means to more
than one constructor in an instance class.

Source Code
//Parameterized Constructor & Constructor Overloading
class Box
{
float length,breadth;
public Box(){ //Default
length=2;
breadth=5;
}
public Box(float x,float y) //Parameterized
{
length=x;
breadth=y;
}
Box(float x)
{
length=breadth=x;
}
float area()
{
return length*breadth;
}
}
public class constructor_overloading {
public static void main(String args[]) {
Box o =new Box();
System.out.println("Area : "+o.area() );

Box o1 =new Box(3,6);


System.out.println("Area : "+o1.area() );

Box o2 =new Box(3);


System.out.println("Area : "+o2.area() );
}
}

Output
Area : 10.0
Area : 18.0
Area : 9.0

Copy Constructor in Java

Constructors are special methods named after the class and without a return type, and are
used to construct objects. Constructors, like methods, can take input parameters.
Constructors are used to initialize objects. A copy constructor is a constructor that creates a
new object using an existing object of the same class and initializes each instance variable of
newly created object with corresponding instance variables of the existing object passed as
argument.

Syntax :
public class_Name(const className old_object)

Example :
Public student(student o)

Source Code
import java.util.Scanner;
class CopyConstructor
{
int age;
String name;
CopyConstructor(int a,String n)
{
age=a;
name=n;
}
CopyConstructor(CopyConstructor cc)
{
age=cc.age;
name=cc.name;
}
void display()
{
System.out.println("Your name is : "+name + "\nAge is : "+age);
}
public static void main(String[] arg)
{
System.out.print("Enter your name and age :");
Scanner scan = new Scanner(System.in);
String name =scan.nextLine();
int age =scan.nextInt();
CopyConstructor cc = new CopyConstructor(age,name);
CopyConstructor c2=new CopyConstructor(cc);
cc.display();
c2.display();
}
}

Output
Enter your name and age :Tutor Joes
27
Your name is : Tutor Joes
Age is : 27
Your name is : Tutor Joes
Age is : 27

Arrays of Objects in Java

An array is a collection of similar data elements stored at contiguous memory locations. It is


the simplest data structure where each data element can be accessed directly by only using
its index number. Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.

Syntax :
Class_name object [ ] = new class_name ( ) ;

Example :
Student s [ 5 ] = new Student ( ) ;

Source Code
//Array of Objects in Java
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
void print()
{
System.out.println("Name : "+name);
System.out.println("Roll No : "+roll_no);
System.out.println("---------------------------------");
}
}
public class array_objects {
public static void main (String[] args)
{
Student[] o;
o = new Student[5];
o[0] = new Student(10,"Ram");
o[1] = new Student(20,"Sam");
o[2] = new Student(30,"Ravi");
o[3] = new Student(40,"Kumar");
o[4] = new Student(50,"Sundar");
for (int i = 0; i < o.length; i++)
o[i].print();
}
}

Output
Name : Ram
Roll No : 10
---------------------------------
Name : Sam
Roll No : 20
---------------------------------
Name : Ravi
Roll No : 30
---------------------------------
Name : Kumar
Roll No : 40
---------------------------------
Name : Sundar
Roll No : 50
---------------------------------

Nesting of Methods in Java


A method can be called by using only its name by another method of the same class that is
called Nesting of Methods. A method of a class can be called only by an object of that class
using the dot operator. So, there is an exception to this. When a method in java calls another
method in the same class, it is called Nesting of methods.

Source Code
//Nesting of Methods in Java
class demo {
private int m, n;

demo(int x, int y) {
m = x;
n = y;
}

int largest() {
if (m > n)
return m;
else
return n;
}

void display()
{
int large=largest();
System.out.println("The Greatest Number is : "+large);
}

}
public class nested_method {
public static void main(String args[]) {
demo o =new demo(10,20);
o.display();
}

}
Output
The Greatest Number is : 20

Single Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. Inheritance is a basic object oriented feature in which one class
acquires and extends upon the properties of another class, using the keyword extends.

With the use of the extends keyword among classes, all the properties of the superclass (also
known as the Parent Class or Base Class) are present in the subclass (also known as the Child
Class or Derived Class)

Types of Inheritance :

• Single Inheritance

• Multilevel Inheritance

• Hierarchical Inheritance

Single Inheritance
Single inheritance is one base class and one derived class. One in which the derived class
inherits the one base class either publicly, privately or protected

Syntax:
class baseclass_Name
{
superclass data variables ;
superclass member functions ;
}
class derivedclass_Name extends baseclass _Name
{
subclass data variables ;
subclass member functions ;
}

Source Code
//Single Inheritance in Java
class Father //Base
{
public void house()
{
System.out.println("Have Own 2BHK House.");
}
}
class Son extends Father //Derived
{
public void car()
{
System.out.println("Have Own Audi Car.");
}
}

public class single {


public static void main(String args[])
{
Son o =new Son();
o.car();
o.house();
}
}

Output
Have Own Audi Car.
Have Own 2BHK House.

Multilevel Inheritance in Java


Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system). When a class extends a class, which extends anther class then this is called
multilevel inheritance.

Example :
class Son extends class Father and class Father extends class Grandfather then this type
of inheritance is known as multilevel inheritance.

Source Code
//Multilevel Inheritance in Java
class GrandFather {
public void house() {
System.out.println("3 BHK House.");
}
}
class father extends GrandFather{
public void land() {
System.out.println("5 Arcs of Land..");
}
}

class son extends father {


public void car() {
System.out.println("Own Audi Car..");
}
}

public class multilevel {


public static void main(String args[]) {
son o = new son();
o.car();
o.house();
o.land();
}
}

Output
Own Audi Car..
3 BHK House.
5 Arcs of Land..

Hierarchical Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. Inheritance is a basic object oriented feature in which one class
acquires and extends upon the properties of another class, using the keyword extends.
Hierarchical Inheritance is one base class and more then derived class.
Example :
Leaf, Flower, root are derived from Tree base class.

Source Code
//Hierarchical Inheritance in Java
class shape {
float length, breadth, radius;
}
class rect extends shape {
public rect(float l, float b) {
length = l;
breadth = b;
}
float rectangle_area() {
return length * breadth;
}
}
class circle extends shape {
public circle(float r) {
radius = r;
}
float circle_area() {
return 3.14f * (radius * radius);
}
}
class square extends shape {
public square(float l) {
length = l;
}

float square_area() {
return (length * length);
}
}

public class Hierarchical {


public static void main(String[] args) {

rect o1 =new rect(2,5);


System.out.println("Area of Rectangle : "+o1.rectangle_area());

circle o2 =new circle(5);


System.out.println("Area of Circle : "+ o2.circle_area());

square o3 =new square(3);


System.out.println("Area of Square : "+o3.square_area());

}
}

Output
Area of Rectangle : 10.0
Area of Circle : 78.5
Area of Square : 9.0
Method Overloading in Java

Method overloading, also known as function overloading, is the ability of a class to have
multiple methods with the same name, granted that they differ in either number or type of
arguments. Compiler checks method signature for method overloading.

Method signature consists of three things :

• Method name

• Number of parameters

• Types of parameters

These types of polymorphism are called static or compile time polymorphism because the
appropriate method to be called is decided by the compiler during the compile time based on
the argument list.

Source Code
//Method Overloading in Java
class MathOperation {
public static int multiply(int a, int b) {
return a * b;
}
public static double multiply(double x, double y) {
return x * y;
}
public static double multiply(double i, int j) {
return i * j;
}
public static int multiply(int r) {
return r*r;
}
}
public class methodOverloading {
public static void main(String arg[]) {
System.out.println("Multiply 2 Integer Value : " + MathOperation.multiply(
25, 10));
System.out.println("Multiply 2 Double Value : " + MathOperation.multiply(2
.5, 8.5));
System.out.println("Multiply Double & Integer Value : " + MathOperation.mu
ltiply(2.5, 8));
System.out.println("Multiply Integer Value : " + MathOperation.multiply(2)
);
}
}

Output
Multiply 2 Integer Value : 250
Multiply 2 Double Value : 21.25
Multiply Double & Integer Value : 20.0
Multiply Integer Value : 4

Method Overriding in Java

Overriding in Inheritance is used when you use a already defined method from a super class
in a sub class, but in a different way than how the method was originally designed in the
super class. Overriding allows the user to reuse code by using existing material and modifying
it to suit the user’s needs better.

Source Code
//Method Overriding in Java
class user { //Base
String name;
int age;
user(String n, int a) {
this.name = n;
this.age = a;
}
public void display(){
System.out.println("Name : "+name);
System.out.println("Age : "+age);
}

}
class MainProgrammer extends user{ //Derived Class
String CompanyName;
MainProgrammer(String n, int a,String c){
super(n,a);
this.CompanyName=c;
}
public void display(){
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Company Name : "+CompanyName);
}

}
public class methodOverriding {
public static void main(String args[]) {
MainProgrammer o =new MainProgrammer("Raja",22,"Tutor Joes");
o.display();
}
}

Output
Name : Raja
Age : 22
Company Name : Tutor Joes

Abstract Class in Java


An abstract class is a class marked with the abstract keyword. It, contrary to non-abstract
class, may contain abstract - implementation-less - methods. It is, however, valid to create
an abstract class without abstract methods.

An abstract class cannot be instantiated. It can be sub-classed (extended) as long as the sub-
class is either also abstract, or implements all methods marked as abstract by super classes.

Abstraction can be achieved with either abstract classes or interfaces .

• Abstract class must have one abstract method.

• We can’ts create object using abstract class.

• Abstract class can have abstract and non abstract methods.

Source Code
//Abstract Class in Java Programming
abstract class Shape
{
abstract void draw();
void message()
{
System.out.println("Message From Shape");
}
}
class rectangleShape extends Shape
{
@Override
void draw() {
System.out.println("Draw Rectangle Using Length & Breadth..");
}
}

public class abstractDemo {


public static void main(String args[]) {
rectangleShape o =new rectangleShape();
o.draw();
o.message();
}
}

Output
Draw Rectangle Using Length & Breadth..
Message From Shape

Smart Phone Example using Abstract Class in Java

An abstract class is a class marked with the abstract keyword. It, contrary to non-abstract
class, may contain abstract - implementation-less - methods. It is, however, valid to create
an abstract class without abstract methods. An abstract class cannot be instantiated. It can
be sub-classed (extended) as long as the sub-class is either also abstract, or implements all
methods marked as abstract by super classes.

Source Code
//Example for Abstract Class in Java Programming
abstract class Mobile {
void VoiceCall() {
System.out.println("You can Make Voice Call");
}
abstract void camera();
abstract void touchDisplay();

}
class samsung extends Mobile
{

@Override
void camera() {
System.out.println("16 Mega Pixel Camera");
}

@Override
void touchDisplay() {
System.out.println("5.5 inch Display");
}
}

class Nokia extends Mobile


{

@Override
void camera() {
System.out.println("8 Mega Pixel Camera");
}

@Override
void touchDisplay() {
System.out.println("5 inch Display");
}

void fingerPrint() {
System.out.println("Fast Finger Sensor..");
}
}
public class abstractDemo2 {
public static void main(String args[]) {

samsung M32 =new samsung();


M32.VoiceCall();
M32.touchDisplay();
M32.camera();
System.out.println("-------------------------");
Nokia N1= new Nokia();
N1.VoiceCall();
N1.camera();
N1.touchDisplay();
N1.fingerPrint();

}
}

Output
You can Make Voice Call
5.5 inch Display
16 Mega Pixel Camera
-------------------------
You can Make Voice Call
8 Mega Pixel Camera
5 inch Display
Fast Finger Sensor..

What is interface in Java

Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signatures, no body, see: Java abstract method). As mentioned above they are used for full
abstraction. Since methods in interfaces do not have body, they have to be implemented by
the class before you can access them.

The class that implements interface must implement all the methods of that interface. Also,
java programming language does not allow you to extend more than one class, however you
can implement more than one interface in your class.

Source Code
interface Animal {
void Sound();
void sleep();
}
class Dog implements Animal
{
@Override
public void Sound() {
System.out.println("The Dog Sounds like : woof");
}

@Override
public void sleep() {
System.out.println("Dog Sleeping");
}
}
public class interfaceDemo{
public static void main(String args[]) {
Dog o =new Dog();
o.Sound();
o.sleep();
}
}

Output
The Dog Sounds like : woof
Dog Sleeping

Implement multiple interfaces in Java

Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signatures, no body, see: Java abstract method). A class can extend the features of other
classes by use of inheritance. When a class extending more than one class is known as
multiple inheritance. But Java doesn’t allow it because it creates the diamond problem and
too complex to manage. We can achieve the multiple inheritances by use of interface.

Source Code
//How Multiple inheritance can be achieved by implement multiple interfaces
class Phone
{
void voiceCall()
{
System.out.println("Make VoiceClass");
}
void sms()
{
System.out.println("We Can send SMS");
}
}
interface Camera
{
void click();
void record();
}

interface player
{
void play();
void pause();
void stop();
}

class SmartPhone extends Phone implements Camera,player


{

@Override
public void click() {
System.out.println("Take a Selfi");
}

@Override
public void record() {
System.out.println("Take a video");
}

@Override
public void play() {
System.out.println("Play Music");
}

@Override
public void pause() {
System.out.println("Pause Music");
}

@Override
public void stop() {
System.out.println("Stop Music");
}
}

public class interfaceDemo2 {


public static void main(String[] args) {
SmartPhone o =new SmartPhone();
o.voiceCall();
o.sms();
o.click();
o.record();
o.play();
o.pause();
o.stop();
}
}

Output
Make VoiceClass
We Can send SMS
Take a Selfi
Take a video
Play Music
Pause Music
Stop Music
More About Interface in Java

Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signatures, no body, see: Java abstract method). A class can extend the features of other
classes by use of inheritance. When a class extending more than one class is known as
multiple inheritance. But Java doesn’t allow it because it creates the diamond problem and
too complex to manage. We can achieve the multiple inheritances by use of interface.

Source Code
interface interDemo {
final static int A = 25;

public abstract void fun1();

public abstract void fun2();

public static void fun3() {


System.out.println("I am Fun-3");
}
private void fun6(){
System.out.println("Fun-6");
}
default void fun5() {
System.out.println("Fun-5");
}
}

interface interDemo2 extends interDemo {


void fun4();
}

class TestInter implements interDemo2 {


@Override
public void fun1() {
System.out.println("Fun-1");
}

@Override
public void fun2() {
System.out.println("Fun-2");
}

@Override
public void fun4() {
System.out.println("Fun-4");
}
}

public class interfaceModeDemo {


public static void main(String[] args) {
System.out.println("A : " + interDemo.A);
interDemo.fun3();
}
}

Output
A : 25
I am Fun-3
Difference Between Abstract Class and Interface in Java

Abstract classes and interfaces are the two main building blocks of the Java Programming
Language. Though both are primarily used for abstraction, they are very different from each
other and cannot be used interchangeably.

Abstract Class Interface

It can extend only one class or one abstract class at a time. It can extend any number of interfaces at a time

It can extend another concrete (regular) class or abstract class It can only extend another interface

Abstract class have both abstract and concrete methods Interface can have only abstract methods

Abstract class keyword "abstract" is mandatory to declare a Interface keyword "abstract" is optional to declare
method as an abstract a method as an abstract

It can have protected and public abstract methods Interface can have only have public abstract
methods

Abstract class can have static, final or static final variable with Interface can only have public static final
any access specifier (constant) variable
Nested Inner Class in Java

A class is a non-primitive or user-defined data type in Java, while an object is an instance of a


class. To define a class within another class. Such a class is called a Nested Class. Nested
Classes are called Inner Classes if they were declared as non-static, if not, they are simply
called Static Nested Classes. This page is to document and provide details with examples on
how to use Java Nested and Inner Classes.

Syntax:
class Class_Name // OuterClass
{
...
class Class_Name // NestedClass
{
...
}
}

Source Code
// Nested Inner Class
class outer {
int a=50;
class inner
{
int b=58;
void innerDisplay()
{
System.out.println("A : "+a);
System.out.println("B : "+b);
}

}
void outerDisplay()
{
inner i =new inner();
i.innerDisplay();
System.out.println("B from inner Class by Outer Display : "+i.b);
}
}
public class nestedClass {
public static void main(String args[]) {
outer o =new outer();
o. outerDisplay();
outer.inner i =new outer().new inner();
i.innerDisplay();
}
}

Output
A : 50
B : 58
B from inner Class by Outer Display : 58
A : 50
B : 58

Local Inner Class in Java

A class is a non-primitive or user-defined data type in Java, while an object is an instance of a


class. Local classes are classes that are defined in a block, which is a group of zero or more
statements between balanced braces. You typically find local classes defined in the body of a
method.

This section covers the following topics: Declaring Local Classes. Accessing Members of an
Enclosing Class. A class i.e. created inside a method is called local inner class in java. If you
want to invoke the methods of local inner class, you must instantiate this class inside the
method.

Syntax:
class Class_Name // OuterClass
{
void method ( )
{
class Class_Name // NestedClass
{
...
}
}
}

Source Code
//Local Inner Class

class Outercls
{
void display()
{
class Inner
{
void innerDisplay()
{
System.out.println("Inner Display");
}
}

Inner i =new Inner();


i.innerDisplay();
}
}

public class localInnerClass {


public static void main(String[] args) {
Outercls o =new Outercls();
o.display();
}
}
Output
Inner Display

Anonymous Inner Class in Java

A class is a non-primitive or user-defined data type in Java, while an object is an instance of a


class. To define a class within another class. Such a class is called a Nested Class. An
anonymous it is an inner class without a name and for which only a single object is created.
An anonymous inner class can be useful when making an instance of an object with certain
“extras” such as overriding methods of a class or interface, without having to actually
subclass a class.

Source Code
//Anonymous Inner Class

abstract class testDemo {


abstract void display();
}

class outerDemo {
public void outerDisplay() {
testDemo o =new testDemo() {
@Override
public void display() {
System.out.println("Test Display");
}
};
o.display();
}
}

public class anonymousInner {


public static void main(String[] args) {
outerDemo o =new outerDemo();
o.outerDisplay();
}
}

Output
Test Display

Static Inner Class in Java

The static keyword is used on a class, method, or field to make them work independently of
any instance of the class.Static fields are common to all instances of a class. They do not need
an instance to access them.

Static methods can be run without an instance of the class they are in. However, they can
only access static fields of that class. Static classes can be declared inside of other classes.
They do not need an instance of the class they are in to be instantiated.

Source Code
//Static Inner Class
class OuterClass {
static int x=10;
int y=20;
static class InnerClass
{
void display()
{
System.out.println("X : "+x);
}
}
}

public class staticInnerClass {


public static void main(String[] args) {
OuterClass.InnerClass i =new OuterClass.InnerClass();
i.display();
}
}

Output
X : 10

Static Members in Java

Static method in Java is a method which belongs to the class and not to the object. A static
method can access only static data. It is a method which belongs to the class and not to the
object(instance).

• A static method can access only static data. It cannot access non-static data (

instance variables ) .

• A static method can call only other static methods and cannot call a non-static

method from it .

• A static method can be accessed directly by the class name and doesn’t need any

object .

Source Code
//Static Variables and Static Methods
class staticTest
{
static int a=10;
int b=20;
void show()
{
System.out.println("A : "+a+" B : "+b);
}
static void display()
{
System.out.println("A : "+a);
}
}
public class stat_vari_methods {
public static void main(String args[])
{
staticTest o1=new staticTest();
o1.show();
staticTest o2=new staticTest();
o2.b=100;
staticTest.a=200;
o2.show();
o1.show();
}
}

Output
A : 10 B : 20
A : 200 B : 100
A : 200 B : 20

Static Blocks in Java

The static block is a set of instructions that is run only once when a class is loaded into
memory. A static block is also called a static initialization block. This is because it is an option
for initializing or setting up the class at run-time.

Source Code
//Static Blocks in Java
class BlockTest
{
static {
System.out.println("BlockTest-1");
}
static {
System.out.println("BlockTest-2");
}
}
public class staticBlocks {
static {
System.out.println("Block-1");
}
public static void main(String[] args) {
BlockTest o =new BlockTest();
System.out.println("Main");
}
static {
System.out.println("Block-2");
}
}

Output
Block-1
Block-2
BlockTest-1
BlockTest-2
Main
Final in Java

Final in Java can refer to variables, methods and classes. The final keyword is used in several
contexts to define an entity that can only be assigned once. Once a final variable has been
assigned, it always contains the same value.

There are three simple rules :

• Final variable cannot be reassigned

• Final method cannot be overridden

• Final class cannot be extended

Source Code
//Final Variables in Java
class Test
{
final int MIN=1;
final int NORMAL;
final int MAX;

Test(int normal) {
NORMAL = normal;
MAX =100;
}
void display()
{
System.out.println("MIN : "+MIN);
System.out.println("NORMAL : "+NORMAL);
System.out.println("MAX : "+MAX);
}
}
public class finalTest {
public static void main(String args[])
{
Test o =new Test(50);
o.display();
}
}

Output
MIN : 1
NORMAL : 50
MAX : 100

Final Methods in Java

We can declare a method as final, once you declare a method final it cannot be overridden. So,
you cannot modify a final method from a sub class. The main intention of making a method
final would be that the content of the method should not be changed by any outsider.

Source Code
//Final Methods in Java
class Super
{
public void display()
{
System.out.println("I am Super Display");
}
final void finalDisplay()
{
System.out.println("I am Super Final Display");
}
}
class sub extends Super
{
public void display()
{
System.out.println("I am Sub Display");
}
}

public class finalMethods {


public static void main(String args[])
{
sub o =new sub();
o.display();
o.finalDisplay();
}
}

Output
I am Sub Display
I am Super Final Display

Final Class in Java

When used in a class declaration, the final modifier prevents other classes from being
declared that extend the class. A final class is a "leaf" class in the inheritance class hierarchy.

Example :
// This declares a final class
final class MyFinalClass
{
// statements
}
// Compilation error: cannot inherit from final MyFinalClass
class MySubClass extends MyFinalClass
{
// statements
}
Source Code
//Final Class in Java
final class finalClassDemo
{
public void display()
{
System.out.println("I am Display");
}
}

public class finalClasss{


public static void main(String[] args) {
finalClassDemo o =new finalClassDemo();
o.display();

}
}

Output
I am Display

Singleton Class in Java

A singleton is a class that only ever has one single instance. For more information on the
Singleton design pattern, please refer to the Singleton topic in the Design Patterns tag.

Source Code
//Singleton Class in Java
class ABC
{
static ABC obj =null;
private ABC(){}
public static ABC getInstance()
{
if(obj==null)
obj=new ABC();
return obj;
}
void display()
{
System.out.println("I am Display");
}
}

public class Singleton {


public static void main(String[] args) {
ABC o=ABC.getInstance();
o.display();
}
}

Output
I am Display

Enumeration in Java

Java enums (declared using the enum keyword) are shorthand syntax for sizable quantities of
constants of a single class. Enum can be considered to be syntax sugar for a sealed class that
is instantiated only a number of times known at compile-time to define a set of constants. A
simple enum to list the different seasons would be declared as follows:

Example :
public enum GameLevel
{
LOW,
MEDIUM,
HIGH,
}

Source Code
//Enumeration in Java
public class enumDemo {
enum GameLevel {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
//Assign Enum Variable
GameLevel a=GameLevel.HIGH;
System.out.println(a);

//Use Enum in Switch


switch(a) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}

//Enum by loop
for (GameLevel level : GameLevel.values()) {
System.out.println(level);
}

}
}
Output
HIGH
High level
LOW
MEDIUM
HIGH

Date and Time Functions in Java

Java provides the Date class available in java.util package, this class encapsulates the current
date and time. Java Dates are LocalDate, Represents a date (year, month, day (yyyy-MM-dd)).
Java Time are LocalTime, Represents a time (hour, minute, second and nanoseconds (HH-
mm-ss-ns)). Calendar class in Java is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc

Source Code
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@SuppressWarnings("ALL")
public class DataTimeDemo {
public static void main(String[] args) {

System.out.println(System.currentTimeMillis());
long year=(System.currentTimeMillis()/1000/60/60/24/365);
System.out.println(year);
//System.out.println(Long.MAX_VALUE);
//System.out.println((Long.MAX_VALUE/1000/60/60/24/365));
//Date d =new Date(System.currentTimeMillis());
//Java 8
Date d =new Date();//MM-DD-YYYY
System.out.println(d);
System.out.println("Date : "+d.getDate());
System.out.println("Day : "+d.getDay()); //0 Sunday to 7-Saturday
System.out.println("Month : "+d.getMonth());//0 Jan to 11 Dec
System.out.println("Year : "+(d.getYear()+1900));
System.out.println("Time : "+d.getTime());
System.out.println("Hours : "+d.getHours());
System.out.println("Minutes : "+d.getMinutes());
System.out.println("Seconds : "+d.getSeconds());

GregorianCalendar o =new GregorianCalendar();


//System.out.println(o);
System.out.println(o.isLeapYear(2020));
System.out.println("Date : "+o.get(Calendar.DATE));
System.out.println("Month : "+o.get(Calendar.MONTH));
System.out.println("Year : "+o.get(Calendar.YEAR));
System.out.println("Day of Week : "+o.get(Calendar.DAY_OF_WEEK)); //1-Sun
to 7-Sat
System.out.println("Day of Year : "+o.get(Calendar.DAY_OF_YEAR));

}
}

Output
1647422013418
52
Wed Mar 16 14:43:33 IST 2022
Date : 16
Day : 3
Month : 2
Year : 2022
Time : 1647422013422
Hours : 14
Minutes : 43
Seconds : 33
true
Date : 16
Month : 2
Year : 2022
Day of Week : 4
Day of Year : 75

Wrapper Class - Converting primitive number to number


object in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Source Code
public class wrapperClass1 {
public static void main(String args[])
{
//Converting primitive number to number object
//Byte Number to Byte Object
byte b=10;
String s1="25";
Byte bo1 =new Byte(b);
Byte bo2 = Byte.valueOf(s1);
System.out.println("Byte Object-1 : "+bo1);
System.out.println("Byte Object-2 : "+bo2);

//Short Number to Short Object


short s=85;
String s2="95";
Short so1 =new Short(s);
Short so2 = Short.valueOf(s2);
System.out.println("Short Object-1 : "+so1);
System.out.println("Short Object-2 : "+so2);

//Int Number to Integer Object


int i=125;
String s3="100";
Integer io1 =new Integer(i);
Integer io2 = Integer.valueOf(s3);
System.out.println("Integer Object-1 : "+io1);
System.out.println("Integer Object-2 : "+io2);

//Long Number to Long Object


long l=122525;
String s4="100885";
Long lo1 =new Long(l);
Long lo2 = Long.valueOf(s4);
System.out.println("Long Object-1 : "+lo1);
System.out.println("Long Object-2 : "+lo2);

//Float Number to Float Object


float f=25.5f;
String s5="23.25f";
Float fo1 =new Float(f);
Float fo2 = Float.valueOf(s5);
System.out.println("Float Object-1 : "+fo1);
System.out.println("Float Object-2 : "+fo2);

//Double Number to Double Object


double d=258.5555;
String s6="223.25";
Double do1 =new Double(d);
Double do2 = Double.valueOf(s6);
System.out.println("Double Object-1 : "+do1);
System.out.println("Double Object-2 : "+do2);
}
}

Output
Byte Object-1 : 10
Byte Object-2 : 25
Short Object-1 : 85
Short Object-2 : 95
Integer Object-1 : 125
Integer Object-2 : 100
Long Object-1 : 122525
Long Object-2 : 100885
Float Object-1 : 25.5
Float Object-2 : 23.25
Double Object-1 : 258.5555
Double Object-2 : 223.25

Wrapper Class - Converting number object to primitive


number in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Source Code
public class wrapperClass2 {
public static void main(String args[])
{
//Converting number object to primitive number.

// Byte B= new Byte((byte) 65);


Byte B= Byte.valueOf((byte) 65);
byte b= B.byteValue();
System.out.println(b);

// Short S= new Short((short) 25);


Short S= Short.valueOf((short) 25);
short s= S.shortValue();
System.out.println(s);

// Integer I= new Integer((int) 45);


Integer I= Integer.valueOf((int) 45);
int i= I.intValue();
System.out.println(i);

// Float F= new Float(45.25f);


Float F= Float.valueOf(45.25f);
float f= F.floatValue();
System.out.println(f);

Long L= Long.valueOf(1052695);
long l= L.longValue();
System.out.println(l);

Double D= Double.valueOf(45.25);
double d= D.doubleValue();
System.out.println(d);

}
}

Output
65
25
45
45.25
1052695
45.25

Wrapper Class - Converting primitive number to string


object in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Source Code
public class wrapperClass3 {
public static void main(String args[])
{
//Converting primitive number to string object.
short s=25;
String S=Short.toString(s);//"25"
System.out.println("Short String Object : "+S);
byte b=25;
String B=Byte.toString(b);
System.out.println("Byte String Object : "+B);
int i=25;
String I=Integer.toString(i);
System.out.println("Integer String Object : "+I);
long l=25;
String L=Long.toString(l);
System.out.println("Long String Object : "+L);
float f=25.5f;
String F=Float.toString(f);
System.out.println("Float String Object : "+F);
double d=25.525;
String D=Double.toString(d);
System.out.println("Double String Object : "+D);
}
}
Output
Short String Object : 25
Byte String Object : 25
Integer String Object : 25
Long String Object : 25
Float String Object : 25.5
Double String Object : 25.525

Wrapper Class - Converting string object to primitive


numbers in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Source Code
public class wrapperClass4 {
public static void main(String args[])
{
//Converting string object to primitive numbers.
String SI="25";
Integer I= Integer.valueOf(SI);
int i= I.intValue();
System.out.println(i);
String SD="25.25";
Double D= Double.valueOf(SD);
double d= D.doubleValue();
System.out.println(d);
}
}

Output
25
25.25

Wrapper Class - Converting numeric string object to


primitive numbers in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Source Code
public class wrapperClass5 {
public static void main(String args[])
{
//Converting numeric string object to primitive numbers.
/*String SI="25";
Integer I= Integer.valueOf(SI);
int i= I.intValue();
System.out.println(i);*/

String SI="25";
int i=Integer.parseInt(SI);
System.out.println("int Value : "+i);
String SF="25.25f";
float f=Float.parseFloat(SF);
System.out.println("float Value : "+f);
}
}

Output
int Value : 25
float Value : 25.25

Shallow Copy Object Cloning in Java


One method of copying an object is the shallow copy. In that case a new object B is created,
and the field’s values of A are copied over to B. Default behavior when cloning an object is to
perform a shallow copy of the object's fields. In that case, both the original object and the
cloned object, hold references to the same objects.

Source Code
//Shallow Copy Object Cloning in Java
/*
class Designation
{
String role;
@Override
public String toString() {
return role;
}
}
class Employee implements Cloneable
{
String name;
int age;
Designation deg=new Designation();

public void display()


{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Department : "+deg);
System.out.println("----------------------");
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
public class objectCloningDemo {
public static void main(String[] args) throws CloneNotSupportedException {

Employee e1 =new Employee();


e1.name="Ram Kumar";
e1.age=25;
e1.deg.role="Manager";
System.out.println("Before Changing Role : ");
e1.display();

System.out.println("Cloning and Printing E2 object : ");


Employee e2 = (Employee)e1.clone();
e2.deg.role="HR";
e2.display();

System.out.println("After Changing Role : ");


e1.display();

}
}
*/

Output
Before Changing Role :
Name : Ram Kumar
Age : 25
Department : Manager
----------------------
Cloning and Printing E2 object :
Name : Ram Kumar
Age : 25
Department : HR
----------------------
After Changing Role :
Name : Ram Kumar
Age : 25
Department : HR
----------------------

Deep Copy Object Cloning in Java

An alternative is a deep copy, meaning that fields are dereferences: rather than references to
objects being copied, new copy objects are created for any referenced objects, and references
to these placed in B. The result is different from the result a shallow copy gives in that the
objects referenced by the copy B are distinct from those referenced by A, and independent.

Deep copies are more expensive, due to needing to create additional objects, and can be
substantially more complicated, due to references possibly forming a complicated graph.

Source Code
//Deep Copy Object Cloning in Java
class Designation
{
String role;
@Override
public String toString() {
return role;
}
}
class Employee implements Cloneable
{
String name;
int age;
Designation deg=new Designation();

public void display()


{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Department : "+deg);
System.out.println("----------------------");
}
public Object clone() throws CloneNotSupportedException
{

// Assign the shallow copy to new reference variable e


Employee e = (Employee)super.clone();

// Creating a deep copy for deg (Designation)


e.deg = new Designation();
e.deg.role = deg.role;

// Create a new object for the field e


// and assign it to shallow copy obtained,
// to make it a deep copy
return e;
}

}
public class objectCloningDeepDemo {
public static void main(String[] args) throws CloneNotSupportedException {

Employee e1 =new Employee();


e1.name="Ram Kumar";
e1.age=25;
e1.deg.role="Manager";
System.out.println("Before Changing Role : ");
e1.display();

System.out.println("Cloning and Printing E2 object : ");


Employee e2 = (Employee)e1.clone();
e2.deg.role="HR";
e2.display();

System.out.println("After Changing Role : ");


e1.display();

}
}

Output
Before Changing Role :
Name : Ram Kumar
Age : 25
Department : Manager
----------------------
Cloning and Printing E2 object :
Name : Ram Kumar
Age : 25
Department : HR
----------------------
After Changing Role :
Name : Ram Kumar
Age : 25
Department : Manager
----------------------

Java Reflection API in Java

The java.lang.Class class provides many methods that can be used to get metadata examine
and change the run time behavior of a class. The java.lang and java.lang.reflect packages
provide classes for java reflection. Where it is used. The Reflection API is mainly used in:

IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc. Debugger
Test Tools etc.

Reflection is commonly used by programs which require the ability to examine or modify the
runtime behavior of applications running in the JVM.
Java Reflection API is used for that purpose where it makes it possible to inspect classes,
interfaces, fields and methods at runtime, without knowing their names at compile time.

And it also makes it possible to instantiate new objects, and to invoke methods using
reflection.

Source Code
//Reflection in Java

import java.lang.reflect.*;
import java.util.Arrays;

class userDetails {
private String name, city;
private int age;
public int rollno;

public userDetails()
{
name="Ram Kumar";
age=25;
city="Salem";
}
public userDetails(String name,int age,String city)
{
this.name=name;
this.age=age;
this.city=city;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getCity() {
return city;
}

public void setCity(String city) {


this.city = city;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public void display()


{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("City : "+city);
System.out.println("--------------------------");
}
private void Salary()
{
System.out.println("This is Private Salary Method");
}
}

public class ReflectionDemo {


public static void main(String[] args) {

//Class o =student.class;
System.out.println("----------------Class Details--------------");
userDetails o =new userDetails("Raja",25,"Salem");
Class c=o.getClass();
System.out.println("Class Name : "+c.getName());
System.out.println("Check its is Interface : "+c.isInterface());
System.out.println("Check its is Array : "+c.isArray());

System.out.println("---------- Constructor Details-----------");


Constructor[] constructors = c.getConstructors();
for(Constructor co : constructors) {
System.out.println("Constructor Name : " + co.getName());
System.out.println("\tConstructor Parameters ");
if(co.getParameterCount()==0){
System.out.println("\t\tNo Arg Constructor");
}else{
Parameter [] parameters=co.getParameters();
for(Parameter p : parameters) {
System.out.println("\t\t"+p.getName()+" "+p.getType());
}

}
}
System.out.println("--------------Method Details-------------");
Method[] methods=c.getMethods();
for(int i=0;i<methods.length;i++)
{
System.out.println("Method "+(i+1)+" : "+
Modifier.toString(methods[i].getModifiers()) +" "+
methods[i].getReturnType().getName()+" "+
methods[i].getName()+" - "+
Arrays.toString(methods[i].getParameters()));
}
System.out.println("--------------Declared Method Details-------------");
Method[] decmethods=c.getDeclaredMethods();
for(int i=0;i<decmethods.length;i++)
{
System.out.println("Method "+(i+1)+" : "+
Modifier.toString(decmethods[i].getModifiers()) +" "+
decmethods[i].getReturnType().getName()+" "+
decmethods[i].getName()+" - "+
Arrays.toString(decmethods[i].getParameters()));
}
System.out.println("--------------Fields Details-------------");
//Field[] fields=c.getFields(); //Public Fields
Field[] fields=c.getDeclaredFields();
for(Field f : fields) {
System.out.println(
Modifier.toString(f.getModifiers()) +" "+
f.getType().getName()+" "+
f.getName());
}
}
}

Output
javac ReflectionDemo.java
java ReflectionDemo.java

----------------Class Details--------------
Class Name : userDetails
Check its is Interface : false
Check its is Array : false
---------- Constructor Details-----------
Constructor Name : userDetails
Constructor Parameters
No Arg Constructor
Constructor Name : userDetails
Constructor Parameters
arg0 class java.lang.String
arg1 int
arg2 class java.lang.String
--------------Method Details-------------
Method 1 : public java.lang.String getName - []
Method 2 : public void setName - [java.lang.String arg0]
Method 3 : public void display - []
Method 4 : public void setAge - [int arg0]
Method 5 : public void setCity - [java.lang.String arg0]
Method 6 : public java.lang.String getCity - []
Method 7 : public int getAge - []
Method 8 : public final void wait - [long arg0, int arg1]
Method 9 : public final void wait - []
Method 10 : public final native void wait - [long arg0]
Method 11 : public boolean equals - [java.lang.Object arg0]
Method 12 : public java.lang.String toString - []
Method 13 : public native int hashCode - []
Method 14 : public final native java.lang.Class getClass - []
Method 15 : public final native void notify - []
Method 16 : public final native void notifyAll - []
--------------Declared Method Details-------------
Method 1 : public java.lang.String getName - []
Method 2 : public void setName - [java.lang.String arg0]
Method 3 : public void display - []
Method 4 : public void setAge - [int arg0]
Method 5 : public void setCity - [java.lang.String arg0]
Method 6 : private void Salary - []
Method 7 : public java.lang.String getCity - []

Calling Private Method in Java Class using Reflection API in


Java

Source Code
import java.lang.reflect.Method;

class ReflectDemo
{
private void method1()
{
System.out.println("Method-1 in Private");
}
private void method2(String name)
{
System.out.println("Method-2 in Private "+name);
}
}
public class PrivateReflectionDemo {
public static void main(String[] args) throws Exception {
ReflectDemo o =new ReflectDemo();
Class c=o.getClass();

Method m1=c.getDeclaredMethod("method1",null);
m1.setAccessible(true);
m1.invoke(o,null);//Object,parameter

Method m2=c.getDeclaredMethod("method2",String.class);
m2.setAccessible(true);
m2.invoke(o,"Tutor Joes");//Object,parameter

}
}

Output
Method-1 in Private
Method-2 in Private Tutor Joes
Java AWT (Abstract Window Toolkit)

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming.
AWT features include:

• A set of native user interface components

• A robust event-handling model

• Graphics and imaging tools, including shape, color, and font classes

• Layout managers, for flexible window layouts that do not depend on a particular

window size or screen resolution

• Data transfer classes, for cut-and-paste through the native platform clipboard

Useful Methods of Component Class

Method Used for

public void add Inserts a component on this component.

public void setSize Sets the size (width and height) of the component.

public void setLayout Defines the layout manager for the component.

public void setVisible Changes the visibility of the component, by default false.
Frame in Java AWT

The class Frame is a top level window with border and title. It uses BorderLayout as default
layout manager.

The size of the frame includes any area designated for the border. The dimensions of the
border area may be obtained using the getInsets method, however, since these dimensions
are platform-dependent, a valid insets value cannot be obtained until the frame is made
displayable by either calling pack or show.

Source Code

01_method.java

package awtDemo;

import java.awt.*;
public class app {

public static void main(String[] args) {


Frame frm =new Frame("Tutor Joes");
frm.setSize(1000,600);//w,h
frm.setLayout(null);

Button btn=new Button("Click Me");


btn.setBounds(75,75,200,50);//X,Y,W,H

frm.add(btn);
frm.setVisible(true);
}
}
Output

To download raw file Click Here

02_method.java

package awtDemo;
import java.awt.*;

public class app extends Frame


{
Button btn;
public app()
{
super("Tutor Joes");
setLayout(null);
btn=new Button("Click Me");
btn.setBounds(75,75,200,50);//X,Y,W,H
add(btn);
setSize(1000,600);
setVisible(true);
}
public static void main(String args[])
{
app frm =new app();
}
}
Output

03_method.java

package awtDemo;
import java.awt.*;
class MyApp extends Frame
{
Button btn;

public MyApp()
{
super("Tutor Joes");
setLayout(null);

btn=new Button("Click Me");


btn.setBounds(75,75,200,50);
add(btn);
setSize(1000,600);
setVisible(true);

public class app


{
public static void main(String args[])
{
MyApp frm =new MyApp();
}

To download raw file Click Here

Output

Button and ActionListener in Java AWT

The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent.

An ActionListener can be used by the implements keyword to the class definition. It can also
be used separately from the class by creating a new class that implements it. It should also
be imported to your project.

Source Code
package awtDemo;
import java.awt.*;
class MyApp extends Frame
{
Button btn;

public MyApp()
{
super("Tutor Joes");
setLayout(null);
btn=new Button("Click Me");
btn.setBounds(75,75,200,50);
add(btn);
setSize(1000,600);
setVisible(true);

public class app


{
public static void main(String args[])
{
MyApp frm =new MyApp();
}

To download raw file Click Here

Output
CheckBox in Java AWT

Checkbox control is used to turn an option on(true) or off(false). There is label for each
checkbox representing what the checkbox does.

Constructor Used for

Checkbox() checkbox with no string as the label.

Checkbox(String label) checkbox with the given label.

Checkbox(String label, boolean state) checkbox with the given label and sets t

Checkbox(String label, boolean state, CheckboxGroup group) checkbox with the given label, set the g

Checkbox(String label, CheckboxGroup group, boolean state) checkbox with the given label, in the giv

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;
//CheckBox in AWT
class MyApp extends Frame{

Label l1,l2,l3;
Checkbox c1,c2,c3;

public MyApp() {
super("Tutor Joes");
setSize(1000,600);//w,h
setLayout(null);
setVisible(true);

c1=new Checkbox("C Program");


c1.setBounds(10,50,250,30);
l1=new Label("Not Selected");
l1.setBounds(300,50,600,30);

c2=new Checkbox("C++ Program");


c2.setBounds(10,100,250,30);
l2=new Label("Not Selected");
l2.setBounds(300,100,600,30);

c3=new Checkbox("Java Program");


c3.setBounds(10,150,250,30);
l3=new Label("Not Selected");
l3.setBounds(300,150,600,30);

c1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l1.setText((e.getStateChange()==1?"checked":"unchecked"));
}
});
c2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l2.setText((e.getStateChange()==1?"checked":"unchecked"));
}
});
c3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l3.setText((e.getStateChange()==1?"checked":"unchecked"));
}
});
add(c1);
add(l1);

add(c2);
add(l2);

add(c3);
add(l3);

//Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}

public class app{


public static void main(String[] args) {
MyApp frm=new MyApp();
}

To download raw file Click Here


Output

RadioButton in Java AWT

Radio buttons provide a more user friendly environment for selecting only one option among
many. It is a special kind of checkbox that is used to select only one option.

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;
//RadioButton in AWT
class MyApp extends Frame{

Label l1,l2;
Checkbox c1, c2;
CheckboxGroup cbg;

public MyApp() {
super("Tutor Joes");
setSize(1000,600);//w,h
setLayout(null);
setVisible(true);
cbg = new CheckboxGroup();

c1 = new Checkbox("Male",cbg,false);
c1.setBounds(10, 50, 250, 30);

l1 = new Label("Not Selected");


l1.setBounds(300, 50, 600, 30);

c2 = new Checkbox("Female",cbg,false);
c2.setBounds(10, 100, 250, 30);

l2=new Label("Not Selected");


l2.setBounds(300,100,600,30);

c1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l1.setText((e.getStateChange() == 1 ? "checked"
: "unchecked"));
l2.setText("unchecked");
}
});
c2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {

l1.setText("unchecked");
l2.setText((e.getStateChange() == 1 ? "checked"
: "unchecked"));
}
});

add(c1);
add(l1);
add(c2);
add(l2);

//Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
public class app{
public static void main(String[] args) {
MyApp frm=new MyApp();
}

To download raw file Click Here

Output

TextField in Java AWT

The textField component allows the user to edit single line of text.When the user types a key
in the text field the event is sent to the TextField.

Constructor Used for

TextField() new text field component.


Constructor Used for

TextField(String text) new text field initialized with the given string text to

TextField(int columns) new textfield (empty) with given number of columns

TextField(String text, int columns) new text field with the given text and given number o

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;
//TextField in AWT
class MyApp extends Frame implements TextListener,ActionListener{

TextField txt;
Label l1,l2;

public MyApp() {
super("Tutor Joes");
setSize(1000,600);//w,h
setLayout(null);
setVisible(true);

txt=new TextField();
txt.setBounds(10, 50, 250, 30);

l1=new Label("----");
l1.setBounds(300, 50, 250, 30);
txt.addTextListener(this);
txt.addActionListener(this);

l2=new Label("----");
l2.setBounds(10, 100, 250, 30);

add(txt);
add(l1);
add(l2);

//Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

@Override
public void actionPerformed(ActionEvent e) {
l2.setText(txt.getText());

@Override
public void textValueChanged(TextEvent e) {
l1.setText(txt.getText());

}
}
public class app{
public static void main(String[] args) {
MyApp frm=new MyApp();
}

To download raw file Click Here


Output
Basic Addition Program in Java AWT

In this program, You will learn how to add two numbers using awt in Java.

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//Basic Addition Program in Java AWT


class MyApp extends Frame implements ActionListener {

Label l1, l2, l3;


TextField txt1;
TextField txt2;
Button b;

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

l1 = new Label("Enter The Value 1 : ");


l1.setBounds(10, 50, 100, 30);

txt1 = new TextField();


txt1.setBounds(150, 50, 250, 30);

l2 = new Label("Enter The Value 2 : ");


l2.setBounds(10, 100, 100, 30);

txt2 = new TextField();


txt2.setBounds(150, 100, 250, 30);

b = new Button("Click Me");


b.setBounds(150, 150, 100, 30);
b.addActionListener(this);

l3 = new Label("--");
l3.setBounds(10, 200, 300, 30);

add(l1);
add(txt1);
add(l2);
add(txt2);
add(b);
add(l3);

// Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

@Override
public void actionPerformed(ActionEvent e) {
String s1 = txt1.getText();
String s2 = txt2.getText();
if(s1.isEmpty() || s2.isEmpty()) {
l3.setText("Please Enter The data");
}else {
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = a+b;
String result = String.valueOf(c);
l3.setText("Total :"+result);
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here

Output

TextArea in Java AWT

The TextArea control in AWT provide us multiline editor area. The user can type here as much
as they wants. When the text in the text area become larger than the viewable area the scroll
bar is automatically appears which help us to scroll the text up & down and right & left.
Constructor Used for

TextArea() new and empty text area with no text in it.

TextArea (int row, int column) new text area with specified number of rows and

TextArea (String text) new text area and displays the specified text

TextArea (String text, int row, int column) new text area with the specified text in the text a

TextArea (String text, int row, int column, int scrollbars) new text area with specified text in text area and

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//TextArea in Java AWT


class MyApp extends Frame implements ActionListener {

TextArea t;
Label l;
TextField tf;
Button b;

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
l=new Label("---");
l.setBounds(20,50,250,30);

t=new TextArea(10,30);//R C
t.setBounds(20,100,300,200);

tf=new TextField(20);
tf.setBounds(20,350,300,30);

b=new Button("Click");
b.setBounds(20,400,100,30);
b.addActionListener(this);

add(l);
add(t);
add(tf);
add(b);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

@Override
public void actionPerformed(ActionEvent e) {
//l.setText(t.getSelectedText());
//t.append(tf.getText());
t.insert(tf.getText(),t.getCaretPosition());
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here

Output

Count Words and Characters in Java AWT

We can develop Word Character Counter in java with the help of string, AWT/Swing with
event handling.

Source Code
package awtDemo;
import java.awt.*;
import java.awt.event.*;

//Program to Count Words and Characters in Java AWT


class MyApp extends Frame implements ActionListener {

Label l1,l2;
TextArea t;
Button b;

public MyApp() {
super("Word & Letters Count");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

l1=new Label("-------");
l1.setBounds(20,30,200,20);

l2=new Label("-------");
l2.setBounds(20,60,200,20);

t=new TextArea(10,30);//R C
t.setBounds(20,100,300,200);

b=new Button("Get Details");


b.setBounds(20,320,100,30);
b.addActionListener(this);

add(l1);
add(l2);
add(t);
add(b);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

@Override
public void actionPerformed(ActionEvent e) {
String text = t.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here


Output

Choice in Java AWT

Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop-
up menu for the user, the user may select an item from the popup menu.

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//Choice in Java AWT


class MyApp extends Frame{

Choice c;
Button btn;
Label lbl;

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

c = new Choice();
c.setBounds(10, 50, 100, 100);

c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");

btn = new Button("Show Details");


btn.setBounds(120, 50, 100, 20);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ c.getItem(c.getSelectedIndex());
lbl.setText(data);
}
});

lbl = new Label("Empty Label");


lbl.setBounds(10, 70, 300, 30);

add(c);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here

Output
List in Java AWT

The List represents a list of text items. The list can be configured that user can choose either
one item or multiple items.

Constructor Used for

List() new scrolling list.

List(int row_num) new scrolling list initialized with the given n

List(int row_num, Boolean multipleMode) new scrolling list initialized which displays t

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//List in Java AWT


class MyApp extends Frame{

List lst;
Button btn;
Label lbl;

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
lst = new List(4, false);
lst.setBounds(10, 50, 100, 100);
lst.add("Mercury");
lst.add("Venus");
lst.add("Earth");
lst.add("Mars");
lst.add("Jupiter");
lst.add("Saturn");
lst.add("Uranus");
lst.add("Neptune");
lst.add("Pluto");

btn = new Button("Show Details");


btn.setBounds(10, 170, 100, 30);

btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String list[] = lst.getSelectedItems();

String data = "Selected Planet : ";


for (String x : list)
data += x + " , ";
lbl.setText(data);
}
});

lbl = new Label("Empty Label");


lbl.setBounds(200, 170, 300, 30);

add(lst);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here

Output
Canvas in Java AWT

The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.

Constructor Used for

Canvas() Creates a new blank canvas.

Canvas(GraphicsConfiguration c) Creates a new canvas with a specified graphics c

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//Canvas in Java AWT

class MyCanvas extends Canvas


{
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
class MyApp extends Frame{

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

add(new MyCanvas());

// Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here


Output
MenuBar,Menu,MenuItem in Java AWT

The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//Menu Bar in AWT

class MyApp extends Frame {

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

MenuBar m=new MenuBar();


Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
m.add(menu);
setMenuBar(m);

// Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here

Output
Panel in Java AWT

The class Panel is the simplest container class. It provides space in which an application can
attach any other component, including other panels. It uses FlowLayout as default layout
manager.

Source Code
package awtDemo;

import java.awt.*;
import java.awt.event.*;

//Panel in AWT
class MyApp extends Frame {

public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);

Panel panel=new Panel();


panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);

Button b1=new Button("Button 1");


b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);

Button b2=new Button("Button 2");


b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);
panel.add(b2);

add(panel);

// Close Button Code


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public class app {


public static void main(String[] args) {
MyApp frm = new MyApp();
}

To download raw file Click Here


Output

You might also like