Java programs
Name: B.Durga Hemanth
Regno: 9919004042
Array List and Strings
1.
Aim: To write a java program called phone keypad, which converts user
for a string and converts to a sequence of keypad digits.
Algorithm:
Coding:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String strinput;
int btnNumber = 0;
StringBuffer outputstr = new StringBuffer("");
Scanner in = new Scanner(System.in);
int strlenth;
System.out.println("Enter a String");
strinput = in.next().toString().toLowerCase();
strlenth = strinput.length();
for (int i = 0; i < strlenth; i++) {
char alphabet = strinput.charAt(i);
if (alphabet == 'a' || alphabet == 'b' || alphabet == 'c') {
btnNumber = 2;
} else if (alphabet == 'd' || alphabet == 'e' || alphabet ==
'f') {
btnNumber = 3;
} else if (alphabet == 'g' || alphabet == 'h' || alphabet ==
'i') {
btnNumber = 4;
} else if (alphabet == 'j' || alphabet == 'k' || alphabet ==
'l') {
btnNumber = 5;
} else if (alphabet == 'm' || alphabet == 'n' || alphabet ==
'o') {
btnNumber = 6;
} else if (alphabet == 'p' || alphabet == 'q' || alphabet == 'r'
|| alphabet == 's') {
btnNumber = 7;
} else if (alphabet == 't' || alphabet == 'u' || alphabet ==
'v') {
btnNumber = 8;
} else if (alphabet == 'w' || alphabet == 'x' || alphabet ==
'y' || alphabet == 'z') {
btnNumber = 9;
} else {
outputstr = new StringBuffer("Invalid Input");
break;
}
outputstr.append(btnNumber);
}
System.out.print(outputstr);
System.out.println("");
Output:
2.
Aim: To write a java program called Count Vowels Digits.
Algorithm:
Coding:
import java.util.*;
class Main
{
public static void main(String args[])
{
int i,vowels=0,consonants=0,digits=0;
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter sentence");
s=sc.nextLine();
char str[] = s.toCharArray();
int n= str.length;
for(i=0;i<n;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||str[i]=='o' ||
str[i]=='u' || str[i]=='A' ||str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U')
{
vowels++;
}
else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&&
str[i]<='Z'))
{
consonants++;
}
else if(str[i]>='0' && str[i]<='9')
{
digits++;
}
}
System.out.println("Vowels = "+vowels);
System.out.println("Consonants = "+consonants);
System.out.println("Digits = "+digits);
}
}
Output:
3.
Aim: To write a java program to reverse a string.
Algorithm:
Coding:
import java.util.*;
class Main
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
}
Output:
4
Aim: To write a java program that reads a line of integers and display
the integer and sum of all the integers.
Algorithm:
Coding:
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter sequence of integers with space b/w
them and press enter : ");
String digit=scr.nextLine();
StringTokenizer token=new
StringTokenizer(digit);
int dig=0,sum=0;
System.out.println("\nEntered digits are : ");
while(token.hasMoreTokens())
{
String s=token.nextToken();
dig=Integer.parseInt(s);
System.out.print(dig+" ");
sum=sum+dig;
}
System.out.println();
System.out.println("Sum is : "+sum);
}
}
Output:
5.
Aim: To write a java program to return the sum of digits present in the
string if there is no digit the sum return 0.
Algorithm:
Coding:
import java.util.*;
public class Main
{
public int sumOfDigits(String stng)
{
int l = stng.length();
int sum = 0;
for (int i = 0; i < l; i++)
{
if (Character.isDigit(stng.charAt(i)))
{
String tmp = stng.substring(i,i+1);
sum += Integer.parseInt(tmp);
}
}
return sum;
}
public static void main (String[] args)
{
Main m= new Main();
String str1 = "kManikanta";
System.out.println("The given string is: "+str1);
System.out.println("The sum of the digits in the string is:
"+m.sumOfDigits(str1));
}
}
Output:
6
Aim: To write a program to return a new string using every characters
of even positions from a given string.
Algorithm:
Coding:
import java.util.*;
public class Main
{
public String makeWithEvenCharacters(String stng)
{
int len = stng.length();
String fin_str = "";
for (int i = 0; i < len; i = i + 2)
{
fin_str += stng.charAt(i);
}
return fin_str;
}
public static void main (String[] args)
{
Main m= new Main();
String str1 = "kmanikanta1911";
System.out.println("The given string is: "+str1);
System.out.println("The new string is:
"+m.makeWithEvenCharacters(str1));
}
}
Output:
7.
Aim: To write a program to check whether the given string is
palindrome or not.
Algorithm:
Coding:
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output:
8
Aim: To write a java program to sort a list of names in ascending order.
Algorithm:
Coding:
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
String temp;
Scanner SC = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int N= SC.nextInt();
SC.nextLine();
String names[] = new String[N];
System.out.println("Enter names: ");
for(int i=0; i<N; i++)
{
System.out.print("Enter name [ " + (i+1) +" ]: ");
names[i] = SC.nextLine();
}
for(int i=0; i<5; i++)
{
for(int j=1; j<5; j++)
{
if(names[j-1].compareTo(names[j])>0)
{
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
}
}
}
System.out.println("\nSorted names are in Ascending
Order: ");
for(int i=0;i<N;i++)
{
System.out.println(names[i]);
}
}
}
Output:
9
Aim: To write a java program to concatenate a given string with itself
of a given number of times .
Coding:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str1 = "MANI";
System.out.println("Original string: "+str1);
String resultV1 = repeat_str(str1, 7);
System.out.println("\nAfter repeating 7 times: "+resultV1);
}
public static String repeat_str(String str1, int n) {
if (str1 == null || str1.isEmpty()) {
return "";
}
if (n <= 0) {
return str1;
}
if (Integer.MAX_VALUE / n < str1.length()) {
throw new OutOfMemoryError("Maximum size of a
String will be exceeded");
}
StringBuilder x = new StringBuilder(str1.length() * n);
for (int i = 1; i <= n; i++) {
x.append(str1);
}
return x.toString();
}
}
Output:
10.
Aim: To write a program to counts occurrences of a certain character in
a given string.
Algorithm:
Coding:
import java.util.*;
class Main {
static final int MAX_CHAR = 256;
static void getOccuringChar(String str)
{
int count[] = new int[MAX_CHAR];
int len = str.length();
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "manikanta";
getOccuringChar(str);
}
}
11.
Aim: To write a java program to perform string operations using Array
List.
Algorithm:
Coding:
import java.util.*;
public class Main
{
public static void main(String args[])
{
ArrayList<String> obj = new ArrayList<String>();
obj.add("Sai");
obj.add("Abhi");
obj.add("Kalyan");
obj.add("Manoj");
obj.add("Ganesh");
System.out.println("\n"+"Elements in ArrayList:");
System.out.print("\t"+obj+""+"\n" + "\n");
obj.add(0, "Mani");
obj.add(1, "teja");
System.out.println("After Inserting Elements:"+"");
System.out.print("\t"+obj+""+"\n" + "\n");
System.out.println("Search For Element:");
Scanner in = new Scanner(System.in);
String searchStr=in.nextLine();
boolean ans = obj.contains(searchStr);
if (ans)
System.out.println("\t"+"ArrayList contains" +searchStr+ "\n");
else
System.out.println("ArrayList does not contains "+searchStr);
System.out.println("Arraylist get the strings starting with given
letter:");
ArrayList<String> obj1 = new ArrayList<String>();
String start= in.next();
for(int i=0;i<obj.size();i++)
{
if(obj.get(i).startsWith(start.toUpperCase()))
{
obj1.add(obj.get(i));
}
}
System.out.print("\t"+obj1+""+"\n" + "\n");
}
}
Output Screen:
12.
Aim: To create a class and objects for Employee to demonstrate
class Employee’s capabilities.
Algorithm:
1. Start.
2. Create a class Employee.
3. Class includes three instance variables first name, last name,
and monthly salary.
4. Create a constructor that initializes three instance variables.
5. If salary is not positive set it to 0.0.
6. Create a test application named Employee test which
demonstrates class Employee’s capabilities.
7. Create 2 employee objects and display each object’s yearly
salary.
8. Raise 10% in salaries and display again employee salary
details.
9. Stop.
Coding:
import java.util.*;
class Employee {
String firstName;
String lastName;
double monthlySalary;
Employee() {
firstName = null;
lastName = null;
monthlySalary = 0.0;
}
void setFirstName(String firstName) {
this.firstName = firstName;
}
void setLastName(String lastName) {
this.lastName = lastName;
}
void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
String getFirstName() {
return this.firstName;
}
String getLastName() {
return this.lastName;
}
double getMonthlySalary() {
return this.monthlySalary;
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
System.out.println("\nEmployee 1 :");
Scanner scan = new Scanner(System.in);
System.out.print("Enter firstName :");
String e1firstName = scan.nextLine();
e1.setFirstName(e1firstName);
System.out.print("Enter lastName :");
String e1lastName = scan.nextLine();
e1.setLastName(e1lastName);
System.out.print("Enter monthlySalary :");
double e1monthlySalary = scan.nextDouble();
e1.setMonthlySalary(e1monthlySalary);
scan.nextLine();
System.out.println("\nEmployee 2 :");
System.out.print("Enter firstName :");
String e2firstName = scan.nextLine();
e2.setFirstName(e2firstName);
System.out.print("Enter lastName :");
String e2lastName = scan.nextLine();
e2.setLastName(e2lastName);
System.out.print("Enter monthlySalary :");
double e2monthlySalary = scan.nextDouble();
e2.setMonthlySalary(e2monthlySalary);
System.out.println("\nEmployee1 Full Name & yearly Salary
: ");
System.out.println(e1.getFirstName()+""+e1.getLastName()
+""+(e1.getMonthlySalary()*12));
System.out.println("\nEmployee2 Full Name & yearly Salary
: ");
System.out.println(e2.getFirstName()+""+e2.getLastName()
+""+(e2.getMonthlySalary()*12));
System.out.println("\nEmployee1 yearly Salary after 10%
raise in salaries : ");
System.out.println(e1.getFirstName()+""+e1.getLastName()
+""+((e1.getMonthlySalary()+
(e1.getMonthlySalary()*0.1))*12));
System.out.println("\nEmployee2 yearly Salary after 10%
raise in salaries : ");
System.out.println(e2.getFirstName()+""+e2.getLastName()
+""+((e2.getMonthlySalary()+
(e2.getMonthlySalary()*0.1))*12));
}
}
Output:
13.
Aim: To create classes and objects for Date test application
which demonstrates class Dates capabilities.
Algorithm:
1. Start.
2. Create a class date.
3. Class includes 3 instance variables month, day, and year.
4. Provide a set and get method for each instance variable.
5. Provide a method display date that displays month, day, year
separated by /.
6. Write a test application named Date Test and demonstrate
class date capabilities.
7. Stop.
Source Code:
import java.util.*;
class Date {
int month;
int day;
int year;
Date() {
month = 0;
day = 0;
year = 0;
}
void setMonth(int month) {
this.month = month;
}
void setDay(int day) {
this.day = day;
}
void setYear(int year) {
this.year = year;
}
int getMonth() {
return this.month;
}
int getDay() {
return this.day;
}
int getyear() {
return this.year;
}
public void displayDate() {
System.out.println("\nDate : "+getMonth()+"/"+getDay()
+"/"+getyear());
}
}
public class DateTest {
public static void main(String[] args) {
Date date = new Date();
Scanner scan = new Scanner(System.in);
System.out.print("Enter Day : ");
int day = scan.nextInt();
date.setDay(day);
System.out.print("Enter Month : ");
int month = scan.nextInt();
date.setMonth(month);
System.out.print("Enter Year : ");
int year = scan.nextInt();
date.setYear(year);
date.displayDate();
}
}
Output:
14.
Aim: To create classes and objects for BookTest application
which demonstrate class book’s capabilities.
Algorithm:
1. Start.
2. Create a class book.
3. Include 4 instance variables book name, ISBN number, author
name, and publisher.
4. Create constructor to initialize four instance variables.
5. Create set and get methods for each instance variables.
6. Create a method getbookinfo to return description of book.
7. Create an array for 3 elements for class book to demonstrate
class book capabilities.
8. Stop.
Coding:
import java.util.*;
class Book {
String bookName;
long ISBNnumber;
String authorName;
String publisher;
Book() {
bookName = "";
ISBNnumber = 0;
authorName = "";
publisher = "";
}
void setBookName(String bookName) {
this.bookName = bookName;
}
void setISBNnumber(long ISBNnumber) {
this.ISBNnumber = ISBNnumber;
}
void setAuthorName(String authorName) {
this.authorName = authorName;
}
void setPublisher(String publisher) {
this.publisher = publisher;
}
String getBookName() {
return this.bookName;
}
long getISBNnumber() {
return this.ISBNnumber;
}
String getAuthorName() {
return this.authorName;
}
String getPublisher() {
return this.publisher;
}
void getBookInfo() {
System.out.println("BookName : "+getBookName());
System.out.println("ISBNnumber : "+getISBNnumber());
System.out.println("AuthorName : "+getAuthorName());
System.out.println("Publisher : "+getPublisher());
}
}
public class BookTest {
public static void main(String[] args) {
Book[] book = new Book[30];
Scanner scan = new Scanner(System.in);
for(int i=1; i<=3; i++) {
book[i] = new Book();
System.out.println("\nBook"+i+" details :");
System.out.print("Enter BookName : ");
String bookName = scan.nextLine();
book[i].setBookName(bookName);
System.out.print("Enter ISBNnumber : ");
long number = scan.nextLong();
book[i].setISBNnumber(number);
scan.nextLine();
System.out.print("Enter authorName : ");
String author = scan.nextLine();
book[i].setAuthorName(author);
System.out.print("Enter Publisher : ");
String publisher = scan.nextLine();
book[i].setPublisher(publisher);
}
for(int k=1; k<=3; k++) {
System.out.println("\nBook "+k+" Description");
book[k].getBookInfo();
}
}
}
Output: