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

Java

The document contains multiple Java programs demonstrating various programming concepts such as string reversal without inbuilt functions, swapping numbers with and without a third variable, counting words using HashMap, and checking for prime numbers. It also includes examples of iterating through HashMaps and ArrayLists, finding duplicate characters in a string, and reading data from an Excel file. Additionally, it discusses method overriding and overloading in Java, including the effects of access modifiers.

Uploaded by

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

Java

The document contains multiple Java programs demonstrating various programming concepts such as string reversal without inbuilt functions, swapping numbers with and without a third variable, counting words using HashMap, and checking for prime numbers. It also includes examples of iterating through HashMaps and ArrayLists, finding duplicate characters in a string, and reading data from an Excel file. Additionally, it discusses method overriding and overloading in Java, including the effects of access modifiers.

Uploaded by

Utkarsh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Write a Java Program to reverse a string without using String inbuilt function.

public class FinalReverseWithoutUsingStringMethods {


2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 String str = "Automation";
6 StringBuilder str2 = new StringBuilder();
7 str2.append(str);
str2 = str2.reverse(); // used string builder to
8
reverse
9 System.out.println(str2);
10 }

12 }

Write a Java Program to reverse a string without using String inbuilt function
reverse().

public class FinalReverseWithoutUsingInbuiltFunction {


2 public static void main(String[] args) {
3 String str = "Saket Saurav";
4 char chars[] = str.toCharArray(); // converted to character array
and printed in reverse order
5 for(int i= chars.length-1; i>=0; i--) {
6 System.out.print(chars[i]);
7 }
8 }
9}

Write a Java Program to swap two numbers with using the third variable.

import java.util.Scanner;
2
3 public class SwapTwoNumbers {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 int x, y, temp;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10 x = in.nextInt();
11 y = in.nextInt();
12 System.out.println("Before Swapping" + x + y);
13 temp = x;
14 x = y;
15 y = temp;
16 System.out.println("After Swapping" + x + y);
17
18 }
19
20 }

Write a Java Program to swap two numbers without using the third variable.

import java.util.Scanner;
2
3 class SwapTwoNumberWithoutThirdVariable
4{
5 public static void main(String args[])
6 {
7 int x, y;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10
11 x = in.nextInt();
12 y = in.nextInt();
13
14 System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
15
16 x = x + y;
17 y = x - y;
18 x = x - y;
19
System.out.println("After Swapping without third variable\nx = "+x+"\
20
ny = "+y);
21 }
22 }

Write a Java Program to count the number of words in a string using HashMap.

import java.util.HashMap;
2
3 public class FinalCountWords {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 String str = "This this is is done by Saket Saket";
8 String[] split = str.split(" ");
9 HashMap<String,Integer> map = new HashMap<String,Integer>();
10 for (int i=0; i<split.length-1; i++) {
11 if (map.containsKey(split[i])) {
12 int count = map.get(split[i]);
13 map.put(split[i], count+1);
14 }
15 else {
16 map.put(split[i], 1);
17 }
18 }
19 System.out.println(map);
20 }
21
22 }

Write a Java Program to iterate HashMap using While and advance for loop.

import java.util.HashMap;
2 import java.util.Iterator;
3 import java.util.Map;
4
5 public class HashMapIteration {
6
7 public static void main(String[] args) {
8 // TODO Auto-generated method stub
9 HashMap<Integer,String> map = new HashMap<Integer,String>();
10 map.put(2, "Saket");
11 map.put(25, "Saurav");
12 map.put(12, "HashMap");
13 System.out.println(map.size());
14 System.out.println("While Loop:");
15 Iterator itr = map.entrySet().iterator();
16 while(itr.hasNext()) {
17 Map.Entry me = (Map.Entry) itr.next();
18 System.out.println("Key is " + me.getKey() + " Value is " +
me.getValue());
19 }
20 System.out.println("For Loop:");
21 for(Map.Entry me2: map.entrySet()) {
22 System.out.println("Key is: " + me2.getKey() + " Value is: " +
me2.getValue());
23 }
24 }
25
26 }

