Showing posts with label Java Program. Show all posts
Showing posts with label Java Program. Show all posts

Points To Remember

You can convert the number from decimal to any base by dividing the number by the base till the number is either 0 or less than the base it self and counting the remainders in a reverse order.

Program : Convert the base of a Decimal Number

import java.util.Scanner;

class ConvertBase{

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Original NUmber");
int originalNumber = sc.nextInt();

System.out.println("Enter the base for conversion");
int base = sc.nextInt();

String convertedNumber = new ConvertBase().convert(originalNumber,base);

System.out.println("Original Number = "+originalNumber);
System.out.println("Converted NUmber = "+convertedNumber);
}



public String convert(int original, int base){
String number = "";
String converted ="";

while(original != 0){
int digit = original % base;
original /= base;
number += digit;
}
for(int itr=number.length()-1;itr>=0; itr--)
converted += number.charAt(itr);
return converted;
}

}
The above program will give the following output
Enter the Original NUmber
45
Enter the base for conversion
5
Original Number  = 45
Converted NUmber = 140
You can convert a decimal number to any base with this code.

Points To Remember

  • An annotation can be used as a replacement of interfaces.
  • You can make both empty/marker annotations and annotations with methods.
  • You can define the retention policy for the annotation and where the annotation can be used.

Program : Create A Custom Annotation

The following program creates a custom empty annotation.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {

public String name() default "table";
}

The above class can be used as a custom annotation with only one method name with a default value. This annotation can be applied only to the class i.e it is class level annotation and can not be applied to any member of a class.

The following program creates a custom annotation with methods defined.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
public String name() default "";
}
In the above example the annotation @Column can be applied only to the fields of a class and not at class level or method level.

@Table(name="user_table")
public class User {

@Column(name="ekiras")
private String username;
 public String password;
}
The above code represents how we can use the annotations @Table and @Column to annotate in any pojo class like the class User mentioned above.
public class RunTest {

public static void main(String args[]){
test();

}

public static void test(){
Table table = User.class.getAnnotation(Table.class);
if(table!=null){
System.out.println("Class is annotated with @Table and name="+table.name());
Field[] fields = User.class.getFields();
for(Field field : fields){
Column column = field.getAnnotation(Column.class);
if(column!=null)
System.out.println("Field "+field.getName() +" annotated with @Column name="+column.name());
else {
System.out.println("Field "+field.getName() +" is not annotated with @Column");
}
}
}
}

}
Class is annotated with @Table and name=user_table
Field username annotated with @Column name=ekiras
Field password is not annotated with @Column



Points To Remember

  • You to need to add the Reflections jar in the class path. 
  • You will not be able to load the packages other than the current package using Package.getPackages() since current class loader will not be able to reach them.

Program : Scan all packages with a Prefix

You can use Package.getPackages() approach to find all the packages that are in the current class loader. But you will not be able to get the packages that are not in the class path of the current class loader. So you need to include the jar "Reflections" to do this for you.
All the dependency to the project via pom.xml or you can add the jar in the class path of the project.

The following code will list all the packages in the project that start with the prefix in the project.

 public static Set<String> findAllPackagesStartingWith(String prefix) {
List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false), new ResourcesScanner())
.setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(prefix))));
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Set<String> packageNameSet = new TreeSet<String>();
for (Class<?> classInstance : classes) {
String packageName = classInstance.getPackage().getName();
if (packageName.startsWith(prefix)) {
packageNameSet.add(packageName);
}
}
for(String t : packageNameSet){
System.out.println(":::"+t);
}
return packageNameSet;
}

If you want the packages in the project in the form of Package class you can do
public Set<Package> findAllPackagesStartingWith(String prefix) {
List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false), new ResourcesScanner())
.setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(prefix))));
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Set<Package> packageNameSet = new TreeSet<Package>();
for (Class<?> classInstance : classes) {
if (classInstance.getPackage().getName().startsWith(prefix)) {
packageNameSet.add(classInstance.getPackage());
}
}

