Posts

Showing posts with the label Core Java

Java this keyword - Example

The ' this ' keyword in Java is a keyword that can be used inside a class method or constructor. The 'this' keyword works as the reference to the current object, whose method or constructor is being invoked. You can use the 'this' keyword to reference any member of the current object inside an instance method or constructor. Following are the ways to use the ' this ' keyword in java: 1. Using ' this ' keyword to refer to current class instance variables 2. Using  this () to invoke the current class constructor 3. Using  ' this '  keyword to return the current class instance 4. Using  ' this '  keyword as a method parameter 5. Using  ' this '  keyword to invoke the current class method 6. Using  ' this '  keyword as an argument in the constructor call Using 'this' keyword to refer to current class instance variables //Java code for using 'this' keyword to //refer current class instance variables publ

Java - Find Largest and Smallest word in a String

Image
In this section, we will show you how to find longest word in as given String in Java . 1.  Using For loop 2. Using  Java 8 Streams Find Largest Word: Using For loop public class Main { public static void main ( String [] args) { String inputString = "Java is an awesome programming language" ; String [] strArray = inputString .split( " " ); String maxlengthWord = "" ; for ( int i = 0 ; i < strArray . length ; i ++){ if ( strArray [ i ].length() > maxlengthWord .length()){ maxlengthWord = strArray [ i ]; } } System . out .println( maxlengthWord ); } } Here the logic is simple, First, declare the string as a string literal. Using the split() method, split the string based on whitespace. It returns an array of strings. Declare an empty string; later, we use it to accumulate the longest word. Iterate over the string array and check whether the length of the [

Java Program to Find Maximum Occurring Character in a String

Image
In this section, we will show you how to find m aximum occurring character in a string . 1.  Using For loop and Map 2.  Using For loop 3.  Using Java 9 chars() method 4. Using  Java 8 Streams Example 1. Using For loop and Map Note:  We may have more than one character with the same maximum  occurence . This program will print all the character with maximum  occurence .   import java.util.Collections ; import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String string = "java awesome dude" ; char chars [] = string .toCharArray(); Map < Character , Integer > occurrences = new HashMap<>(); for ( Character character : chars ) { Integer oldCount = occurrences .get( character ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( character , oldCount + 1 ); } int maxValue =( Collections