Skip to content

How do you print the highest and smallest number of ASCII value in string java

I found it, thank u mate. I actually too confuse yesterday, till i forget everything that i learnt. So here is my code, what do you think?

I just don’t know why my minChar not working when i delete this code :

if(stringValue.charAt(i) != 32){
    public class MyString {
        public static void main(String[] args) {
            String stringValue = "Hello World";
            SearchMyString str = new SearchMyString(stringValue);
    class SearchMyString{
        private char maxChar;
        private char minChar;
        String stringValue;
        int ascii;
        public SearchMyString(String stringValue){
            this.stringValue = stringValue;
        char getMinChar(String stringValue, int n){
            minChar = 'z';
            for(int i = 0;i<n-1;i++){
                    if(stringValue.charAt(i) != 32){
                    minChar = stringValue.charAt(i);
                    ascii = (int)stringValue.charAt(i);
            return minChar;
        public void stringInfo(){
            int size = stringValue.length();

            System.out.println("Smallest char : "+getMinChar(stringValue,size) + "tASCII : " + ascii);



Use this method:

public static char getMaxChar(String a){
       char max = a.charAt(0); 
        for (int i=0; i<a.length(); i++){
            if ((a.charAt(i) > max)){ 
                max = a.charAt(i);  
        return max; 

Test case:




So what did we change?

For starters, if we are trying to get the character in the String that has the highest char int value, we don’t need n. We are looping through the String, so all we need is the length, which can already be supplied by the .length() method.

To call the method, just do:

SearchMyString search = new SearchMyString();

EDIT: So to make the method more reliable, instead of automatically setting max to 'A', we can set it to the first char of a (e.g, a.charAt(0))

User contributions licensed under: CC BY-SA
10 People found this is helpful