return packageNameSet;
}
When we run the above code in a demo java project and call the function as findAllPackagesStartingWith("java"); we will get a output like the following. The output may differ for you depending upon the packages in your project.
package = javassist
package = javassist.bytecode
package = javassist.bytecode.analysis
package = javassist.bytecode.annotation
package = javassist.bytecode.stackmap
package = javassist.compiler
package = javassist.compiler.ast
package = javassist.convert
package = javassist.expr
package = javassist.runtime
package = javassist.scopedpool
package = javassist.tools
package = javassist.tools.reflect
package = javassist.tools.rmi
package = javassist.tools.web
package = javassist.util
package = javassist.util.proxy
package = javax.annotation
package = javax.annotation.concurrent
package = javax.annotation.meta
package = javax.xml.parsers
package = javax.xml.transform
package = javax.xml.transform.dom
package = javax.xml.transform.sax
package = javax.xml.transform.stream

Points To Remember

  • To make a class Singleton the class must satisfy the following points
    • No class should be able to make the object of this class.
    • Only one object of this class must me there that is used by all the other classes.
  • The class must have a private constructor so that no class should be able to make object of this class.
  • Class should make a final object of the class itself and return it whenever asked for.
  • Class should have a static method that returns the object of this class.

Demo : Create a Singleton Class

Class : Singleton.java
public class Singleton{

private String name = "Singleton Object";
private static final Singleton object = new Singleton();

private Singleton(){
}

public static Singleton getObject(){
return object;
}

public String getName(){
return name;
}

}
Class : SingletonTest.java
class SingletonTest{

public static void main(String args[]){
Singleton obj = Singleton.getObject();
System.out.println(obj.getName());
}

}
The output of the following program will be
Singleton Object

No matter how many times you try to get the object of this class, you will always get the same object. Also you can not alter the object since it is final. This type of design pattern can be used to do stuffs like
  • Loading configuration files.
  • Loading credentials
  • Provide constant services to the application.

Points To Remember

Program : Flatten a Nested List 

Here we write a Java function that will accept a nested ist upto any level of nesting and flatten this list.
import java.util.List;
import java.util.LinkedList;
import java.util.Scanner;

class FlattenList{

public static void main(String args[]){

CreateList obj = new CreateList();

// Get the nested list sample
List<Object> nestedList = obj.createNestedList();
System.out.println("-----------------------------------");

// Print the nested list
System.out.println("Nested List = " + nestedList);
// Print the sample nested list after flattening the list
System.out.println("Flatten List = " + new FlattenList().flattenList(nestedList));

}

public List<Integer> flattenList(List<Object> nestedList){
List<Integer> flatList = new LinkedList<Integer>();
for(Object obj : nestedList){
if(obj instanceof List) // If the value is a List
for(Integer integer : flattenList((List)obj)) // traverse the returned list and add it to the list.
flatList.add(integer);
if(obj instanceof Integer) // If the value is an integer number add it to list
flatList.add((Integer)obj);
}
return flatList;
}

}
The above program will give the following output
Enter the Nested List
[1,2,3,[4,5],6,[7,[8,9]],10,[11,[12,[13,[14,15],16]]]]
-----------------------------------
Nested List = [1, 2, 3, [4, 5], 6, [7, [8, 9]], 10, [11, [12, [13, [14, 15], 16]]]]
Flatten List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Algorithm

  1. We traverse the List from start to end.
  2. At each element we check if the element is a List or Integer.
    1. If it is a Integer we add it to the output list.
    2. If it is a list we use recursion to flatten this list.
Using the above steps any level of nested list can be flatten.

Points To Remember

  • The Correct Datatype for creating a Nested List will be List<Object>, because we have to store either a integer number or a list inside the list.
  • We can not have a nested list like List<List<Integer>> because it will not be able to hold the integer values. It can only hold a list.
  • The List we create can be nested to any level.

Program : Create A nested list upto any level

Here we suppose that we get a String input of the list that we have to create. The following program accepts the list as a String and returns after converting the list to a nested list up to any level.
import java.util.*;
import java.util.LinkedList;
import java.util.Scanner;

