Apollo Java
Apollo Java
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
• Web Applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games, etc.
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
• 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
• 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
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
Step 3:Choose the JDK for your operating system.Click -> Download the "exe" installer
Step 4:Click -> "Accept License Agreement"
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
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.
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
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
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:
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 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.
• 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
• byte -> short -> char -> int -> long -> float -> double
• 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
• 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
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.
operands.
operands.
4. Division(/): This is a binary operator that is used to divide the first operand(dividend)
5. Modulus(%): This is a binary operator that is used to return the remainder when the
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
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.
-= 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 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
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 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
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
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 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.
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 XOR
~ Bitwise complement
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
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;
}
}
/*
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;
Output
Enter Your Age :
23
You are Eligible For Vote...
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;
}
}
Output
Enter Year :
1900
Year 1900 is a leap year
Enter Year :
2022
Year 2022 is not a leap year
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
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;
}
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
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.
• Case: This is the value that is evaluated for equivalence with the argument to the
switch statement.
evaluate to true.
• Abrupt completion of the case statement; usually break: This is required to prevent
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;
Output
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter Your Choice :
3
Enter 2 Nos :
12
8
Multiplication : 96
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
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.
Syntax:
while(Condition)
{
// body of loop;
// Increment (or) Decrement;
}
Source Code
import java.util.Scanner;
1
2
3
4
5
6
7
8
9
10
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 condition check to true, the body of the loop inside the do statement is executed
again.
Syntax:
do
{
// body of loop;
// Increment (or) Decrement;
} while(Condition) ;
Source Code
import java.util.Scanner;
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;
Output
Enter The Limit :
10
1
2
3
4
5
6
7
8
9
10
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;
}
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
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[]) {
Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
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;
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
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
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
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
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;
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
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
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
Source Code
import java.util.Scanner;
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;
}
}
Output
Enter The Number : 17
17 is a Prime Number
Enter The Number : 10
10 is not a Prime Number
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
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
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).
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]);
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
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;
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
Source Code
import java.util.Arrays;
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]
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};
}
}
Output
Duplicate Element : 2
Duplicate Element : 5
Duplicate Element : 6
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
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
}
}
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.
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
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:
Methods:
• public synchronized StringBuffer replace ( int startIndex, int endIndex, String str )
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
}
}
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
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
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
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
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(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);
}
}
}
}
}
Output
Original String : tuTor joes coMputer education
Capitalized Each Word String : Tutor Joes Computer Education
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);
Output
Original String : Tutor Joes Computer Education
tOGGLE cASE wORD Output : tUTOR jOES cOMPUTER eDUCATION
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:
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
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:
Syntax:
Access_ specifier Return_type Method_name ( Parameter list )
{
// body of method ;
}
Access specifier :
package
Return type :
Parameter list :
Method body :
Source Code
class Methods {
//No Return W/o args
public void add() {
int a = 123;
int b = 10;
System.out.println("Addition : " + (a + b));
}
//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;
* */
Output
Addition : 133
Subtraction : 113
Muli : 1230
Division : 12.0
Source Code
import java.util.Arrays;
import java.util.Scanner;
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
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
Source Code
import java.util.Scanner;
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
• Object - Any entity that has state and behaviour is known as an object.
• Inheritance - When one object acquires all the properties and behaviours of a parent
polymorphism.
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.
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;
}
}
Output
Area of Rectangle : 200
Area of Rectangle : 600
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;
}
}
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 can only take the modifiers public, private, and protected, and cannot be
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;
}
}
}
}
Output
Constructor Called
Area of Rectangle : 20
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() );
Output
Area : 10.0
Area : 18.0
Area : 9.0
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
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
---------------------------------
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
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.");
}
}
Output
Have Own Audi Car.
Have Own 2BHK House.
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..");
}
}
Output
Own Audi Car..
3 BHK House.
5 Arcs of Land..
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);
}
}
}
}
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 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
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
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
//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..");
}
}
Output
Draw Rectangle Using Length & Breadth..
Message From Shape
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");
}
}
@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[]) {
}
}
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..
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
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();
}
@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");
}
}
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;
@Override
public void fun2() {
System.out.println("Fun-2");
}
@Override
public void fun4() {
System.out.println("Fun-4");
}
}
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.
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
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
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");
}
}
Source Code
//Anonymous Inner Class
class outerDemo {
public void outerDisplay() {
testDemo o =new testDemo() {
@Override
public void display() {
System.out.println("Test Display");
}
};
o.display();
}
}
Output
Test Display
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);
}
}
}
Output
X : 10
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
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.
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
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");
}
}
Output
I am Sub Display
I am Super Final Display
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");
}
}
}
}
Output
I am Display
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");
}
}
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);
//Enum by loop
for (GameLevel level : GameLevel.values()) {
System.out.println(level);
}
}
}
Output
HIGH
High level
LOW
MEDIUM
HIGH
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());
}
}
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
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);
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
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.
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
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
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
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
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();
}
}
*/
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
----------------------
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 class objectCloningDeepDemo {
public static void main(String[] args) throws CloneNotSupportedException {
}
}
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
----------------------
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;
}
//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("--------------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 - []
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:
• Graphics and imaging tools, including shape, color, and font classes
• Layout managers, for flexible window layouts that do not depend on a particular
• Data transfer classes, for cut-and-paste through the native platform clipboard
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 {
frm.add(btn);
frm.setVisible(true);
}
}
Output
02_method.java
package awtDemo;
import java.awt.*;
03_method.java
package awtDemo;
import java.awt.*;
class MyApp extends Frame
{
Button btn;
public MyApp()
{
super("Tutor Joes");
setLayout(null);
Output
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);
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.
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.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);
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);
c2 = new Checkbox("Female",cbg,false);
c2.setBounds(10, 100, 250, 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);
Output
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.
TextField(String text) new text field initialized with the given string text to
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);
@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();
}
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.*;
public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
l3 = new Label("--");
l3.setBounds(10, 200, 300, 30);
add(l1);
add(txt1);
add(l2);
add(txt2);
add(b);
add(l3);
@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);
}
Output
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 (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 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());
}
Output
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.*;
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);
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());
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 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");
add(c);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
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.
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 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.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(lst);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
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.
Source Code
package awtDemo;
import java.awt.*;
import java.awt.event.*;
public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
add(new MyCanvas());
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.*;
public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
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);
add(panel);