These are the valid strings:
A string of length 0 – accept through q0.
A string of length 1 – accept through q1.
A string of length 2 – accept through q2.
A string of length 3 – accept through q3.
A string of length 4 – accept through q4.
A string of length 5 – accept through q5.
String of length > 5 should be rejected through a dead state or failure state. A failure state is designated as q0.
Designing DFA step by step:
Step -1:
String length less than or equal to 5 are accept to length 0 is also accept. So “q0” is also accepts.

Step -2:
String length of 1 is also accepted of ‘0’ or ‘1’. Create transition of input alphabet ‘1’ or ‘0’ from state “q0” to state “q1“.



Step -3:
After this length of string is 1 and 2 length is also accept. So, send input alphabet ‘0’ and ‘1’ from state “q1” to state “q2“.



Step -4:
Repeat the above step it gets the string length less than five. As less than five is the accept table so make the states “q0, q1, q2, q3, q4, q5” be the final state.



Transition table of above DFA:



In the above table, -> represents the initial state and * represents the final state. In this post, the initial and final state is the same which is the final state.
Code:
Main.java
import java.util.Scanner; public class less_than_5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); String str = sc.nextLine(); stateA(str); } private static void stateA(String str) { if(str.length() <= 5){ System.out.println("String Accepted"); } else { if(str.charAt(0)=='0') stateB(str.substring(1)); else stateB(str.substring(1)); } } private static void stateB(String str) { if(str.length() == 0){ System.out.println("String not accepted"); } else { if(str.charAt(0)=='0') stateB(str.substring(1)); else stateB(str.substring(1)); } } }
Output:
Enter the string 1010101 String not accepted
Recommended:
- DFA for number of 0’s divisible by five and 1’s divisible by 3
- DFA for Number of 1’s is even/odd and number of 0’s is even/odd
- Number of 1’s is a multiple of 3 on {0,1} using DFA
- Introduction to Finite Automata
- Deterministic Finite Automata (DFA)
- Number of 1’s is not multiple of 3 on {0,1} using DFA
- Automata Theory and Formal Languages
- Kleene Closure
- Recursive Definition of a Language
- Finite Representation of language