public class CreateList{

public static void main(String args[]){
CreateList obj = new CreateList();
System.out.println(obj.createNestedList());
}

public List<Object> createNestedList(){

Scanner sc = new Scanner(System.in);
System.out.println("Enter the Nested List");

// Take input from the user
String inputString = sc.next();

List<Object> nestedList = new LinkedList<Object>();
String num=""; // Strore the number as String
for(int itr=1; itr<inputString.length()-1;itr++){
char c = inputString.charAt(itr);
if(c == ','){ // If the char is , then add the number to list
if(!num.equals("")) // Check if the number is not null or ""
nestedList.add(Integer.parseInt(num));
num= "";
}
else if(c != '[' && c != ']') // If the character is a digit add it to number
num += c;
else if(c == '[') // If [ is encountered, add it to list
nestedList.add(c);
else if(c == ']'){ // If ] is encountered, pop all elements till last [ and add to list.
if(!num.equals(""))
nestedList.add(Integer.parseInt(num));
num= "";
List<Object> temp = new LinkedList<Object>(nestedList.subList(nestedList.lastIndexOf('[')+1,nestedList.size()));
nestedList = nestedList.subList(0,nestedList.lastIndexOf('['));
nestedList.add(temp);
}
}
if(!num.equals("")) // If last digit is not added to list, add it
nestedList.add(Integer.parseInt(num));
return nestedList;
}
}
The above program gives the following output.
Enter the Nested List
[1,2,3,[4,5],6,[7,[8,9]],10]
[1, 2, 3, [4, 5], 6, [7, [8, 9]], 10]
If we add a print statement just before the end of the for loop we will see the following output.
[]
[1]
[1]
[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3, []
[1, 2, 3, []
[1, 2, 3, [, 4]
[1, 2, 3, [, 4]
[1, 2, 3, [4, 5]]
[1, 2, 3, [4, 5]]
[1, 2, 3, [4, 5]]
[1, 2, 3, [4, 5], 6]
[1, 2, 3, [4, 5], 6, []
[1, 2, 3, [4, 5], 6, []
[1, 2, 3, [4, 5], 6, [, 7]
[1, 2, 3, [4, 5], 6, [, 7, []
[1, 2, 3, [4, 5], 6, [, 7, []
[1, 2, 3, [4, 5], 6, [, 7, [, 8]
[1, 2, 3, [4, 5], 6, [, 7, [, 8]
[1, 2, 3, [4, 5], 6, [, 7, [8, 9]]
[1, 2, 3, [4, 5], 6, [7, [8, 9]]]
[1, 2, 3, [4, 5], 6, [7, [8, 9]]]
[1, 2, 3, [4, 5], 6, [7, [8, 9]]]
[1, 2, 3, [4, 5], 6, [7, [8, 9]]]
[1, 2, 3, [4, 5], 6, [7, [8, 9]], 10]

Algorithm Followed

  • Step 1 : Iterate over the String , you can encounter digit, comma, or brackets [ and ].
    • If a digit is encountered add it to String number, this is used to store digits that are greater than 10.
    • If  , is encountered add the number to list and reset value of number.
    • If [ is encountered add it to the list.
    • if ] is encountered
      • Add number to list if it is not null.
      • Pop all elements till [ is encountered and add it to a temp list
      • Add temp list to the list.


Points To Remember

Program : Test CAS Rest Api from a Java Code

You can use the following piece of code to test the CAS Rest API.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

public class TestCASRest {


public static void main(String... args) throws Exception
{
String username ="ekansh@ekiras.com";
String password ="password";
validateFromCAS(username,password);
}

public static boolean validateFromCAS(String username, String password) throws Exception
{

String url = "https://ekansh:8443/cas/v1/tickets";
try
{
HttpsURLConnection hsu = (HttpsURLConnection)openConn(url);
String s = URLEncoder.encode("username","UTF-8") + "=" + URLEncoder.encode(username,"UTF-8");
s+="&" +URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode(password,"UTF-8");

System.out.println("string s = "+s);
OutputStreamWriter out = new OutputStreamWriter(hsu.getOutputStream());
BufferedWriter bwr = new BufferedWriter(out);
bwr.write(s);
bwr.flush();
bwr.close();
out.close();

String tgt = hsu.getHeaderField("location");
System.out.println( hsu.getResponseCode());
if(tgt != null && hsu.getResponseCode() == 201)
{
System.out.println(tgt);

System.out.println("Tgt is : " + tgt.substring( tgt.lastIndexOf("/") +1));
tgt = tgt.substring( tgt.lastIndexOf("/") +1);
bwr.close();
closeConn(hsu);


String serviceURL = "http://ekansh:8090/";
String encodedServiceURL = URLEncoder.encode("service","utf-8") +"=" + URLEncoder.encode(serviceURL,"utf-8");
System.out.println("Service url is : " + encodedServiceURL);



String myURL = url+ "/"+ tgt ;
System.out.println(myURL);
hsu = (HttpsURLConnection)openConn(myURL);
out = new OutputStreamWriter(hsu.getOutputStream());
bwr = new BufferedWriter(out);
bwr.write(encodedServiceURL);
bwr.flush();
bwr.close();
out.close();

System.out.println("Response code is: " + hsu.getResponseCode());

BufferedReader isr = new BufferedReader( new InputStreamReader(hsu.getInputStream()));
String line;
System.out.println( hsu.getResponseCode());
while ((line = isr.readLine()) != null) {
System.out.println( line);
}
isr.close();
hsu.disconnect();
return true;

}
else
{
return false;
}


}
catch(MalformedURLException mue)
{
mue.printStackTrace();
throw mue;

}
catch(IOException ioe)
{
ioe.printStackTrace();
throw ioe;
}





}


static URLConnection openConn(String urlk) throws MalformedURLException, IOException
{

URL url = new URL(urlk);
HttpsURLConnection hsu = (HttpsURLConnection) url.openConnection();
hsu.setDoInput(true);
hsu.setDoOutput(true);
hsu.setRequestMethod("POST");
return hsu;


}


static void closeConn(HttpsURLConnection c)
{
c.disconnect();
}


}
You will get the following type of response if everything is working fine.
string s = username=admin%40gmail.com&password=igdefault
201
https://ekansh:8443/cas/v1/tickets/TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Tgt is : TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Service url is : service=http%3A%2F%2Fekansh%3A8090%2F
https://ekansh:8443/cas/v1/tickets/TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Response code is: 200
200
ST-3-Uagfse2pVB7hR5GL09WB-ekansh
If the authentication fails at the server then you will get a response like the following
string s = username=ekansh%40ekiras.com&password=pwd
400
TGT - It is the token by the ticket granting token.
ST-3-Uagfse2pVB7hR5GL09WB-ekansh - It is the service token.

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("Thread t1"));
Thread t2 = new Thread(new Test("Thread t2"));
Thread t3 = new Thread(new Test("Thread t3"));
t1.start();
t2.start();
t3.start();

System.out.println("main ended");

}

@Override
public void run(){
System.out.println(name);
}

}
Running the program for the first time.
main started
Thread t1
Thread t3
Thread t2
main ended
Running the program for the second time.
main started
main ended
Thread t2
Thread t1
Thread t3
Running the program for the third time.
main started
main ended
Thread t1
Thread t3
Thread t2
The above outputs confirms that we cannot guarantee the execution of any thread. Any thread may execute first.
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(str[itr]) +1);
}else{
map.put(str[itr],1);
}
}
String word = null;
int max = 0;
for(String token : map.keySet()){
System.out.println("word = " + token + " occurrences = " + map.get(token) );
if(map.get(token) > max){
max = map.get(token);
word = token;
}
}
return word;
}
}
Enter the line of String
this is a random text from a text book with unknown text
word = with occurrences = 1
word = text occurrences = 3
word = is occurrences = 1
word = a occurrences = 2
word = book occurrences = 1
word = random occurrences = 1
word = unknown occurrences = 1
word = from occurrences = 1
word = this occurrences = 1
Word = with maximum occurances = text
Logic : Concept to be used
We will make use of HashMap and use String as the key and Integer as value to store the number of times each word occurs in a given line. Now we need to add each word of the line to the HashMap and count the number of occurrences of each word.

We will traverse the line of string and add each word to HashMap. Before adding the word to the HashMap we will check if the word already exists in the map
  • if it exists -  then we will increment the occurrence of the word by increasing its value by 1.
  • if does not exist - then we will add the word to the map and add its value as 1.
Now, we will traverse through the map and find the word with the maximum number of occurrences.
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.getNumber(sc.next()));

}

public String getNumber(String num){
String words="";
int digit = Integer.parseInt(num.charAt(0)+"");

switch(num.length())
{
case 3:
return words = once[digit] + " hundered "+ getNumber(num.substring(1));
case 2:
if(Integer.parseInt(num) % 10 != 0){
return words = tens[digit-1] + getNumber(num.substring(1));
}else{
return words = tens[digit-1];
}
case 1:
if(digit != 0)
return words += " " + once[digit];
default:
return words += getNumber(num.substring(0,num.length()-3)) + " thousand " + getNumber(num.substring(num.length()-3)) ;
}
}

}
Enter the number to be converted to words
456
four hundered fifty six
Enter the number to be converted to words
789456
seven hundered eighty nine thousand four hundered fifty six
Enter the number to be converted to words
50
fifty
Logic : Important Points To Remember
We will need to have the numbers 1-9 in words in an array. We will also need the numbers like 10,20 up to 90 in words. We need them because they are the root words that can be used to print numbers in words. Using these we can generate a large range of numbers in words.
  • Now, if the have a number string of length 1 i.e. "case 1" this means that the number is of one digit only and we can print its value from array "once[]".
  • If the length of the number string is 2 i.e. "case 2" this means this number is between 10 to 99. Now we check if the number is divisible by 10 or not.
    • if number is divisible by 10 like 20, 80 etc, we will get the words from the array "tens[]".
    • if number is not divisible by 10 like 55,72 etc, we will print tens's digit from array "tens[]" and once digit from array "once[]".
  • If the length of the number is 3 we print the number's hundred's digit from array "once[]" add "hundred" and then call the method recursively.
  • For the numbers greater than 9999 we will print the numbers as 1000's and then proceed to the normal cases stated above. In this case we divide the number in two parts, e.g for number 123456 we divide the number 123 and 456, the first part prints "one hundred twenty three" then adds "thousand" and then adds the second part "four hundred fifty six". This makes our complete number.
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.println(value);
}

// Iterating over Keys
for(String key : map.keySet()){
System.out.println(key + " " + map.get(key));
}


}

}
value 1
value 2
value 3
value 4
value 5
key 1 value 1
key 2 value 2
key 3 value 3
key 4 value 4
key 5 value 5

Method 2: Iterate a HashMap using Iterator 
In the below method we declare an iterator "itr" and then check if the iterator has next entry element, if it has then .hasnext() returns true and itr.next() gives the next entry element.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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 Iterator
Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String, String> entry = itr.next();
System.out.println(entry.getKey() + " " + entry.getValue());

}


}

}
key 1   value 1
key 2 value 2
key 3 value 3
key 4 value 4
key 5 value 5
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.lang.reflect.Field;