Write a Java Program to find whether a number is prime or not.

import java.util.Scanner;
2
3 public class Prime {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 int temp, num;
8 boolean isPrime = true;
9 Scanner in = new Scanner(System.in);
10 num = in.nextInt();
11 in.close();
12 for (int i = 2; i<= num/2; i++) {
13 temp = num%i;
14 if (temp == 0) {
15 isPrime = false;
16 break;
17 }
18 }
19 if(isPrime)
20 System.out.println(num + "number is prime");
21 else
22 System.out.println(num + "number is not a prime");
23
24
25 }
26
27 }

Write a Java Program to find whether a string or number is palindrome or not.

import java.util.Scanner;
2
3 public class Palindrome {
4 public static void main (String[] args) {
5 String original, reverse = "";
6 Scanner in = new Scanner(System.in);
7 int length;
8 System.out.println("Enter the number or String");
9 original = in.nextLine();
10 length = original.length();
11 for (int i =length -1; i>=0; i--) {
12 reverse = reverse + original.charAt(i);
13 }
14 System.out.println("reverse is:" +reverse);
15
16 if(original.equals(reverse))
17 System.out.println("The number is palindrome");
18 else
19 System.out.println("The number is not a palindrome");
20
21 }
}

22

Write a Java Program for Fibonacci series.


import java.util.Scanner;
2
3 public class Fibonacci {
4 public static void main(String[] args) {
5 int num, a = 0,b=0, c =1;
6 Scanner in = new Scanner(System.in);
7 System.out.println("Enter the number of times");
8 num = in.nextInt();
9 System.out.println("Fibonacci Series of the number is:");
10 for (int i=0; i<=num; i++) {
11 a = b;
12 b = c;
13 c = a+b;
System.out.println(a + ""); //if you want to print on the
14
same line, use print()
15 }
16 }
17 }

Write a Java Program to iterate ArrayList using for-loop, while-loop, and advance for-
loop.

import java.util.*;
2
3 public class arrayList {
4 public static void main(String[] args) {
5 ArrayList list = new ArrayList();
6 list.add("20");
7 list.add("30");
8 list.add("40");
9 System.out.println(list.size());
10 System.out.println("While Loop:");
11 Iterator itr = list.iterator();
12 while(itr.hasNext()) {
13 System.out.println(itr.next());
14 }
15 System.out.println("Advanced For Loop:");
16 for(Object obj : list) {
17 System.out.println(obj);
18 }
19 System.out.println("For Loop:");
20 for(int i=0; i<list.size(); i++) {
21 System.out.println(list.get(i));
22 }
23 }
24 }

Write a Java Program to find the duplicate characters in a string.

public class DuplicateCharacters {


2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 String str = new String("Sakkett");
6 int count = 0;
7 char[] chars = str.toCharArray();
8 System.out.println("Duplicate characters are:");
9 for (int i=0; i<str.length();i++) {
10 for(int j=i+1; j<str.length();j++) {
11 if (chars[i] == chars[j]) {
System.out.println(char
12
s[j]);
13 count++;
14 break;
15 }
16 }
17 }
18 }
19
20 }
Write a Java Program to find the second highest number in an array.
public class SecondHighestNumberInArray {
2 public static void main(String[] args)
3 {
4 int arr[] = { 14, 46, 47, 94, 94, 52, 86, 36, 94, 89 };
5 int largest = arr[0];
6 int secondLargest = arr[0];
7 System.out.println("The given array is:");
8 for (int i = 0; i < arr.length; i++)
9 {
10 System.out.print(arr[i] + "\t");
11 }
12 for (int i = 0; i < arr.length; i++)
13 {
14 if (arr[i] > largest)
15 {
16 secondLargest = largest;
17 largest = arr[i];
18 }
19 else if (arr[i] > secondLargest && arr[i] != largest)
20 {
21 secondLargest = arr[i];
22 }
23 }
24 System.out.println("\nSecond largest number is:" + secondLargest);
25 }
26 }
Write a Java Program to check Armstrong number.

