Java Interview Coding Questions:
1) How To Reverse a String without using reverse method:
public class Reverse{
public static void main(String[] args) {
String str = "STRING";
char []chr = str.toCharArray();
for(int i=chr.length-1; i>=0; i--) {
System.out.print(chr[i]);
}
}
}
2) Swap two numbers without using third variable:
public class Swap {
public static void main(String[] args) {
int a = 11;
int b = 12;
//logic
b = b-a;
a = a+b;
b = a-b;
System.out.println("value of a is "+a);
System.out.println("value of b is "+b);
}
}
3) To check if vowel is present in the string:
public class Vowel {
public static void main(String[] args) {
char chr[] = {'a','e','i','o','u'};
String str = "HimanshuU";
char stchr[] = str.toLowerCase().toCharArray();
for(int i=0; i<str.length(); i++) {
for(int j=0; j<chr.length; j++) {
if(stchr[i]==chr[j]) {
System.out.println(stchr[i]);
}
}
}
}
}
4) Program to use the linked list without collection class:
public class linkedlist
{
public static class Node //We are defining a node here
{
int data; //data of node here
Node next; //next refers to the address of the next node
}
public static void main(String args[])
{
Node newnode1=new Node(); //here we are making objects of class Node
Node newnode2=new Node(); //basically these are nodes of first linkedlist
Node newnode3=new Node();
Node newnode4=new Node();
newnode1.data=1;
newnode2.data=2;
newnode3.data=3;
newnode4.data=4;
newnode1.next=newnode2; //here we are linking the previous node to the next node of the list
newnode2.next=newnode3;
newnode3.next=newnode4;
newnode4.next=null;
//Now we will print the linked list
for (int i=1;i<=4;i++)
{
System.out.print(newnode1.data+" ");
newnode1=newnode1.next; //we are assigning the next address of the linked list to the current address
}
}
}
Comments
Post a Comment