class SuperClass{
public String abc = "super class";

}

class SampleClass extends SuperClass{

public String s1 = "Class variable";
public int a = 123;

}

class Test{

public static void main(String args[]){
Test obj = new Test();
try{
Class clazz = Class.forName("SampleClass");
Field feild = obj.getField(clazz, "abc");
System.out.println(feild);
}catch(Exception e){
e.printStackTrace();
}

}

public Field getField(Class clazz, String field) throws NoSuchFieldException{
return clazz.getField(field);
}

}
public java.lang.String SuperClass.abc
We can only get the public fields declared in a class using this method. In case we try to access the private or default fields of the class, we will get a NoSuchFieldException.
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");
Method declaredMethods[] = obj.getDeclaredMethods(clazz);
for(Method method : declaredMethods){
System.out.println(method);
}
}catch(Exception e){
e.printStackTrace();
}

}

public Method[] getDeclaredMethods(Class clazz){
return clazz.getDeclaredMethods();
}



}
public void SampleClass.show()
public void SampleClass.print()
Program : Get All Declared and Inherited Methods of 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");
Method allMethods[] = obj.getAllMethods(clazz);
for(Method method : allMethods){
System.out.println(method);
}
}catch(Exception e){
e.printStackTrace();
}

}

public Method[] getAllMethods(Class clazz){
return clazz.getMethods();
}



}
public void SampleClass.show()
public void SampleClass.print()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
Difference between the getDeclaredMethods() and getMethods() is that getDeclaredMethods() will return all the methods that are declared within the class while getMethods() will return all the methods that are declared in the class and all the methods that this class inherits from its super classes.
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 constructor : cc){
System.out.println(constructor);
}
}catch(Exception e){
e.printStackTrace();
}

}

