Java Codes
1) Write a simple Java program?
public class Simple{
public static void main(String[] args){
System.out.println(“Hello World”);
}
}
2) Write a Java program to print an integer value?
public class PrintInteger{
public static void main(String[] args){
int i = 1; System.out.println(i);
}
}
3) Write a Java program to print the command line arguments?
public class Sample {
public static void main(String[] args){
if (args.length > 0) {
System.out.println(“The command line”+ ” arguments are:”);
for(String val:args)
System.out.println(val);
} else
System.out.println(“No command line “+ “arguments found.”);
}
}
Command Line:
Bijans-MacBook-Pro:java bijan$ javac Sample.java
Bijans-MacBook-Pro:java bijan$ java Sample Java Interview Questions
The command line arguments are:
Java Interview Questions
4) Write a Java program to print the input from scanner?
public class PrintScannerInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(“Name: “+name);
}
}
5) Write a Java program to convert from Fahrenheit to Celsius?
public class ConvertToCelsius {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“Input temperature in Fahrenheit: “);
double fahrenheit = sc.nextDouble();
double celsius = ((5 * (fahrenheit – 32.0)) / 9.0);
System.out.println(fahrenheit + ” degree fahrenheit is equal to ” + celsius + “in celsius”);
}
}
6) Write a Java program to swap two numbers?
public class SwapNumbers {
public static void main(String[] args) {
int x, y, z;
Scanner sc = new Scanner(System.in);
x = sc.nextInt(); y = sc.nextInt();
System.out.println(“Before swapping\n x = ” + x + “\n y = ” + y);
z = x; x = y; y = z;
System.out.println(“After swapping\n x = ” + x + “\n y = ” + y);
}
}
7) Write a Java program to swap two numbers without using third variable?
public class SwapNumberWithoutVariable {
public static void main(String[] args) {
int x = 10;
int y = 5;
x = x + y;
y = x – y;
x = x – y;
System.out.println(“After swapping: ” + ” x is ” + x + ” and ” + “y is “+ y);
}
}
8) Write a Java program to add two numbers?
public class AddNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(); int b = sc.nextInt();
int sum = a + b;
System.out.println(“Sum of two numbers is: ” + sum);
}
}
9) Write a Java program to find the largest number?
public **class** FindLargestNumberInArray {
static int array[] = {21,98,13,9,34};
public static **void** main(String[] args){
int maxNumber = findLargestNumber();
System.out.println(“Maximum number in the array: “+ maxNumber);
}
private static int findLargestNumber(){
int max = array[0];
**for**(int i =0;i<array.length;i++){
**if**(array[i]>max)
max = array[i];
}
**return** max;
}
}
10) Write a Java program to demonstrate if..else statement ?
public class FindNumberIsPrime {
public static void main(String[] args){
boolean flag = false;
System.out.println(“Enter input number”);
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for(int i=2;i<=num/2;i++){
if(num%i==0){
flag = true;
break;
}
}
if(!flag){
System.out.println(num + ” is a prime number”);
} else{
System.out.println(num + ” is not a prime number”);
}
}
}
11) Write a Java program to demonstrate nested if … else if .. statement?
public class IfElseDemo {
public static void main(String[] args){
int i =20;
if(i == 10)
System.out.println(“i is 10”);
else if(i == 15)
System.out.println(“i is 15”);
else if(i == 20)
System.out.println(“i is 20”);
else
System.out.println(“i is not present”);
}
}
12) Write a Java program to demonstrate nested if …else statement?
class Ladder {
public static void main(String[] args) {
int number = 0;
if (number > 0) {
System.out.println(“Number is positive.”);
} else if (number < 0) {
System.out.println(“Number is negative.”);
} else {
System.out.println(“Number is 0.”);
}
}
}
13) Write a Java program to find odd and even numbers ?
public class FindOddEvenNumbers {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println(“Enter a number: “);
int inputNumber = sc.nextInt();
findNumber(inputNumber);
}
public static void findNumber(int number){
if(number%2!=0){
System.out.println(“Number is odd”);
}
else {
System.out.println(“Number is even”);
}
}
}
14) Write a Java program to compare two strings?
public class CompareTwoStrings {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter first string”);
String first = sc.next();
System.out.println(“Enter second string”);
String second = sc.next();
compare(first,second);
}
public static void compare(String s1, String s2){
if(s1.compareTo(s2)==0) {
System.out.println(“Strings are equal”);
} else {
System.out.println(“Strings are not equal”);
}
}
}
15) Write a Java program to demonstrate for loop ?
public class ReverseSentenceWordByWord {
public static void main(String[] args){
String sentence = “Java Interview Questions”;
String reversedSentence = reverseSentence(sentence);
System.out.println(reversedSentence);
}
public static String reverseSentence(String sentence){
String reverse = “”;
String[] words = sentence.split(“\\s”);
for(int i=words.length-1;i>=0;i–){
reverse = reverse + words[i] + ” “;
}
return reverse;
}
}
16) Write a Java program to print stars using for loop, where the number of stars printed should be equal to the row number?
public class PrintStarPatternInRow {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows”);
int rows = sc.nextInt();
printStars(rows);
}
public static void printStars(int n){
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.print(“* “);
}
System.out.println();
}
}
}
17) Write a Java program to demonstrate while loop?
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i–;
}
}
}
18) Write a Java program to print the entered number in reverse?
public class ReverseNumber {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number”);
int num = sc.nextInt();
reverseNumber(num);
}
public static void reverseNumber(int number){
int reverse = 0;
while(number!=0){
int digit = number % 10;
reverse = reverse * 10 + digit;
number = number/10;
}
System.out.println(“Reversed number ” + reverse);
}
}
19) Write a Java program to demonstrate the usage of break statement inside while loop?
class BreakExample {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.print(“Enter a number: “);
number = input.nextDouble();
if (number < 0.0) {
break;
}
sum += number;
}
System.out.println(“Sum = ” + sum);
}
}
20) Write a Java program to demonstrate the usage of break and continue statements inside while loop?
public class ContinueExample {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 5};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print(“\n”);
}
}
}
21) Write a Java program to print the alphabets using for loop?
public class PrintAlphabets
{
public static void main(String[] args)
{
char i;
System.out.printf(“The Alphabets from A to Z are: \n”);
for (i = ‘A’; i <= ‘Z’; i++)
{
System.out.printf(“%c “, i);
}
}
}
22) Write a Java program to demonstrate for each loop?
public class FindHighestMarks {
public static void main(String[] arg) {
int[] marks = { 125, 132, 95, 116, 110 };
int highest_marks = maximum(marks);
System.out.println(“The highest score is ” + highest_marks);
}
public static int maximum(int[] numbers) {
int max = numbers[0];
// for each loop
for (int num : numbers) {
if (num > max) {
max = num;
}
}
return max;
}
}
23) Write a Java program for printing the Multiplication table?
public class MultiplicationTable {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter number”);
int number = sc.nextInt();
System.out.println(“Enter multiplication range”);
int range = sc.nextInt();
for(int i=1;i<=range;i++){
System.out.printf(“%d * %d = %d \n”, number, i, number * i);
}
}
}
24) Write a Java program for printing the prime numbers?
public class FindNumberIsPrime {
public static void main(String[] args){
boolean flag = false;
System.out.println(“Enter input number”);
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for(int i=2;i<=num/2;i++){
if(num%i==0){
flag = true;
break;
}
}
if(!flag){
System.out.println(num + ” is a prime number”);
} else{
System.out.println(num + ” is not a prime number”);
}
}
}
25) Write a Java program to check whether a given number is Armstrong ?
public class ArmstrongNumber {
public static void main(String[] args){
int c=0,a,temp;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a number”);
int num = sc.nextInt();
temp = num;
while(num>0){
a=num%10;
num=num/10;
c=c+(aaa);
}
if(temp==c) {
System.out.println(temp + ” is an Armstrong number”);
} else
System.out.println(temp + ” is not an armstrong number”);
}
}
1) Write a Java program to print Floyd’s triangle?
public class FloydTriangle {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows”);
int rows = sc.nextInt();
printFloydTriangle(rows);
}
public static void printFloydTriangle(int n){
int number = 1;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.print(number +” “);
number++;
}
System.out.println();
}
}
}
2) Write a Java program to find all the sub-string of given string?
public class FindSubString {
public static void main(String[] args) {
String name = “Selenium And Java Interview Questions”;
System.out.println(name.contains(“Java”)); // true
System.out.println(name.contains(“java”)); // false
System.out.println(name.contains(“Interview”)); // true
System.out.println(name.contains(“questions”)); // false
}
}
3) Write a Java program to print the given string in reverse?
public class ReverseString {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter input string”);
String s1 = sc.next();
String s2 = reverseString(s1);
System.out.println(“Reversed String is: “+s2);
}
public static String reverseString(String s){
String rev=””;
char[] arr = s.toCharArray();
for(int i=arr.length-1;i>=0;i–)
rev = rev + arr[i];
return rev;
}
}
4) Write a Java program to check whether the given number is palindrome?
public class PalindromeNumber {
public static void main(String[] args){
int r,sum=0,temp;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a number”);
int n = sc.nextInt();
temp=n;
while (n > 0) {
r = n%10;
sum = (sum*10) + r;
n=n/10;
}
if(temp==sum)
System.out.println(“Number is palindrome”);
else
System.out.println(“Number is not palindrome”);
}
}
5) Write a Java program to add two matrix?
public class AddTwoMatrix {
public static void main(String args[]) {
//creating two matrices
int a[][] = {{1, 3, 4}, {2, 4, 3}, {3, 4, 5}};
int b[][] = {{1, 3, 4}, {2, 4, 3}, {1, 2, 4}};
//creating another matrix to store the sum of two matrices
int c[][] = new int[3][3];
//adding and printing addition of 2 matrices
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
System.out.print(c[i][j] + ” “);
}
System.out.println();
}
}
}
6) Write a Java program to multiply two matrix?
public class MultiplyTwoMatrix {
public static void main(String args[]) {
//creating two matrices
int a[][] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
int b[][] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
//creating another matrix to store the multiplication of two matrices
int c[][] = new int[3][3];
//multiplying and printing multiplication of 2 matrices
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
c[i][j] = 0;
for(int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + ” “);
}
System.out.println();
}
}
7) Write a Java program to get the transpose of matrix?
public class TransposeMatrix{
public static void main(String args[]){
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
//creating another matrix to store transpose of a matrix
int transpose[][]=new int[3][3]; //3 rows and 3 columns
//Code to transpose a matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println(“Printing Matrix without transpose:”);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(original[i][j]+” “);
}
System.out.println();
}
System.out.println(“Printing Matrix After Transpose:”);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+” “);
}
System.out.println();
}
}
}
8) Write a Java program to compare two strings?
public class CompareTwoStrings {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter first string”);
String first = sc.next();
System.out.println(“Enter second string”);
String second = sc.next();
compare(first,second);
}
public static void compare(String s1, String s2){
if(s1.compareTo(s2)==0) {
System.out.println(“Strings are equal”);
} else {
System.out.println(“Strings are not equal”);
}
}
}
9) How to find whether a String ends with a specific character or text using Java program?
public class StringEndWith{
public static void main(String args[]) {
String s1 = “Java is a programming language”;
//Check if string ends with particular character
boolean endsWithCharacter = s1.endsWith(“e”);
System.out.println(“String ends with character ‘e’: ” + endsWithCharacter);
//Check if string ends with particular text
boolean endsWithText = s1.endsWith(“java”);
System.out.println(“String ends with String ‘lang’: ” + endsWithText);
}
}
10) Write a Java program to demonstrate indexOf()?
public class IndexOfExample{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the input string:”);
String inputString = sc.nextLine();
System.out.println(“Enter the sub string:”);
String subString = sc.nextLine();
int index = inputString.indexOf(subString);
System.out.println(“Index of sub string is: ” + index);
}
}
11) Write a Java program to demonstrate how to replace a string with another string?
public class ReplaceString{
public static void main(String args[]) {
String originalString = “Java for dummies”;
String newString = originalString.replace(“dummies”,”experts”);
System.out.println(“Original string is: ” + originalString);
System.out.println(“New String is: ” + newString);
}
}
12) Write a Java program to split the given string?
class SplitString{
public static void main(String []args){
String strMain = “Java,C,Python,Perl”;
String[] arrSplit = strMain.split(“,”);
for (int i=0; i < arrSplit.length; i++)
{
System.out.println(arrSplit[i]);
}
}
}
13) Write a Java program to remove the spaces before and after the given string?
class RemoveSpacesInString{
public static void main(String []args){
String s1 = “Interview Questions for Java”;
String newString = s1.replaceAll(“\\s”,””);
System.out.println(“Old String: ” + s1);
System.out.println(“New String: ” + newString);
}
}
14) Write a Java program to convert all the characters in given string to lower case?
class ConvertToLowerCase{
public static void main(String []args){
String s1 = “Interview QUESTIONS”;
String newString = s1.toLowerCase();
System.out.println(“Old String: ” + s1);
System.out.println(“New String: ” + newString);
}
}
15) Write a Java program to demonstrate creating a method?
public class CreateMethodExample {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number”);
int num = sc.nextInt();
reverseNumber(num);
}
public static void reverseNumber(int number){
int reverse = 0;
while(number!=0){
int digit = number % 10;
reverse = reverse * 10 + digit;
number = number/10;
}
System.out.println(“Reversed number ” + reverse);
}
}
16) Write a Java program to find the length of the given string?
class FindLength{
public static void main(String []args){
String s1 = “Interview Questions In Java”;
int length = s1.length();
System.out.println(“Length of string is: ” + length);
}
}
17) Write a Java program to concatenate the given strings?
class StringConcatenation{
public static void main(String []args){
String s1 = “Interview Questions In Java”;
String s2 = ” And Selenium”;
String s3 = s1.concat(s2);
System.out.println(“After concatenation: “+ s3);
}
}
18) Write a Java program to replace a string?
class ReplaceString{
public static void main(String []args){
String s1 = “Interview Questions In Java”;
String s2 = “Answers”;
String s3 = s1.replace(“Questions”,”Answers”);
System.out.println(“Original String: “+ s1);
System.out.println(“New String: “+ s3);
}
}
19) Write a Java program to demonstrate a Static block?
class StaticTest {
static int i;
int j;
// start of static block
static {
i = 10;
System.out.println(“static block called “);
}
// end of static block
}
class Main {
public static void main(String args[]) {
System.out.println(Test.i);
}
}
20) Explain the difference between static and instance methods in Java?
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
21) Write a Java program to demonstrate creating multiple classes?
public class A {
public static void print() {
System.out.println(“This is a method”);
}
}
public class B {
public static void main(String args[]) {
print();
}
}
22) Write a Java program to demonstrate creating a constructor?
class ConstructorTest {
ConstructorTest(){
System.out.println(“Constructor called”);
}
}
class Main
{
public static void main (String[] args)
{
ConstructorTest test = new ConstructorTest();
}
}
23) Write a Java program to demonstrate constructor overloading?
class Box
{
double width, height, depth;
int boxNo;
Box(double w, double h, double d, int num)
{
width = w;
height = h;
depth = d;
boxNo = num;
}
Box()
{
width = height = depth = 0;
}
Box(int num)
{
this();
boxNo = num;
}
public static void main(String[] args)
{
Box box1 = new Box(1);
System.out.println(box1.width);
}
}
24) Write a Java program to demonstrate Exception Handling?
public class ExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
}
}
25) Write a Java program to demonstrate throwing an exception?
class ThrowExceptionExample
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(10000);
System.out.println(“Hello World”);
}
}
- Java Program: Change a string such that first character is upper case, second is lower case and so on?
public static String changeToUpperCase(String str) {
StringBuffer s = new StringBuffer();
char ch = ‘ ‘;
for (int i = 0; i < str.length(); i++) {
if (ch == ‘ ‘ && str.charAt(i) != ‘ ‘)
s.append(Character.toUpperCase(str.charAt(i)));
else
s.append(str.charAt(i));
ch = str.charAt(i);
}
return s.toString().trim();
}
- Java Program: To find duplicates in a list?
public static Set<String> findDuplicates(List<String> listDuplicates) {
final Set<String> set1 = new HashSet<String>();
final Set<String> set2 = new HashSet<String>();
for (String str : listDuplicates) {
if (!set1.add(str)) {
set2.add(str);
}
}
return set2;
}
- Write a program to compare two Hashmap for equality?
public static Boolean compareMaps(){
Map<String, String> country1 = new HashMap<String, String>();
country1.put(“Japan”, “Tokyo”);
country1.put(“China”, “Beijing”);
Map<String, String> country2 = new HashMap<String, String>();
country2.put(“Japan”, “Tokyo”);
country2.put(“China”, “Beijing”);
if(country1==country2){
return true;
} else
return false;
}
- Write a Java program to demonstrate creating an Array?
public static void main (String[] args)
{
int[] arr;
arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (int i = 0; i < arr.length; i++)
System.out.println(“Element at index ” + i + ” : “+ arr[i]);
}
- Java Program: String s = “sub53od73th”; Eliminate the numbers alone. Print the Alphabets.
public static String removeNumFromString(String str) {
if (str == null) {
return null;
}
char[] ch = str.toCharArray();
int length = ch.length;
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < length) {
if (Character.isDigit(ch[i])) {
i++;
} else {
sb.append(ch[i]);
i++;
}
}
return sb.toString();
}
- Java program: Reverse the words in the sentence?
public static String reverseTheSentence(String inputString)
{
String[] words = inputString.split(“\s”);
String outputString = “”;
for (int i = words.length-1; i >= 0; i–)
{
outputString = outputString + words[i] + ” “;
}
return outputString;
}
- Java program: Find the count of each element in a two dimensional matrix?
static void printCount(int a[][], int n, int m, int z[], int l)
{
for (int i = 0; i < n; i++)
{
Map<Integer,Integer> mp = new HashMap<>();
for (int j = 0; j < m; j++)
mp.put(a[i][j], 1);
int count = 0;
for (int j = 0; j < l; j++)
{
if (mp.containsKey(z[j]))
count += 1;
}
System.out.println(“row” +(i + 1) + ” = ” + count);
}
- Java Program: Find duplicate elements in an array of numbers?
public static void main(String[] args) {
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println(“Duplicate elements in given array: “);
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
- Write a program to read/write data from a Property file?
public static void main(String[] args){
Properties prop = new Properties();
prop.setProperty(“db.url”, “localhost”);
prop.setProperty(“db.user”, “mkyong”);
prop.setProperty(“db.password”, “password”);
prop.store(outputStream, “”);
prop.load(inputStream)
prop.getProperty(“db.url”);
prop.getProperty(“db.user”);
prop.getProperty(“db.password”);
prop.keySet();
prop.forEach((k, v) -> System.out.println(“Key : ” + k + “, Value : ” + v));
}
- Write a Java program to demonstrate creating factorial of a number using recursion?
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;
fact = factorial(number);
System.out.println(“Factorial of “+number+” is: “+fact);
}
}
- Java Program: To print the frequency of words in a paragraph?
public static void frequencyWords(String strInput){
Map<String, Integer> occurrences = new HashMap<String, Integer>();
String[] words = strInput.split(“\\s+”);
for(String word: words){
if(occurrences.containsKey(word)){
int count = occurrences.get(word);
map.put(word,count+1);
} else {
map.put(word,1);
}
}for(Map.Entry<String,Integer> entry: map.entrySet()){
System.out.println(entry.getKey() + “:” + entry.getValue());
}
}
- Write a Java program to see the output as 0,1,1,2,3?
public static void main(String args[])
{
int n1=0,n2=1,n3,count=5;
System.out.print(n1+” “+n2);
for(int i=2;i<count;i++)
{
n3=n1+n2;
System.out.print(” “+n3);
n1=n2;
n2=n3;
} }
- Write a java program to find the factorial of a given number ?
public static void findFactorial(int number){
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println(“Factorial of ” + number + “is: ” + fact);
}
- Write a Java program to demonstrate ArrayList?
class ArrayListExample {
public static void main(String[] args)
{
int n = 5;
ArrayList<Integer> arrList = new ArrayList<Integer>(n);
for (int i = 1; i <= n; i++)
arrList.add(i);
System.out.println(arrList);
arrList.remove(3);
System.out.println(arrList);
for (int i = 0; i < arrList.size(); i++)
System.out.print(arrList.get(i) + ” “);
}
}
- Write a Java program to demonstrate LinkedList?
public class LinkedListExample {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.add(“A”);
list.add(“B”);
list.addLast(“C”);
list.addFirst(“D”);
list.add(2, “E”);
System.out.println(list);
list.remove(“B”);
list.remove(3);
list.removeFirst();
list.removeLast();
System.out.println(list);
}
}
- Write a Java program to demonstrate ArrayList using List interface?
class ArrayListWithListInterface {
public static void main(String[] args)
{
List<String> arrayList = new ArrayList<String>();
arrayList.add(“Java”);
arrayList.add(“C#”);
arrayList.add(“Python”);
System.out.println(arrayList);
}
}
- Write a Java program to demonstrate Hashset?
class HashSetExample{
public static void main(String[] args){
Set<String> hs = new HashSet<String>();
hs.add(“India”);
hs.add(“Australia”);
hs.add(“South Africa”);
hs.add(“India”);
System.out.println(hs);
}
}
- Write a Java program to demonstrate LinkedHashSet?
public class LinkedHashSetExample
{
public static void main(String[] args)
{
LinkedHashSet<String> linkedset = new LinkedHashSet<String>();
linkedset.add(“A”);
linkedset.add(“B”);
linkedset.add(“C”);
linkedset.add(“D”);
System.out.println(linkedset);
}
}
- Write a Java program to demonstrate TreeSet?
class TreeSetExample {
public static void main(String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();
ts1.add(“A”);
ts1.add(“B”);
ts1.add(“C”);
ts1.add(“C”);
System.out.println(ts1);
}
}
- Write a Java program to demonstrate PriorityQueue?
class PriorityQueueExample {
public static void main(String args[])
{
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
pQueue.add(10);
pQueue.add(20);
pQueue.add(15);
System.out.println(pQueue.peek());
System.out.println(pQueue.poll());
}
}
- Write a Java program to demonstrate creating HashMap using Map interface?
class HashMapExample{
public static void main(String[] args){
Map<Integer,String> h1 = new HashMap<>();
h1.put(1,”Java”);
h1.put(2,”C#”);
h1.put(3,”Python”);
System.out.println(h1);
}
}
- Write a Java program to demonstrate LinkedHashMap ?
public class LinkedHashMapExample
{
public static void main(String a[])
{
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(“one”, “www.gmail.com“);
map.put(“two”, “www.ymail.com“);
map.put(“four”, “www.outlook.com“);
System.out.println(lhm);
}
}
- Write a Java program to demonstrate TreeMap?
class TreeMapExample{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,”Amit”);
map.put(102,”Ravi”);
map.put(101,”Vijay”);
map.put(103,”Rahul”);
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+” “+m.getValue());
}
}
}
- Write a Java program to demonstrate Hashtable?
class HashtableExample{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,”Jeorge”);
hm.put(102,”Smith”);
hm.put(101,”Sarah”);
hm.put(103,”John”);
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+” “+m.getValue());
}
}
}
- Write a Java program to demonstrate creating Multidimensional array?
class MultiExample {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println(“arr[” + i + “][” + j + “] = “
- arr[i][j]);
}
}
1) Write a Java program to demonstrate the creation of Interface?
// A simple interface
interface A
{
final int a = 10;
void display();
// A class that implements the interface.
class TestClass implements A
}
{
public void display()
{
System.out.println(“this is an interface”);
}
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
2) Write a Java program to print date and time?
public class CurrentDateTime {
public static void main(String[] args) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);
LocalDateTime now = LocalDateTime.now();
System.out.println(df.format(now));
}
}
3) Write a Java program to demonstrate SQL Date?
public class SQLDate {
public static void main(String[] args) {
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
}
}
4) Write a Java program to demonstrate Date format?
public class GetCurrentDateTime {
private static final DateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);
public static void main(String[] args) {
Date date = new Date();
System.out.println(sdf.format(date));
Calendar cal = Calendar.getInstance();
System.out.println(sdf.format(cal.getTime()));
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
LocalDate localDate = LocalDate.now();
System.out.println(DateTimeFormatter.ofPattern(“yyy/MM/dd”).format(localDate));
}
}
5) Write a Java program to demonstrate generating a random number?
public class GenerateRandomNumber {
public static void main(String[] args){
Random rand = new Random();
int r1 = rand.nextInt(1000);
System.out.println(“Random numbers: “+ r1);
}
}
6) Write a Java program to demonstrate garbage collection?
public class GarbageCollector {
public static void main(String[] args) throws InterruptedException{
GarbageCollector t1 = new GarbageCollector();
GarbageCollector t2 = new GarbageCollector();
// Nullifying the reference variable
t1 = null;
// requesting JVM for running Garbage Collector
System.gc();
// Nullifying the reference variable
t2 = null;
// Requesting JVM for running Garbage Collector
Runtime.getRuntime().gc();
}
@Override
protected void finalize() throws Throwable {
System.out.println(“Garbage collector called”);
System.out.println(“Object garbage collected: ” + this);
}
}
7) Write a Java program to get the IP Address of own machine?
public class FindIPAddress {
public static void main(String[] args) throws Exception{
// Returns the instance of InetAddress containing local host name and address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(“System IP Address : ” + (localhost.getHostAddress()).trim());
// Find public IP address
String systemipaddress = “”;
try {
URL url_name = new URL(“http://bot.whatismyipaddress.com“);
BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
// reads system IPAddress
systemipaddress = sc.readLine().trim();
} catch (Exception e) {
systemipaddress = “Cannot Execute Properly”;
}
System.out.println(“Public IP Address: ” + systemipaddress +”\n”);
}
}
8) Write a Java program to open a notepad?
public class OpenNotepad {
public static void main(String[] args){
Runtime rs = Runtime.getRuntime();
try{
rs.exec(“notepad”);
}
catch (IOException e){
System.out.println(e);
}
}
}
9) Write a Java program to demonstrate Linear Search?
public class LinearSearch {
static int search(int arr[], int n, int x){
for(int i = 0;i<n;i++){
if(arr[i] == x)
return i;
}
return -1;
}
public static void main(String[] args){
int[] arr = {5,1,9,4,3,8};
int n = arr.length;
int x = 4;
int index = search(arr,n,x);
if(index == -1){
System.out.println(“Element is not present in the array”);
}
else
System.out.println(“Element found at position ” + index);
}
}
10) Write a Java program to demonstrate Binary Search?
class BinarySearch {
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r – l) / 2;
// If the element is present at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid – 1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// If element is not present in array
return -1;
}
public static void main(String args[])
{
BinarySearch bs = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = bs.binarySearch(arr, 0, n – 1, x);
if (result == -1)
System.out.println(“Element not present”);
else
System.out.println(“Element found at index ” + result);
}
}
11) Write a Java program to demonstrate Bubble sort?
class BubbleSort
{
void bubbleSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + ” “);
System.out.println();
}
public static void main(String args[]) {
BubbleSort bs = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bs.bubbleSort(arr);
System.out.println(“Sorted array”);
bs.printArray(arr);
}
}
12) Write a Java program to demonstrate connecting to a Database?
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,String db_userid,String db_password)
{
try {