You are on page 1of 42

/* Linear search */ And

/*Finding maximum and minimum element in an array*/

import java.io.*;
import java.util.*;

public class sorting {

public static void main(String[] args) {


//To sort the elements in the array and to find max and min elements
using linear search
int array[]={2,3,1,6,4};
int temp,i,j;
for(i=0;i<array.length;i++)
{
for(j=0;j<array.length;j++)
{
if(array[i]<array[j])
{
temp=array[i];//code for sorting element and elements
in array will be 1 2 3 4 6
array[i]=array[j];
array[j]=temp;
}
}
}
System.out.println("The minimum element is:"+array[0]);
System.out.println("The maximum element is:"+array[array.length-1]);
}

Output:-

The minimum element is:1


The maximum element is:6

===================================================================================
=============================================================
/*consider a method with two strings parameters as arguments and concat them
overload the same method with 3 string arguments and concat them*/

import java.io.*;
public class ofum {

public void add(String s1,String s2)


{
String s3=s1.concat(s2);
System.out.println(s3);
}
public void add(String s1,String s2,String s3)
{
String s4=s1.concat(s2);
String s5=s4.concat(s3);
System.out.println(s5);
}
public static void main(String[] args)
{
ofum d=new ofum();
d.add("hi","Lekha");
d.add("dumbuu", "is", "back");
}

output:-

hiLekha
dumbuuisback

===================================================================================
==============================================================
/*Fibonacii Series */
/* write a program to display number in 0 1 1 2 3 5 8.....pattern*/

public class fib {

public static void main(String[] args)


{
int f=0,f1=1,temp,f3;
System.out.println("Fibonacii Series");
System.out.println(f);
System.out.println(f1);
for(int i=0;i<8;i++)
{
f3=f+f1;
f=f1;
f1=f3;
System.out.println(f3);
}
}

output:-

Fibonacii Series
0
1
1
2
3
5
8
13
21
34

===================================================================================
===============================================================
/*Library fine*/
/*if the date between issue date and return date is >10 means fine is 1 rupee per
day if >20 fine is ruppes 2 else fine is 3 and cancel memner ship*/

import java.util.Scanner;

public class library {

public static void main(String[] args) {


int fine;
int days;
Scanner br=new Scanner(System.in);
System.out.println("Enter the number of days between issuedate and
return date");
days=br.nextInt();
if(days>10&&days<20)
{
fine=1*days;
System.out.println("Fine amount is :"+fine);
}
else if(days>20&&days<30)
{
fine=2*days;
System.out.println("Fine amount is :"+fine);
}
else if(days>30)
{
fine=3*days;
System.out.println("Fine amount is : "+fine);
System.out.println("Membership cancelled");
}
else
{
System.out.println("No fine is imposed");
}

output:-

Enter the number of days between issuedate and return date


45
Fine amount is : 135
Membership cancelled
===================================================================================
====================================================================

/*passing a string as parameter and finding the number of vowels in it*/

public class vowels


{
public int count=0;
public void check(String s)
{
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||
s.charAt(i)=='o'||s.charAt(i)=='u'||
s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||
s.charAt(i)=='O'||s.charAt(i)=='U')
{
count++;
}
}

System.out.println("The given String is:"+s);


System.out.println("Number of vowels are:"+count);
}

public static void main(String[] args)

{
vowels v=new vowels();
v.check("Lekha");

Output:-

The given String is:Lekha


Number of vowels are:2
===================================================================================
========================================================================
/*Accept age of the person and throw error if it is >100*/

import java.util.Scanner;

public class age {

public static void main(String[] args) {


int age;
Scanner br=new Scanner(System.in);
System.out.println("Enter age");
age=br.nextInt();
try
{
if(age>0&&age<100)
{
System.out.println("Entered age is"+age);
}
else
{
throw new illegalage("Invalid age");
}
}
catch(Exception e)
{
System.out.println("Exception is"+e);
}
}

//another class for considering message

public class illegalage extends Exception


{
public illegalage(String msg)
{
super(msg);
}
}

Output:-

Enter age
198
Exception isillegalage: Invalid age

===================================================================================
===============================================================
/*Exception handling*/

public class exceptionhandling


{
public void div(int x,int y)
{
try
{
int z=x/y;
System.out.println("The divident is"+z);
}
catch(Exception e)
{
System.out.println("The exception is:"+e);
}
}

public static void main(String[] args)


{
exceptionhandling r=new exceptionhandling();
r.div(10, 0);

}
output:-
The exception is:java.lang.ArithmeticException: / by zero
===================================================================================
=====================================================================

/*password validating it should have 15-60 characters and do not contain spaces*/

public class passwords {


int count=0;
public void check(String s)
{
if(s.length()>15&&s.length()<60)
{
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=' ')
{
count=1;
}

}
}
else
{
System.out.println("Invalid pswd");
}
if(count==1)
System.out.println("Password is valid and pswd is "+s);

}
public static void main(String[] args)
{
passwords p=new passwords();
p.check("hellolekunanabngaru");
}

Output:

Password is valid and pswd is hellolekunanabngaru

===================================================================================
================================================================

/*password should be between 1-60 characteres and shouls not contain * , . ,$*/

public class passwords {


int count=0;
public void check(String s)
{
if(s.length()>15&&s.length()<60)
{
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='*'||s.charAt(i)=='$'||s.charAt(i)=='.')
{
count=0;
}

}
}
else
{
System.out.println("Invalid pswd");
}
if(count==0)
System.out.println("Password is invalid and pswd is "+s);
else
System.out.println("password is valid");

}
public static void main(String[] args)
{
passwords p=new passwords();
p.check("hellolekunanabngaru$");
}

Output:-

Password is invalid and pswd is hellolekunanabngaru$

===================================================================================
=============================================================

/*Taxi softwre if taxi is late by 15 min amount is 50% should be paid else late by
30 min amount should be paid is 40% .if late by 60 min free ride*/

import java.util.Scanner;

public class taxi {

public static void main(String[] args)


{
double fare=1000;
int timelateinmin = 0;
Scanner br=new Scanner(System.in);
System.out.println("Enter time late in minutes");
timelateinmin=br.nextInt();
if(timelateinmin>15&&timelateinmin<=30)
{
fare=fare*50/100;
System.out.println("Amount that should be paid is "+fare);
}
else if(timelateinmin>30&&timelateinmin<=60)
{
fare=fare*40/100;
System.out.println("Amount that should be paid is "+fare);

}
else
{
System.out.println("Free journey");
}
}

Output:-

Enter time late in minutes


54
Amount that should be paid is 400.0
===================================================================================
==================================================================

Polymporphism means the behaviour of an object will be different at different


instance of time

or

Polymorphism in java is a concept by which we can perform a single action by


different ways. Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism.
We can perform polymorphism in java by method overloading and method overriding.

/*Run time polymorphism means


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass.
The determination of the method to be called is based on the object being referred
to by the reference variable.

In simple run time polymorphism (METHOD OVERRIDING)


-------------------

class Bike
{
void run()
{
System.out.println("running");
}
}
class Splender extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
public static void main(String args[]){
Splender b = new Splender();//Overriding
b.run();
}
}

OutPut:-

running safely with 60km


===================================================================================
===============================================================
compile time polymorphism(method overloading)
----------------------------------------------

public class overloading


{
public void add(int a)
{
int c=a;
System.out.println("Element is" +c);
}
public void add(int a,int b)
{
int c=a+b;
System.out.println("sum is :"+c);
}

public static void main(String[] args)


{
overloading u=new overloading();
u.add(10);
u.add(10,20);
}

Output:-
Element is10
sum is :30

===================================================================================
================================================================

/*write a program having static add method to add two numbers*/

public class staticex {

public static void add(int x,int y)


---------
{
int z=x+y;
System.out.println("Sum is "+z);
}
public static void main(String[] args)
{
add(10,20);//static method do not require objects to create
}

Output:-

Sum is 30

===================================================================================
=================================================================

/*Write a method that accepts String as argument and returns array of words*/

public class arraywords


{
public void check(String s)
{
String array[]=s.split(" ");
System.out.println("The number of words are : "+array.length);
for(int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}
}
public static void main(String[] args)
{
arraywords a=new arraywords();
a.check("Lekha is my sweet heart");
}

Output:-

The number of words are : 5


Lekha
is
my
sweet
heart

===================================================================================
==================================================================

/*write a method that accepts string as argument and return second word and its
length*/
public class arraywords
{
public void check(String s)
{
String array[]=s.split(" ");
System.out.println("The number of words are : "+array.length);
System.out.println("The second word is :"+array[1]);
System.out.println("The length of the second word
is:"+array[1].length());
}
public static void main(String[] args)
{
arraywords a=new arraywords();
a.check("Lekha is my sweet heart");
}

Output:-

The number of words are : 5


The second word is :is
The length of the second word is:2

===================================================================================
=====================================================================

/*consider an array and display its nth element*/

public class nth {

public static void main(String[] args)


{
int array[]={1,2,3,4,56,7,8,4,6,75,8,5776,6878};
System.out.println("The last element in the array
is"+array[array.length-1]);
}

Output:-

The last element in the array is6878

===================================================================================
=====================================================================

/*passport should be mandatory and avg should be >60*/

import java.util.Scanner;

public class passport


{
String passport;
double ssc,inter,btech;
public void check()
{
Scanner br=new Scanner(System.in);
System.out.println("if passport enter yes else no");
passport=br.next();
System.out.println("Enter ssc percentage");
ssc=br.nextDouble();
System.out.println("Enter inter percentage");
inter=br.nextDouble();
System.out.println("Enter btech percentage");
btech=br.nextDouble();
if(passport.equalsIgnoreCase("yes")&&ssc>60&&inter>60&&btech>60)
{
System.out.println("Eligible to fly");
}
else
{
System.out.println("Not eligible");
}
}

public static void main(String[] args)


{
passport p=new passport();
p.check();
}

Output:-
if passport enter yes else no
yes
Enter ssc percentage
67
Enter inter percentage
87
Enter btech percentage
89
Eligible to fly

===================================================================================
===================================================================

/*Converting a string from caps to small and small to caps*/

public class egup


{

public static void main(String[] args)


{
String s="Hello";
String s1=s.toUpperCase();
System.out.println("Uppercase "+s1);
String s2=s.toLowerCase();
System.out.println("Lowercase "+s2);
}
}

Output:-

Uppercase HELLO
Lowercase hello

===================================================================================
===================================================================

/*get a string from the user and return the third character from it using method*/

public class thirdchr


{
public void check(String s)
{
for(int i=0;i<s.length();i++)
{
if(i==2)
{
String s1=s.substring(2,3);
System.out.println("The third char is:"+s1);
}
}
}

public static void main(String[] args)


{
thirdchr t=new thirdchr();
t.check("World");
}

Output:-

the third char is: r

===================================================================================
======================================================================

/*Number of days between two days*/

import java.util.Calendar;

public class isss {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long todayMilli;
long dateMilli;
long diff;

Calendar today =Calendar.getInstance();


// System.out.println(today);
Calendar date = Calendar.getInstance();
date.set(Calendar.DATE, 20);
date.set(Calendar.MONTH, 1);
date.set(Calendar.YEAR, 2015);
// System.out.println(date);
todayMilli=today.getTimeInMillis();
dateMilli=date.getTimeInMillis();
diff= (todayMilli-dateMilli)/(1000*60*60*24);

System.out.println("Difference between 2 given dates is :" +diff+"


days");

Output:-

Difference between 2 given dates is :10 days

===================================================================================
=====================================================================
/*Encapsulating a variable and performing it in function....some thing like
that...*/

public class encapsulating


{
private double accountNo;
private String accountHolderName;
private double balance;

public double getAccountNo() {


return accountNo;
}
public void setAccountNo(double accountNo) {
this.accountNo = accountNo;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public static void main(String x[])
{
encapsulating e1=new encapsulating();
e1.setAccountHolderName("Lekha");
e1.setAccountNo(31544);
e1.setBalance(100000);
System.out.println("The account holder name is :
"+e1.getAccountHolderName());
System.out.println("The account number is:"+e1.getAccountNo());
System.out.println("The balance is:"+e1.balance);
}
}

OutPut:-

The account holder name is : Lekha


The account number is:31544.0
The balance is:100000.0

===================================================================================
===================================================================

/*Enum example*/

class EnumExample1{

public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);

}}

output:-
WINTER
SPRING
SUMMER
FALL

===================================================================================
==================================================================

/*reversing a string and displaying it*/

import java.util.*;

class stringrev
{
public static void main(String args[])
{
String original, reverse = "";
Scanner br = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = br.nextLine();

int length = original.length();

for ( int i = length - 1 ; i >= 0 ; i-- )


reverse = reverse + original.charAt(i);

System.out.println("Reverse of entered string is: "+reverse);


}
}

output:-
Enter a string to reverse
lekha
Reverse of entered string is: ahkel
===================================================================================
======================================================================

/*Sum of array of elements*/

public class sum


{

public static void main(String[] args)


{
int sumarray[]={1,2,3,4,5};
int sumofarray=0;
for(int i=0;i<sumarray.length;i++)
{
sumofarray=sumofarray+sumarray[i];
}
System.out.println("Sum of elements in the array is:"+sumofarray);
}

output:

Sum of elements in the array is:15


===================================================================================
========================================================================

/*Evaluate the employee based on the performance during training,behaviour and


punctuality if he is good in all threer make him permanent*/

import java.util.Scanner;

public class employee


{

public static void main(String[] args)


{
String trainingPerformance;
String behaviour;
String punctuality;
Scanner br=new Scanner(System.in);
System.out.println("Training performance good/bad:?");
trainingPerformance=br.next();
System.out.println("Behaviour good/bad:?");
behaviour=br.next();
System.out.println("Punctuality good/bad:?");
punctuality=br.next();

if(trainingPerformance.equalsIgnoreCase("good")&&punctuality.equalsIgnoreCase("good
")
&&behaviour.equalsIgnoreCase("good"))
{
System.out.println("Employee made permanent");
}
else
{
System.out.println("Temp employee");
}

Output:

Training performance good/bad:?


Good
Behaviour good/bad:?
good
Punctuality good/bad:?
good
Employee made permanent
===================================================================================
=======================================================================

/*elements that are divisible by 3 */

public class arrayby3 {

public static void main(String[] args) {


int a[]={23,24,33,36,56};
int array[] ={0,0,0};
int j=0;
int count=0;
for(int i=0;i<a.length;i++)
{

if(a[i]%3==0)
{
array[j]=a[i];
j++;
count++;
}
}
if(count!=0)
{
System.out.println("The elements that are divisible by 3 are:");
for(int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}
}
else
{
System.out.println("No elements");
}

}
Output:
The elements that are divisible by 3 are:
24
33
36

===================================================================================
============================================================================
/*Finding maximum of three numbes without using and operator*/

import java.util.Scanner;

public class Largest_Ternary

public static void main(String[] args)

int a, b, c, d;

Scanner s = new Scanner(System.in);

System.out.println("Enter all three numbers:");

a = s.nextInt();

b = s.nextInt();

c = s.nextInt();

d = c > (a > b ? a : b) ? c : ((a > b) ? a : b);

System.out.println("Largest Number:"+d);

Output:
Enter all three numbers:
5
6
7
Largest Number:7
===================================================================================
============================================================================
/*Find the sum of diagonal elements in an array*/

import java.util.Scanner;

public class diagonal


{

public static void main(String[] args)


{
int array[][] = new int[2][2];
int sum=0,i,j;;
Scanner br=new Scanner(System.in);
System.out.println("Enter values into the array");
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
int number=br.nextInt();
array[i][j]=number;
if(i==j)
{
sum=sum+array[i][j];
}
}

}
System.out.println("Sum of diagonal element is: "+sum);

output:-
Enter values into the array
2
3
4
5
Sum of diagonal element is: 7

===================================================================================
=====================================================================

/*Interface example*/
--------------
public interface BasketballTeam
{
public void printBasketballName();
}

-----------
public interface FootballTeam
{
public void printFootballName();
}
-----------------

public class Team implements BasketballTeam, FootballTeam {


private String name = null;

@Override
public void printFootballName() {
System.out.println("Football Team: \"" + name + " F.C.\"");
}

@Override
public void printBasketballName() {
System.out.println("Basketball Team: \"" + name + " B.C.\"");
}

public static void main(String[] args) {


Team t = new Team();
t.printBasketballName();
t.printFootballName();
}
}
===================================================================================
====================================================================

/*Inheritance example*/

class Employee
{
float salary=40000;
}
------------
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Output:-
Programmer salary is:40000.0
Bonus of programmer is:10000
===================================================================================
==================================================================
/*password check with it should not contain special char like @ % #
and should not end with .*/

public class passwords {


int count=0;
public void check(String s)
{
if(s.length()>15&&s.length()<60)
{
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)=='@'||s.charAt(i)=='%'||s.charAt(i)=='#')
&&s.charAt(s.length()-1)!='.')
{
count=1;
}

}
}
else
{
System.out.println("Invalid pswd");
}
if(count==1)
System.out.println("Password is invalid and pswd is "+s);
else
System.out.println("password is valid");

}
public static void main(String[] args)
{
passwords p=new passwords();
p.check("hellolekunanabngaru$");
}

Output:-

password is valid
===================================================================================
==================================================================
/*read a sentence and that should have 10 characters
should have space and should not contain .symbol
*/

public class passwords {


int count=0;
public void check(String s)
{
if(s.length()==10)
{
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)!='.'))
{
if(s.charAt(i)==' ')
{
count=1;
}
}

}
}
else
{
System.out.println("Invalid sting");
}
if(count==0)
System.out.println("string is invalid and string is "+s);
else
System.out.println("string is valid");

}
public static void main(String[] args)
{
passwords p=new passwords();
p.check("good morin");
}

Output:

string is valid

===================================================================================
=========================================================================
/*admission for child if age>3 and parents educated and income>2lks*/

import java.util.Scanner;

public class admission {

public static void main(String[] args) {


Scanner br=new Scanner(System.in);
System.out.println("Enter age of child");
int age=br.nextInt();
System.out.println("Educational status of parents educated/not");
String status=br.next();
System.out.println("Income of parents");
double income=br.nextDouble();
if(age>3&&status.equalsIgnoreCase("educated")&&income>200000)
{
System.out.println("Admission given to the child");
}
else
{
System.out.println("Admission rejected");
}
}

}
Output:-
Enter age of child
4
Educational status of parents educated/not
educated
Income of parents
500000
Admission given to the child
===================================================================================
=====================================================================
/*calculate the discount price according to the bill amount if bill amount is >5000
10% discount
>10000 means 20%discount >20000 means 30% discount*/
import java.util.Scanner;

public class discount


{

public static void main(String[] args)


{
System.out.println("Enter bill amount");
Scanner br=new Scanner(System.in);
double bill=br.nextDouble();
if(bill>5000&&bill<=10000)
bill=bill-(bill*10)/100;
else if(bill>10000&&bill<=20000)
bill=bill-(bill*20)/100;
else
bill=bill-(bill*30)/100;
System.out.println("Bill amount is:"+bill);
}

}
Output:-
Enter bill amount
20000
Bill amount is:16000.0
===================================================================================
=======================================================================

/*print the series in 1 2 2 4 8 32.....*/

public class number


{
public static void main(String[] args)
{
int f=1,f1=2,f3;
System.out.println(f);
System.out.println(f1);
for(int i=1;i<6;i++)
{
f3=f1*f;
System.out.println(f3);
f=f1;
f1=f3;

}
}

0utput:-
1
2
2
4
8
32
256
===================================================================================
====================================================================
/*email id validation @cant be at first place and @will be only once and length
should be 10-30*/

public class EmailValidator


{
public boolean emailvalidate(String s)
{

if(s.length()>10&&s.length()<=30)
{
if(s.matches("[a-zA-Z0-9\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}"))
{
return true;
}
else
{
return false;
}
}
return false;
}
public static void main(String d[])
{
EmailValidator e=new EmailValidator();
boolean b=e.emailvalidate("chaithanyacsit@gmail.com");
if(b)
{
System.out.println("valid email");
}
else
{
System.out.println("Invalid email");
}
}
}

Output:-
valid email
===================================================================================
=====================================================================
/*sort a array of elements by using template function*/ same type of cose for all
template codes

import java.util.*;
public class Details
{

public static void main(String args[])


{
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");

/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries)
{
System.out.println(counter);
}

/* Sort statement*/
Collections.sort(listofcountries);

/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries)
{
System.out.println(counter);
}
}
}
Output:-

Before Sorting:
India
US
China
Denmark

After Sorting:
China
Denmark
India
US

OR
-----
import java.util.*;
public class ArrayListOfInteger
{

public static void main(String args[])


{
ArrayList<Integer> arraylist = new ArrayList<Integer>();
arraylist.add(11);
arraylist.add(2);
arraylist.add(7);
arraylist.add(3);

/* ArrayList before the sorting*/


System.out.println("Before Sorting:");
for(int counter: arraylist)
{
System.out.println(counter);
}
/* Sorting of arraylist using Collections.sort*/
Collections.sort(arraylist);

/* ArrayList after sorting*/


System.out.println("After Sorting:");
for(int counter: arraylist)
{
System.out.println(counter);
}
}
}

Output:-

Before Sorting:
11
2
7
3
After Sorting:
2
3
7
11

===================================================================================
=====================================================================

/* +,-, *, / perform all methods by using abstractclass/interface */ or any


interface example will be on same concept

public interface operations


{
public void add(int x,int y);
public void sub(int x,int y);
public void mul(int x,int y);
public void div(int x,int y);
}

---
public class interfaceeg implements operations
{

public void add(int x, int y)


{
int z=x+y;
System.out.println("sum"+z);
}

public void div(int x, int y)


{
int z=x/y;
System.out.println("div"+z);
}
public void mul(int x, int y)
{
int z=x*y;
System.out.println("mul"+z);
}

public void sub(int x, int y)


{
int z=x-y;
System.out.println("sub"+z);
}
public static void main(String[] args)
{
interfaceeg w=new interfaceeg();
w.add(10, 20);
w.sub(20, 10);
w.mul(2, 3);
w.div(10, 2);
}

Output:
sum30
sub10
mul6
div5
===================================================================================
===========================================================

/* how can we call a static method in main method*/

public class staticeg


{
public static void add(int x,int y)
{
int z=x+y;
System.out.println("Sum is"+z);
}

public static void main(String[] args)


{
add(10,20);
}

output:-
Sum is30
===================================================================================
==========================================================
/*how to access static in an int method*/

public class staticex


{
public static int add(int x,int y)
{
int z=x+y;
return z;
}
public static void main(String[] args)
{
int q=add(10,20);//static method do not require objects to create
System.out.println("The sum is "+q);
}

Output:-
The sum is 30
===================================================================================
===============================================================
/*count of an odd number in an array list*/

public class oddarray


{

public static void main(String[] args)


{
int array[]={1,2,3,4,5};
int count=0;
for(int i=0;i<array.length;i++)
{
if(array[i]%2!=0)
{
++count;
}
}
System.out.println("Number of odd elements is"+count);
}

Output:-

Number of odd elements is3


===================================================================================
===============================================================
/* find the length of the string with space and override the same function without
space*/

class strng
{
public void space(String s)
{
String i=s.replaceAll(" ", "");
System.out.println("The length of the string without
spaces :"+i.length());
}
}
public class stringoverride extends strng
{

public void space(String s)


{
System.out.println("The length of the string with spaces :
"+s.length());
}
public static void main(String[] args)
{
stringoverride e=new stringoverride();
e.space("leku is good girl");
strng t=new strng();
t.space("leku is good girl");

}
Output:-

The length of the string with spaces : 17


The length of the string without spaces :14
===================================================================================
==================================================================
/*count of an even number in an array*/
public class evenarray
{

public static void main(String[] args)


{
int array[]={1,2,3,4,5};
int count=0;
for(int i=0;i<array.length;i++)
{
if(array[i]%2==0)
{
++count;
}
}
System.out.println("Number of even elements is"+count);
}

Output:-

Number of even elements is2


===================================================================================
=====================================================================
/*consider an array split into even and odd arrays*/

public class oddarray


{

public static void main(String[] args)


{
int array[]={1,2,3,4,5},earray[]=new int[5],oarray[]=new int[5];
int ocount=0,ecount=0;
for(int i=0;i<array.length;i++)
{
if(array[i]%2!=0)
{
oarray[ocount]=array[i];
++ocount;
}
else
{
earray[ecount]=array[i];
++ecount;
}
}

System.out.println("Odd elements");
for(int i=0;i<ocount;i++)
{
System.out.println(oarray[i]);

}
System.out.println("Total number of odd elements:"+ocount);

System.out.println("even elements");
for(int i=0;i<ecount;i++)
{
System.out.println(earray[i]);

}
System.out.println("Total number of even elements:"+ecount);
}

}
output:-

Odd elements
1
3
5
Total number of odd elements:3
even elements
2
4
Total number of even elements:2
===================================================================================
===============================================================
/*sum of individual elements in an array and reversing it*/

public class reversearray


{

public static void main(String[] args)


{
int array[]={23,43,433};
int digit,sum = 0,dsum=0;
for(int i=0;i<3;i++)
{
int number=array[i];
sum=0;
dsum=0;
while(number>0)
{

digit=number%10;
dsum=dsum+digit;
sum=(sum*10)+digit;
number=number/10;
}
System.out.println("The reversed element is:"+sum);
System.out.println("The sum of element is"+dsum);
}

Output:
The reversed element is:32
The sum of element is5
The reversed element is:34
The sum of element is7
The reversed element is:334
The sum of element is10
===================================================================================
================================================================

/*leap year*/

public class leapyear


{

public static void main(String[] args)


{
int array[]={2000,1990,2002,1996,2012};
int larray[]=new int[5];
int j=0;
for(int i=0;i<array.length;i++)
{
if((array[i]%4==0 && array[i]%100!=0) || array[i]%400==0)//year
should be divisible by 4 and not divide by 100
or year should be
divided by 400;
{
larray[j]=array[i];
j++;
}
}
System.out.println("leap years are:");
for(int i=0;i<j;i++)
{
System.out.println(larray[i]);
}
}

}
Output:-
leap years are:
2000
1996
2012
===================================================================================
==================================================================

/*using abstract/interface methods implement getreverse,getlength,getconcat


methods*/

public interface methods


{
void getConcat(String s1,String s2);
void getReverse(String s);
void getLength(String s);
}
-----

public class coint implements methods


{
public void getConcat(String s1, String s2)
{
String s3=s1.concat(s2);
System.out.println("The concatenated string is"+s3);

public void getLength(String s)


{
int length=s.length();
System.out.println("The length is"+length);

public void getReverse(String s)


{
String reverse ="";
int length = s.length();

for ( int i = length - 1 ; i >= 0 ; i-- )


reverse = reverse + s.charAt(i);

System.out.println("Reverse of entered string is: "+reverse);

public static void main(String[] args)


{
coint y=new coint();
y.getConcat("Hello", "Lekha");
y.getLength("Dumbuu");
y.getReverse("Pandi");
}

}
Output:-

The concatenated string isHelloLekha


The length is6
Reverse of entered string is: idnaP
===================================================================================
==================================================================

or we can use abstact we can do in the following way

public abstract class methodss


{
abstract void getConcat(String s1,String s2);
abstract void getReverse(String s);
abstract void getLength(String s);
}
----------------------------------------

public class coint extends methodss


{
public void getConcat(String s1, String s2)
{
String s3=s1.concat(s2);
System.out.println("The concatenated string is"+s3);

public void getLength(String s)


{
int length=s.length();
System.out.println("The length is"+length);

public void getReverse(String s)


{
String reverse ="";
int length = s.length();

for ( int i = length - 1 ; i >= 0 ; i-- )


reverse = reverse + s.charAt(i);

System.out.println("Reverse of entered string is: "+reverse);

public static void main(String[] args)


{
coint y=new coint();
y.getConcat("Hello", "Lekha");
y.getLength("Dumbuu");
y.getReverse("Pandi");
}

Output:-

The concatenated string isHelloLekha


The length is6
Reverse of entered string is: idnaP
===================================================================================
====================================================================

/* sum of diagonal elements in the array*/

import java.util.Scanner;

public class diagonal


{

public static void main(String[] args)


{
int array[][] = new int[2][2];
int sum=0,i,j;;
Scanner br=new Scanner(System.in);
System.out.println("Enter values into the array");
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
int number=br.nextInt();
array[i][j]=number;
if(i==j)
{
sum=sum+array[i][j];
}
}

}
System.out.println("Sum of diagonal element is: "+sum);

Output:-
Enter values into the array
1
2
3
1
Sum of diagonal element is: 2
===================================================================================
==============================================================
/*check whether diagonal elements are same are not */
import java.util.Scanner;

public class diagonal


{

public static void main(String[] args)


{
int array[][] = new int[2][2];
int sum=0,i,j,n=0,count = 0;
int value[]=new int[2];
Scanner br=new Scanner(System.in);
System.out.println("Enter values into the array");
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
int number=br.nextInt();
array[i][j]=number;

}
for(int k=0;k<2;k++)
{
for(int m=0;m<2;m++)
{
if(k==m)
{
value[n]=array[k][m];
n++;
}
}
}

if(value[0]==value[1])
{
count=1;
}
else
{
count=0;
}

if(count==1)
{
System.out.println("Diagonal elements are same");
}
else
{
System.out.println("Not same");
}
}

}
Output:-
Enter values into the array
1
2
3
1
Diagonal elements are same
===================================================================================
============================================================
/* return sum of array elements using function*/

public class sum


{
public int sumint()
{
int sumarray[]={1,2,3,4,5};
int sumofarray=0;
for(int i=0;i<sumarray.length;i++)
{
sumofarray=sumofarray+sumarray[i];
}
return sumofarray;
}
public static void main(String[] args)
{
sum s=new sum();
int z=s.sumint();
System.out.println("Sum of array elements is :"+z);

}
OutPut:-
Sum of array elements is :15
===================================================================================
=======
======================================================

/* sum of array elements without function*/

public class sum


{

public static void main(String[] args)


{
int sumarray[]={1,2,3,4,5};
int sumofarray=0;
for(int i=0;i<sumarray.length;i++)
{
sumofarray=sumofarray+sumarray[i];
}
System.out.println("Sum of elements in the array is:"+sumofarray);
}

Output:-
Sum of array elements is :15
===================================================================================
================================================================

/* Enter a key value and replace it*/

import java.util.Scanner;

public class keyreplace


{

public static void main(String[] args)


{
int array[]={3,4,65,43};
int count=0;
Scanner br=new Scanner(System.in);
System.out.println("Enter the key value and replace it by 66 if
found");
int key=br.nextInt();
for(int i=0;i<array.length;i++)
{
if(array[i]==key)
{
array[i]=66;
count=1;
break;
}
}
if(count==1)
{
System.out.println("Value replaced");
}
else
{
System.out.println("Key value not found");
}
for(int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}

}
Output:-

Enter the key value and replace it by 66 if found


4
Value replaced
3
66
65
43
===================================================================================
==============================================================

/*Overriding example*/
class Bike
{
void run()
{
System.out.println("running");
}
}
class Splender extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}

public static void main(String args[]){


Splender b = new Splender();//Overriding
b.run();
}
}
Output:-
running safely with 60km
===================================================================================
=======================================================

/* employee is promoted if he has good communication skills,behaviour and technicl


skills*./

import java.util.Scanner;

public class employee


{

public static void main(String[] args)


{
String goodCommunication;
String behaviour;
String technicalSkills;
Scanner br=new Scanner(System.in);
System.out.println("goodCommunication good/bad:?");
goodCommunication=br.next();
System.out.println("Behaviour good/bad:?");
behaviour=br.next();
System.out.println("technicalSkills good/bad:?");
technicalSkills=br.next();

if(goodCommunication.equalsIgnoreCase("good")&&technicalSkills.equalsIgnoreCase("go
od")
&&behaviour.equalsIgnoreCase("good"))
{
System.out.println("Employee promoted");
}
else
{
System.out.println("Temp employee");
}

}
}

Output:-
goodCommunication good/bad:?
good
Behaviour good/bad:?
good
technicalSkills good/bad:?
good
Employee promoted
===================================================================================
==============================================================
/* display if bookcost<=500-normal book
bookcost>500&&bookcost<=1000-costlybook
bookcost>1000-precious book*/
import java.util.Scanner;

public class ifelse


{

public static void main(String[] args)


{
Scanner br=new Scanner(System.in);
System.out.println("Enter the book cost");
int cost=br.nextInt();
if(cost>0&&cost<=500)
System.out.println("Normal book");
else if(cost>500&&cost<=1000)
System.out.println("Costly book");
else if(cost>1000)
System.out.println("Precious book");
else
System.out.println("Enter valid cost");

}
Output:-
Enter the book cost
3989
Precious book
===================================================================================
==============================================================
/*consider a 2d array and display sum of non dimensional elements*/
import java.util.Scanner;

public class diagonal


{

public static void main(String[] args)


{
int array[][] = new int[3][3];
int sum=0,i,j;
Scanner br=new Scanner(System.in);
System.out.println("Enter values into the array");
for( i=0;i<3;i++)
{
for( j=0;j<3;j++)
{
int number=br.nextInt();
array[i][j]=number;

}
for(int k=0;k<3;k++)
{
for(int m=0;m<3;m++)
{
if(k!=m)
{
sum=sum+array[k][m];
}
}
}
System.out.println("Sum of non diagonal elements is"+sum);

Output:-

Enter values into the array


1 2 3
3 1 3
3 3 1
Sum of non diagonal elements is17
===================================================================================
======================================================================
/*create abstractclass/interface for productId and price*/

public class intex implements value


{
public void calculate()
{
int cost=3*price;
System.out.println(cost);
}

public static void main(String[] args)


{
intex i=new intex();
i.calculate();
}

}
---------

public interface value


{
public static final int productId=200;
public static final int price=300;
}

Output:-
900
===================================================================================
=====================================================================
/*nth element in an array*/

public class nth {

public static void main(String[] args)


{
int array[]={1,2,3,4,56,7,8,4,6,75,8,5776,6878};
System.out.println("The last element in the array
is"+array[array.length-1]);
}

}
===================================================================================
=====================================================================
/*second word in the string*/

public class stri {


public void add(String h)
{

String d[]=h.split(" ");


System.out.println(d[1]);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
stri g=new stri();
g.add("hello welcome to my world");
}

Output:

welcome
===================================================================================
================================================================
/*static example*/
class a
{
public static int s=9;
public int y=8;
static
{
System.out.println("Welcome");
}
static
{
System.out.println("Lekha is a angry girl");
}
public static void show()
{
System.out.println(s);
//System.out.println(y);
}
public void dis()
{
System.out.println(s);
// System.out.println(y);
}
}
public class statick extends a{

public static void main(String[] args) {


a i=new a();

}
output:-
welcome
lekha is angry girl
===================================================================================
==========================================================

programs and enum and templates should learn

You might also like