Skip to main content

Posts

Showing posts from October, 2014

How to make Thread by extending Thread class

Points To Remember We can implement Runnable interface or extend Thread class to create threads. We have to override the run()  method to define the functionality of thread. We should call start()  method to start execution of a thread as a new entity, if we call run() method on a thread then it will not start a new thread. We cannot guarantee which thread will execute first even if we prioritize the threads. A thread whose run() method is executed completely reaches the dead state and cannot be invoked again. Program : Making 3 Threads using Thread Class In the following example we are making three different threads in the class Test which extends the Thread class. We just pass a parameter name to each object of Test thread to distinguish between them. class Test extends Thread{ String name; public Test(String name){ this.name = name; } public static void main(String args[]){ System.out.println("main started"); Thread t1 = new Thread(new Test("Th

Find the word with maximum occurrences in a line

Question : Count the number of occurrences of each word in a String Write a program to accept a string from the user and print the number of times each word of the string occurs in the input string. e.g If the input is "Tinkle Twinkle little star" then the output should be Twinkle  - 2 little        -1 star         -1 Program  import java.util.HashMap; import java.util.Scanner; class CountOccurances{ public static void main(String args[]){ CountOccurances obj = new CountOccurances(); System.out.println("Enter the line of String"); String max = obj.maxOccurances(new Scanner(System.in).nextLine().split(" ")); System.out.println("Word with maximum occurances = " + max); } public String maxOccurances(String[] str){ HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int itr=0;itr<str.length;itr++){ if(map.containsKey(str[itr])){ map.put(str[itr], map.get(s

Java MCQ's on Random Java

This test contains 10 questions based on Java . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Which of these is not supported by Java ? Multilevel Inheritence Multiple Inheritence Garbage Collection Data Hiding B Java does not support Multiple inheritence. It can be only achieved by making use of the Interfaces. Which of the following exceptions needs not to be in a try catch block. ClassNotFound Exception Arithmatic Exception FileNotFound Exception NoClassDefFound Exception B We do not need to write a Runtime exceptions in a try-catch block. Arithmatic Exception is an Unchecked Exception while all other are Checked Exceptio

Java MCQ's on Java

This test contains 10 questions based on Java . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Weakest access specifier among the following is public private default protected B private has the weakest access among all. Private members of a class can be accessed only within the same class. Which access specifier should be used with a class which should be available everywhere in the project. public private default protected A A class with a public access can be accessed from anywhere. Which of the following access

Program to print Numbers in Words

Question : Print a given number in Words Write a program to print a number and convert it into words. Suppose we enter a number 132 the output should be "one hundred thirty two" 5234 the output should be "five thousand two hundred thirty four" 90 the output should be "ninety" Program : Print Numbers in Words import java.util.Scanner; class NumberInWords{ String once[] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; String tens[] = {"ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"}; public static void main(String args[]){ NumberInWords obj = new NumberInWords(); System.out.println("Enter the number to be converted to words"); Scanner sc = new Scanner(System.in); System.out.println(obj.get

How to add objects in a HashMap

Points To Remember HashMap saves objects in form of key-value pair in form of Entry object (Map.Entry). We can use any object as a key on which hashCode() and equals() can be applied. We cannot use primitive datatypes as keys or values. We can have only one value corresponding to a key , other values will get overridden. A hashMap can contain a single null key . Initial size of a HashMap is 16 and its load factor is 0.75 after this HashMap gets rehashed. Program : Adding Objects to HashMap Below program shows how to save key-value pairs as entry objects in a HashMap. We use put()  method to store key-value pairs in a Hashmap. import java.util.HashMap; class Test{ public static void main(String args[]){ // Declaring and Initializing a HashMap HashMap<String, String> map = new HashMap<String, String>(); // Adding Objects TO HashMap map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key

How to Iterate over HashMap Collection in Java

Points To Remember A HashMap contains objects in key-value pair. We can use enumeration, iterator , for loop (jdk v1.5 onwards) and lamda expression ( jdk v1.8) We can add values to HashMap using put(key,value). We can get all keys by . keySet()  and value of a key using .get(key) Method 1: Traverse A HashMap using "for" loop The below example shows how we can traverse a HashMap in java using advanced for loop. import java.util.HashMap; class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5"); // Iterating Map using advanced for loop available from jdk v1.5 onwards // Iterating over Values for(String value : map.values()){ System.out.p

Java MCQ's on Fundamentals Of Java

This test contains 10 questions based on Fundamentals Of Java . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Which of the following is not a conditional statement. while if for do while B if is the conditional statement out of these all the others are the loops. Which of the following is not a keyword in java. volatile clazz private transient B clazz is not a keyword in java. Which of the following is not an Object. Integer Boolean String char D char is not an object, it is a primitive datatype. Which of these is invalid. char A = 1 char A = 'A'

How to make threads using Runnable Interface.

Points To Remember We can make threads in java by implementing Runnable Interface . Any class that implements this interface must override its run() method. The call to start()  method internally calls the run()  method of the thread. We can not guarantee which thread would be executed first. Thread Priority only promises the cpu time and not that it will be run first .  Program : How to make threads by implementing Runnable Interface In the below example we are implementing the Runnable interface and creating two threads " t1 " and " t2 " and calling the run() method using thread .start().  We run the same program twice and we might get different outputs each time as shown below. class Test implements Runnable{ String msg; public void run(){ System.out.println("Running Thread" + msg); } public Test(String msg){ this.msg = msg; } public static void main(String args[]){ System.out.println("Stating main"); Thread t1 = new Thread(new Test(&quo

How to get all Declared Fields in a Class

Points To Remember We can use reflection to find all the fields available within a class. We can get all the declared fields in a class by getDeclaredFields() . We can search for any field in a class by using getField().  It throws  NoSuchFieldException  if the field does not exist in the class. Program : Get all the declared fields in a class import java.lang.reflect.Field; class SampleClass{ String s1 = "Class variable"; int a = 123; } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Field feilds[] = obj.getDeclaredFields(clazz); for(Field feild : feilds){ System.out.println(feild); } }catch(Exception e){ e.printStackTrace(); } } public Field[] getDeclaredFields(Class clazz){ return clazz.getDeclaredFields(); } } java.lang.String SampleClass.s1 int SampleClass.a Program : Get a particular field declared in a class. import java.la

How to get all Methods available in a Class

Points To Remember We can use Reflection API to get all methods available in a class. Method class is present in java.land.reflect.Method class. We can use getDeclaredMethods() to get all the declared Methods in a class. We can use getMethods()  to get all the methods available in a class. It also includes methods from its super classes. Program : Get All Methods Declared in a Class import java.lang.reflect.Method; class SampleClass{ String s1 = "Class variable"; int a = 123; public SampleClass(){ System.out.println("SampleClass Default Constructor"); } public SampleClass(String str){ System.out.println("SampleClass Overloaded Constructor"); } public void show(){ System.out.println("SampleClass Show Method"); } public void print(){ System.out.println("SampleClass Print Method"); } } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass&qu

How to get all Constructors declared in a Class

Points To Remember We can get the constructors declared in a class using Reflection API. Constructor class is present in java.lang.reflect.Constructor  class. The  getDeclaredConstructors()  method will return an array of Constructors in a class. Program : Get all constructors declared in a class import java.lang.reflect.Constructor; class SampleClass{ String s1 = "Class variable"; int a = 123; public SampleClass(){ System.out.println("SampleClass Default Constructor"); } public SampleClass(String str){ System.out.println("SampleClass Overloaded Constructor"); } public void show(){ System.out.println("SampleClass Show Method"); } public void print(){ System.out.println("SampleClass Print Method"); } } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Constructor cc[] = obj.getConstructors(clazz); for(Constructor

Program to convert String to Integer without using Integer.parseInt()

Program : Convert a String to an Integer without using parseInt() method. We have to convert a String suppose "12345" to its equivalent integer value that is 13245 without using the parseInt() method. We need to check if the number is positive or negative and convert accordingly. import java.util.Scanner; import java.util.Scanner; class Test{ public static void main(String args[]){ System.out.println("Enter the string to be converted to integer number "); System.out.println(new Test().stringToInteger(new Scanner(System.in).next())); } public int stringToInteger(String str){ int number = 0,itr=0; boolean flag = false; if(str.charAt(0) == '-'){ flag = true; itr = 1; } for(; itr <=str.length()-1 ; itr++){ char digit = str.charAt(itr); number += Math.pow(10, str.length() - itr -1) * (digit-48); } if(flag) return -number; else return number; } } Enter the string to be

Program to check if the given number is Armstrong

Program : Find if the given number is Armstrong A number is said to be armstrong if the sum of cube of its digits is equal to the number itself. e.g. 371 is an Armstrong number, since   3^3 + 7^3 + 1^3 = 371 341 is not Armstrong number, since  3^3 + 4^3 + 1^3 = 92 import java.util.Scanner; class Armstrong{ public static void main(String args[]){ Armstrong obj = new Armstrong(); System.out.println("Enter a number to check Armstrong"); Scanner sc = new Scanner(System.in); obj.isArmstrong(sc.nextInt()); } public void isArmstrong(int n){ int sum = 0,number = n; while(n!=0){ sum += Math.pow(n%10,3); n = n/10; } if(sum == number) System.out.println("Number "+number+" is Armstrong"); else System.out.println("Number "+number+" is not Armstrong"); } } Enter a number to check Armstrong 371 Number 371 is Armstrong Here we run the while loop while(n!=0) till the

How to make Object of a class By Reflection API

Points To Remember Reflection API is a powerful technique to find out environment of a class as well as to inspect the class itself. Reflection API was introduced in Java v1.1 It allows user to get full information about the classes, interfaces, constructors, methods, variables etc. It is available in java.lang.reflect package. Example : Creating Object Using Reflection API In the example below we are trying to create the object of class "A" in class "Test" using reflection api. We will first get the class of "A" by using .class  and then call the newInstance() method to get the object of this class. class A{ public A(){ System.out.println("class A constructor"); } public void show(){ System.out.println("class A show() "); } public void show(String s){ System.out.println(s); } } public class Test{ public static void main(String args[]){ try{ Class clazz = A.class; A object = (A)clazz.ne

Java MCQ's on Method Overloading

This test contains 10 questions based on Method Overloading . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Compile time polymorphism is also known as Method Overriding Method Overloading Method Rewriting None of these B Comiple Time polymorphism means that methods with same names gets resolved at the compile time only. JVM does not have to resolve these methods at runtime. Which conditions should a method satisfy for overloading a method in a class. A.its return type should be same. B.number of parameters it takes should be different. C.type of parameters should be different. Onl

Java MCQ's on Method Overriding

This test contains 10 questions based on Method Overriding . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Compile time polymorphism is also known as Method Overriding Method Overloading Method Rewriting None of these B Comiple Time polymorphism means that methods with same names gets resolved at the compile time only. JVM does not have to resolve these methods at runtime. Which conditions should a method satisfy to override a method of parent class. A.its return type should be same. B.number of parameters it takes should be same and of same type. C.its access specifier should not be weaker than the m

Find the Sum of Even Digits of a Number

Question : Find sum of digits of number that are even. Suppose we have a number 456789 and we need to find the sum of all the digits in the number that are even or divisible by 2. e.g In number  456789 sum of even digits is 4 + 6 + 8 = 18. import java.util.Scanner; class FindSum{ public static void main(String args[]){ System.out.println("Enter the number"); Scanner sc = new Scanner(System.in); FindSum object = new FindSum(); int number = sc.nextInt(); int sum = object.findSumOfDigits(number); System.out.println("Sum of digits of "+number+" = "+ sum); } public int findSumOfDigits(int num){ int sum = 0; while(num != 0){ if((num % 10) %2 == 0) sum += num % 10; num = num / 10; } return sum; } } Enter the number 456789 Sum of digits of 456789 = 18 In the above program we take the number as input from the user by using the Scanner class and then pass this number to the method findSumOfDigits() that calculates the sum of digits of

Find the Sum of Digits of a number.

Question : Find the sum of digits of a number Suppose we have a number and we need to find the sum of digits of the number. e.g let the number be 456789, then the sum of digits will be 4 + 5 + 6 + 7 + 8 + 9 = 39 import java.util.Scanner; class FindSum{ public static void main(String args[]){ System.out.println("Enter the number"); Scanner sc = new Scanner(System.in); FindSum object = new FindSum(); int number = sc.nextInt(); int sum = object.findSumOfDigits(number); System.out.println("Sum of digits of "+number+" = "+ sum); } public int findSumOfDigits(int num){ int sum = 0; while(num != 0){ sum += num % 10; num = num / 10; } return sum; } } Enter the number 456789 Sum of digits of 456789 = 39 In the above program we take the number as input from the user by using the Scanner class and then pass this number to the method findSumOfDigits() that calculates the sum of digits of the number. The while loop runs till the number is not

Can We have a Private Constructor in Class

Points To Remember A constructor have the same name as that of a class. A constructor does not have any return type, not even void. Constructor of a class is called first, before any other method is called. Constructor of a super class is called before the base class constructor.  We can have a private constructor in a java class. A class with a private constructor can not be inherited. We cannot create object of a class with a private constructor. What happens if we have a Private Constructor in a class. Suppose if we make a private constructor of our class and try to create the object of that class from that class only. In the example below, we have a class A and we created the constructor of this class that just prints a statement. Now we created the object of this class from a main method. The code will compile and run successfully to give a output. Thus, this proofs that we can have a private constructor in a class . class A { private A(){ System.out.println("Private Co

Program to Find All paths in a Matrix of 2D array.

Problem : Find all possible paths through the array. It is only allowed to go diagonally up or down, or go to the right. An example 4x4 matrix 3 5 7 9 2 4 6 8 9 3 7 5 6 8 2 4 The numbers in the matrix can be any arbitrary value. I would like to generate all possible routes through the matrix, starting in one of the four numbers in the first column. It is only allowed to move Northeast, East, and Southeast. An example route: 3-5 7 9 \ 2 4 6-8 9 3 7 5 6 8 2 4 Solution import java.util.*; class Paths{ static int arr[][] = {{3,5,7,9},{2,4,6,8},{9,3,7,5},{6,8,2,4}}; public static void main(String args[]){ for(int itr=0; itr<arr.length; itr++){ for(String path : new Paths().findPaths(itr, 0)){ if(path.split("->").length == 4) System.out.println(path); } } } public ArrayList<String> findPaths(int row, int col){ ArrayList<String> paths = new ArrayList<String>(); if(goNorthEast(row,col)){

Java MCQ's on Fundamentals Of Java

This test contains 10 questions based on Fundamentals Of Java . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds What was the original name of Java ? Oak Pok James Coffee A Java was initially named as Oak by its founders. Who is know as the father of Java ? Ken Arnold David Holmes James Gosling Peter Dibble C James Arthur Gosling, OC (born May 19, 1955) is a Canadian computer scientist, best known as the father of the Java programming language Java Source Code is compiled into which format .java .class .exe .bytecode B Java Source code in .java format is compiled by the compiler t

Java MCQ's on Constructors

This test contains 10 questions based on Constructors . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds What is the return type of Constructors? int float void None of these D Constructors does not have any return type, not even void. Which keyword is used by method to refer to the object that invoked it? import catch this super C this  keyword is used by the method to refer to the object that invoked it. this  keyword can also be used to refer to any member that is within the class e.g instance variables , functions or even objects.   Which of the following is a method having same name as that of its class?