class Armstrong{
2 public static void main(String[] args) {
3 int c=0,a,temp;
4 int n=153;//It is the number to check Armstrong
5 temp=n;
6 while(n>0)
7 {
8 a=n%10;
9 n=n/10;
10 c=c+(a*a*a);
11 }
12 if(temp==c)
13 System.out.println("armstrong number");
14 else
15 System.out.println("Not armstrong number");
16 }
17 }
Write a Java Program to remove all white spaces from a string with using replace().

class RemoveWhiteSpaces
2{
3 public static void main(String[] args)
4 {
5 String str1 = "Saket Saurav is a QualityAna list";
6
7 //1. Using replaceAll() Method
8
9 String str2 = str1.replaceAll("\\s", "");
10
11 System.out.println(str2);
12
13 }
14 }
15 }

Write a Java Program to remove all white spaces from a string without using
replace().

class RemoveWhiteSpaces
2{
3 public static void main(String[] args)
4 {
String str1 = "Saket Saurav is an Autom ation Engi ne
5
er";
6
7 char[] chars = str1.toCharArray();
8
9 StringBuffer sb = new StringBuffer();
10
11 for (int i = 0; i < chars.length; i++)
12 {
13 if( (chars[i] != ' ') && (chars[i] != '\t') )
14 {
15 sb.append(chars[i]);
16 }
17 }
18 System.out.println(sb); //Output :
CoreJavajspservletsjdbcstrutshibernatespring
19 }
20 }

Write a Java Program to read an excel.

@Test
2 public void ReadData() throws IOException
3 {
// Import excel sheet from a webdriver directory which is inside c
4
drive.
5 //DataSource is the name of the excel
6 File src=new File("C:\\webdriver\\DataSource.xls");
7
8 //This step is for loading the file. We have used FileInputStream as
9 //we are reading the excel. In case you want to write into the file,
//you need to use FileOutputStream. The path of the file is passed as
10
an argument to FileInputStream
11 FileInputStream finput = new FileInputStream(src);
12
//This step is to load the workbook of the excel which is done by
13
global HSSFWorkbook in which we have
14 //passed finput as an argument.
15 workbook = new HSSFWorkbook(finput);
16
17 //This step is to load the sheet in which data is stored.
18 sheet= workbook.getSheetAt(0);
19
20 for(int i=1; i<=sheet.getLastRowNum(); i++)
21 {
22 // Import data for Email.
23 cell = sheet.getRow(i).getCell(1);
24 cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("email")).sendKeys(cell.getStringCellValu
25
e());
26
27 // Import data for the password.
28 cell = sheet.getRow(i).getCell(2);
29 cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("password")).sendKeys(cell.getStringCellV
30
alue());
31
32 }
33 }
PTR

We can change the return type or different argument is possible in case of overriding only by using co-
variant.

Java 5.0 onwards it is possible to have different return type for a overriding method in child
class, but child’s return type should be sub-type of parent’s return type. Overriding method
becomes variant with respect to return type.

class SuperClass {

SuperClass get() {

System.out.println("SuperClass");

return this;

public class Tester extends SuperClass {

Tester get() {

System.out.println("SubClass");

return this;

public static void main(String[] args) {

SuperClass tester = new Tester();

tester.get();

Output:

Subclass
Does access modifier affects method overloading in Java ?
 Access modifiers doesn’t affect method overloading, so overloaded methods can
have same or different access levels
Q) Whether it is possible to overload methods in Java, just by changing
return-type ?
 No, it is not valid to consider return type for method overloading
Q) Whether class compiles successfully, if we have two methods with same
name but different return-type ?
 Compilation fails with below error

You might also like