Posts

Showing posts with the label Java Interview Programs

Write a program to check string is palindrome or not

Write a simple program to check given string is palindrome or not. This is very simple but it frequent asked in interview for freshers. public class StringPalindrome { public static void main(String[] args) { String input = "abcdcba"; boolean isPalindrome = isPalindrome(input); System.out.println(isPalindrome); } private static boolean isPalindrome(String input){ for (int i = 0; i < input.length()/2; i++) { if(input.charAt(i) != input.charAt(input.length()-i-1)){ return false; } } return true; } }

Implement a custom linked list with add and iteration functionality.

Write a program to implement custom linked list with minimum functionalities like add and iterations. You can not use in-build functionality of collection framework. package ztest; import java.util.Iterator; public class CustomLinkedList implements Iterable{ private int size = 0; private Node first; private Node last; private static class Node{ Object element; Node next; public Node(Object element) { this.element = element; } } public void add(Object element){ Node newNode = new Node(element); Node preLast = this.last; this.last = newNode; if(this.first == null){ this.first = newNode; }else{ preLast.next = newNode; } size++; } private class CustomListIterator implements Iterator{ int cursor; Node currentNode = first; @Override public boolean hasNext() { return cursor < size; } @Override public Object next() { Node tempNode = currentNode; currentNode = currentNode.next; cursor++; return tempNode....

Write a program to sort object using Comparator and Comparable

We will sort object of Student class. We will sort students by marks in ascending order. Comparable: import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Student implements Comparable { private Integer id; private String name; private int marks; public Student() { } public void setName(String name) { this.name = name; } public Student(Integer id, String name, int marks) { this.id = id; this.name = name; this.marks = marks; } @Override public int compareTo(Student stu) { if(this.marks < stu.marks){ return -1; }else if(this.marks > stu.marks){ return 1; }else{ return 0; } } public static void main(String[] args) { List students = new ArrayList<>(); students.add(new Student(1, "A", 67)); students.add(new Student(2, "B", 35)); students.add(new Student(3, "C", 80)); students.add(new Student(4, "D", 17)); System.out.println("E...