public Constructor[] getConstructors(Class clazz){
return clazz.getDeclaredConstructors();
}

}
public SampleClass()
public SampleClass(java.lang.String)
The above example shows how we can get all the constructors that are declared within a class. We first get the Class of the class and then call the getDeclaredConstructors() methods to get an array of all declared constructors.
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 converted to integer number 
12345
12345

Enter the string to be converted to integer number
-12345
-12345
In the above program we traverse the string from first to last and find the power of 10 that is equal to the number of digits that are to the right of it and multiply it by the digit itself. For example
9     = 10^0 * 9 = 9
87   = 10^1*8 + 10^0*7 = 87
751 = 10^2*7 + 10^1*5 + 10^0*1 = 751
But when the number is negative i.e starts with a '-' sign, we find the number in the same form but change the sign of the number at the end.
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 value of n does not becomes zero. In the loop we find the last digit of the number by n%2 and add the cube of the digit to the sum. At last if the sum is equal to the sum of cubes of digit we say the number is armstrong.

sum = 0 digit = 1 number = 371
sum = 1 digit = 7 number = 37
sum = 344 digit = 3 number = 3
sum = 371 digit = 0 number = 0
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 the number. The while loop runs till the number is not zero.
In the while loop we add the last digit of the number to the sum and divide the number by 10 all we need to do extra is to check if the digit is divisible by 2, if yes then we add it to the sum or else we do not.. What happens is
456789 % 10(gives 9), if condition fails so we do not add it to the sum and num = 456789 / 10 = 45678 (since num is integer)
45678 % 10(gives 8), condition satisfies so we add it to sum, sum = 0 + 8 = 8 and num = 45678 / 10 = 4567 and so on.

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 zero. In the while loop we add the last digit of the number to the sum and divide the number by 10. What happens is

sum += 456789 % 10(gives 9), so sum = 0 + 9 = 9 and num = 456789 / 10 = 45678 (since num is integer)
sum += 45678 % 10(gives 8), so sum = 9 + 8 = 17 and num = 45678 / 10 = 4567
and so on.

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)){
paths.add(arr[row][col]+"->"+arr[row-1][col+1]);
for(String path : findPaths(row-1,col+1)){
paths.add(arr[row][col]+"->" + path);
}
}
if(goEast(row,col)){
paths.add(arr[row][col]+"->"+arr[row][col+1]);
for(String path : findPaths(row,col+1)){
paths.add(arr[row][col]+"->" + path);
}
}
if(goSouthEast(row,col)){
paths.add(arr[row][col]+"->"+arr[row+1][col+1]);
for(String path : findPaths(row+1,col+1)){
paths.add(arr[row][col]+"->" + path);
}
}
return paths;
}

public boolean goNorthEast(int row, int col){
if(row-1<0 || col+1 >= arr.length)
return false;
return true;
}

public boolean goEast(int row, int col){
if(col+1 >= arr.length)
return false;
return true;
}

public boolean goSouthEast(int row, int col){
if(row+1 >=arr.length || col+1 >= arr.length)
return false;
return true;
}


}
3->5->7->9
3->5->7->8
3->5->6->9
3->5->6->8
3->5->6->5
3->4->7->9
3->4->7->8
3->4->6->9
3->4->6->8
3->4->6->5
3->4->7->8
3->4->7->5
3->4->7->4
2->5->7->9
2->5->7->8
2->5->6->9
2->5->6->8
2->5->6->5
2->4->7->9
2->4->7->8
2->4->6->9
2->4->6->8
2->4->6->5
2->4->7->8
2->4->7->5
2->4->7->4
2->3->6->9
2->3->6->8
2->3->6->5
2->3->7->8
2->3->7->5
2->3->7->4
2->3->2->5
2->3->2->4
9->4->7->9
9->4->7->8
9->4->6->9
9->4->6->8
9->4->6->5
9->4->7->8
9->4->7->5
9->4->7->4
9->3->6->9
9->3->6->8
9->3->6->5
9->3->7->8
9->3->7->5
9->3->7->4
9->3->2->5
9->3->2->4
9->8->7->8
9->8->7->5
9->8->7->4
9->8->2->5
9->8->2->4
6->3->6->9
6->3->6->8
6->3->6->5
6->3->7->8
6->3->7->5
6->3->7->4
6->3->2->5
6->3->2->4
6->8->7->8
6->8->7->5
6->8->7->4
6->8->2->5
6->8->2->4
Program : Factorial Using Recursion
class Factorial{

public static void main(String args[]){
int number = Integer.parseInt(args[0]);
System.out.println("Factorial of " + number + " = " + factorial(number));
}

public static int factorial(int n){

// Check if the number is greater than equal to 0.
// because factorial of a number < 0 is undefined.

if(n == 1)
return 1;

return n * factorial(n-1);

}

}
Factorial of 5 = 120

Here the function factorial for
  • number =1 will return  1
  • number =2 will return  2 * factorial(1)  = 2 * 1 = 2
  • number =3 will return  3 * factorial(2)  = 3 * 2 * factorial(1) =  3 * 2 * 1 = 6