- Java Programming Language
- Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
- Method references provide easy-to-read lambda expressions for methods that already have a name.
- Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.
- Repeating Annotations provide the ability to apply the same annotation type more than once to the same declaration or type use.
- Type Annotations provide the ability to apply an annotation anywhere a type is used, not just on a declaration. Used with a pluggable type system, this feature enables improved type checking of your code.
- Improved type inference.
- Method parameter reflection.
- Collections
- Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.
- Performance Improvement for HashMaps with Key Collisions.
- Compact Profiles contain predefined subsets of the Java SE platform and enable applications that do not require the entire Platform to be deployed and run on small devices.
- Security
- Client-side TLS 1.2 enabled by default
- New variant of AccessController.doPrivileged that enables code to assert a subset of its privileges, without preventing the full traversal of the stack to check for other permissions
- Stronger algorithms for password-based encryption
- SSL/TLS Server Name Indication (SNI) Extension support in JSSE Server
- Support for AEAD algorithms: The SunJCE provider is enhanced to support AES/GCM/NoPadding cipher implementation as well as GCM algorithm parameters. And the SunJSSE provider is enhanced to support AEAD mode based cipher suites. See Oracle Providers Documentation, JEP 115.
- KeyStore enhancements, including the new Domain KeyStore type java.security.DomainLoadStoreParameter, and the new command option -importpassword for the keytool utility
- SHA-224 Message Digests
- Enhanced Support for NSA Suite B Cryptography
- Better Support for High Entropy Random Number Generation
- New java.security.cert.PKIXRevocationChecker class for configuring revocation checking of X.509 certificates
- 64-bit PKCS11 for Windows
- New rcache Types in Kerberos 5 Replay Caching
- Support for Kerberos 5 Protocol Transition and Constrained Delegation
- Kerberos 5 weak encryption types disabled by default
- Unbound SASL for the GSS-API/Kerberos 5 mechanism
- SASL service for multiple host names
- JNI bridge to native JGSS on Mac OS X
- Support for stronger strength ephemeral DH keys in the SunJSSE provider
- Support for server-side cipher suites preference customization in JSSE
- JavaFX
- The new SwingNode class enables developers to embed Swing content into JavaFX applications. See the SwingNode javadoc and Embedding Swing Content in JavaFX Applications.
- The new UI Controls include the DatePicker and the TreeTableView controls.
- The javafx.print package provides the public classes for the JavaFX Printing API. See the javadoc for more information.
- The WebView class provides new features and improvements. Review Supported Features of HTML5 for more information about additional HTML5 features including Web Sockets, Web Workers, and Web Fonts.
- Enhanced text support including bi-directional text and complex text scripts such as Thai and Hindi in controls, and multi-line, multi-style text in text nodes.
- Support for Hi-DPI displays has been added in this release.
- The CSS Styleable* classes became public API. See the javafx.css javadoc for more information.
- The new ScheduledService class allows to automatically restart the service.
- JavaFX is now available for ARM platforms. JDK for ARM includes the base, graphics and controls components of JavaFX.
- Tools
- The jjs command is provided to invoke the Nashorn engine.
- The java command launches JavaFX applications.
- The java man page has been reworked.
- The jdeps command-line tool is provided for analyzing class files.
- Java Management Extensions (JMX) provide remote access to diagnostic commands.
- The jarsigner tool has an option for requesting a signed time stamp from a Time Stamping Authority (TSA).
- Javac tool
- The -parameters option of the javac command can be used to store formal parameter names and enable the Reflection API to retrieve formal parameter names.
- The type rules for equality operators in the Java Language Specification (JLS) Section 15.21 are now correctly enforced by the javac command.
- The javac tool now has support for checking the content of javadoc comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated when javadoc is run. The feature is enabled by the new -Xdoclint option. For more details, see the output from running "javac -X". This feature is also available in the javadoc tool, and is enabled there by default.
- The javac tool now provides the ability to generate native headers, as needed. This removes the need to run the javah tool as a separate step in the build pipeline. The feature is enabled in javac by using the new -h option, which is used to specify a directory in which the header files should be written. Header files will be generated for any class which has either native methods, or constant fields annotated with a new annotation of type java.lang.annotation.Native.
- Javadoc tool
- The javadoc tool supports the new DocTree API that enables you to traverse Javadoc comments as abstract syntax trees.
- The javadoc tool supports the new Javadoc Access API that enables you to invoke the Javadoc tool directly from a Java application, without executing a new process. The javadoc tool now has support for checking the content of javadoc comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated when javadoc is run. The feature is enabled by default, and can also be controlled by the new -Xdoclint option. For more details, see the output from running "javadoc -X". This feature is also available in the javac tool, although it is not enabled by default there.
- Internationalization
- Unicode Enhancements, including support for Unicode 6.2.0
- Adoption of Unicode CLDR Data and the java.locale.providers System Property
- New Calendar and Locale APIs
- Ability to Install a Custom Resource Bundle as an Extension
- java.lang and java.util Packages
- Parallel Array Sorting
- Standard Encoding and Decoding Base64
- Unsigned Arithmetic Support
- JDBC
- The JDBC-ODBC Bridge has been removed.
- Networking
- The class java.net.URLPermission has been added.
- In the class java.net.HttpURLConnection, if a security manager is installed, calls that request to open a connection require permission.
- Concurrency
- Classes and interfaces have been added to the java.util.concurrent package.
- Methods have been added to the java.util.concurrent.ConcurrentHashMap class to support aggregate operations based on the newly added streams facility and lambda expressions.
- Classes have been added to the java.util.concurrent.atomic package to support scalable updatable variables.
- Methods have been added to the java.util.concurrent.ForkJoinPool class to support a common pool.
- The java.util.concurrent.locks.StampedLock class has been added to provide a capability-based lock with three modes for controlling read/write access.
- HotSpot
- Removal of PermGen.
- Default Methods in the Java Programming Language are supported by the byte code instructions for method invocation.
- Java Mission Control 5.3 Release Notes
- JDK 8 includes Java Mission Control 5.3.
TechBytes is a practical technology blog for developers and technology enthusiasts, covering programming, backend development, data engineering, cloud, DevOps, AI, software architecture, system design, and emerging technologies through practical articles, tutorials, examples, and insights.
Monday, September 7, 2026
Whats New in Java 8 ?
Access Modifiers in Method Overriding: Rules and Examples in Java
Note :-
Public is the 1st stronger access specifier
Protected is the 2nd stronger access specifier
Default is the 3rd stronger access specifier
Private is the most weaker access specifier
Always keep in mind about the access specifiers has vital role in inheritance (OOPS concept).
Example :-
class AccessTest{
protected void display(){ //Stronger Access specifier
System.out.println("Hello AccessTest:Display");
}
}
class TestWithMain extends AccessTest{
// I am trying to override with weaker specifier , it show error
// You can use public or protected (higher or same level of access specifier)
private void display(){
System.out.println("Hello TestWithMain:display");
}
public static void main(String str[]){
AccessTest acObj=new TestWithMain();
acObj.display();
}
}
Error :-
TestWithMain.java:8: display() in TestWithMain cannot override display() in AccessTest;
attempting to assign weaker access privileges; was protected
private void display(){
So, now if you change the access specifier to protected or public then it will work properly.
Changed executable code :-
public void display(){
System.out.println("Hello TestWithMain:display");
}
OR
protected void display(){
System.out.println("Hello TestWithMain:display");
}
Hope it will help you.
Static Block vs Instance Initialization Block in Java (With Example)
In Java, understanding the order of execution between static blocks and instance initialization blocks is essential for managing class-level and object-level setup.
Static Block (
static { ... }): Belongs to the class itself, not to any specific object. It executes exactly once when the class is loaded into memory by the JVM, well before any instances are constructed.Instance Initialization Block (
{ ... }): Belongs to individual object instances. It executes every time a new object is created, running immediately before the constructor body.
Code Example - InitBlockStaticBlock.java
public class InitBlockStaticBlock {
// 1. Static Initialization Block: Runs once when the class is loaded
static {
System.out.println("Executing static block (Class loaded)");
}
// 2. Instance Initialization Block: Runs once per object instantiation
{
System.out.println("Executing instance init block (Object created)");
}
public static void main(String[] args) {
System.out.println("--- Inside main method ---");
InitBlockStaticBlock obj1 = new InitBlockStaticBlock();
InitBlockStaticBlock obj2 = new InitBlockStaticBlock();
InitBlockStaticBlock obj3 = new InitBlockStaticBlock();
}
}
Output :-
Executing static block (Class loaded)
--- Inside main method ---
Executing instance init block (Object created)
Executing instance init block (Object created)
Executing instance init block (Object created)
How to Get the Day of the Week from a Date in Java
Below the code for finding the day name from an input date.import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DayFinder {
public static void main(String[] args) {
String inputDate = "01/08/2012";
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date dt1 = format1.parse(inputDate);
DateFormat format2 = new SimpleDateFormat("EEEE");
String finalDay = format2.format(dt1);
System.out.println("My Day is: " + finalDay);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:- Wednesday
Explanation :-
First I prepare a date by using SimpleDateFormat . Then Prepare a DateFormat by using that before SimpleDateFormat(format1).
EEEE is the date Format Suffix for Day.More
Modern Java Solution (java.time)
In modern Java, this is simpler, safer, and does not need Date or SimpleDateFormat:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DayFinderModern {
public static void main(String[] args) {
String inputDate = "01/08/2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(inputDate, formatter);
// Get day of the week directly
System.out.println("My Day is: " + date.getDayOfWeek());
// Or format it as full text ("Wednesday"):
// date.format(DateTimeFormatter.ofPattern("EEEE"))
}
}
Understanding Interfaces in Java: Definition, Syntax, and Implementation
Rally java has many features and scopes.But when I go for the interface ( like an important organ in the java body) , really I can not calculate the face value of interface.How much essential it is for java followers?The face value of interface is undefined.As we know that interface makes java popular.
The Term "Interface"
And it is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies inside interface. Interfaces cannot be instantiated and interfaces can only be implemented by classes or extended by other interfaces.Its a protocol of communication between objects.
How to Define an Interface ?
It is quite simple to define an interface. The modifier 'interface' is used to define an interface.The naming convention shall be follows like declaring a class.A class can implement more than one interface separated by comma.And also an interface can extends more than one interface separated by comma.And it contains only signature of the method , no implementation.
public interface SymbolInterface extends int_face1, int_face2, int_face3,int_face4 {
//Declare your member here
}
OR
public class ImplementSymbolInterface implements SymbolInterface,OtherInterfaces {
//Declare your member here
}
It is recommended to make your interface public, so that it can be used by other packages, or it can only visible to that implemented class.And you quite sure that the body of the interface is always having any number method (without method body) or closing with semicolon.Those method has no implementation inside that interface. For implementing that you may need implementation class.
Except, method an interface can contain constant declaration with few modifiers public,static and final. These method & constant declarations are completely optional, i.e. you can declare an interface without any method or any constants. And when an interface does not contain any method or constants that interface is called Marker Interface.
Note:- Yes, Marker interface is good question asked by major MNC .You can find more details about marker interface from the post A Moment with with Marker Interface in Java Development, What is Marker Interface.
How to Implement an Interface ?
Yes, this is the point that you need in your real life program. Before going to implement you have some brief idea about the term interface & its usage.
Use, implements keyword for implement the interface over a class . Follow few code below :-
Declare an interface :
public interface InterfaceSymbol {
public void symbolAdd();
public void symbolDiv();
public void symbolMul();
public void symbolSub();
}
Implement the above interface for a class :
public class SymbolImplementa implements InterfaceSymbol{
public void symbolAdd(){
System.out.println("I am In Add");
}
public void symbolSub(){
System.out.println("I am In Sub");
}
public void symbolMul(){
System.out.println("I am In Mul");
}
public void symbolDiv(){
System.out.println("I am In Div");
}
}
As per the rule you must have to override the methods of interface in the implementation class. But , remember it is not mandatory , you can avoid it by using :
1--- Adapter Class
2--- Make that implementation class as Final. ( Final is a keyword)
Here I am not describing how to avoid for overriding all methods of interface.This is beyond of this post.You follow other posts related to interface.
Also , like a class one interface can extend ( defined keyword) another interface.And the behavior of that interface will remains same.When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
This is main function where the implementation is done.
public class MainImplementationClass extends SymbolImplementa implements InterfaceSymbol{
/**
* @param args
*/
public void symbolAdd(){
System.out.println("inside ");
}
public static void main(String[] args) {
testf fobj=new testf();
SymbolImplementa impobj;
//fobj.symbolAdd();
impobj=fobj;
impobj.symbolAdd();
System.out.println("I am in Main.........");
}
}
The word of Caution.
Then you need to rewrite an interface, be careful about the pitfall. In the above example InterfaceSymbol interface is implemented by the class SymbolImplementa , but If you make few changes in the old interface , all classes that implement the old InterfaceSymbol interface will break because they don't implement the interface anymore. Programmers relying on this interface will oppose deeply.So, enjoy the flavor of interface in java programming.
Saturday, September 5, 2026
Java: JVM Inside — The Story Behind JVM (Part 2)
In the previous post, we discussed some basic concepts about the JVM and its role in the Java platform. If you haven't read it yet, you can read Java: JVM Inside — The Story Behind the JVM before continuing with this post.
In this post, let's look a little deeper into what happens inside the JVM and some of the important runtime areas used while a Java application is running.
From Java Source Code to Bytecode
Java source code is compiled by the Java compiler (javac) into bytecode. The bytecode is stored in .class files.
A Java application may contain many classes, so multiple .class files can be packaged together into a JAR (Java Archive) file for easier distribution.
The Java application launcher, java, can be used to start a Java application. The JVM loads the required classes and executes the bytecode.
A JVM may interpret bytecode and can also use Just-In-Time (JIT) compilation to compile frequently executed code into native machine code at runtime. This allows the JVM to optimize application execution while the program is running.
There are also other approaches, such as Ahead-of-Time (AOT) compilation, which can compile code ahead of execution for particular environments.
JVM Runtime Areas
The JVM specification defines several runtime data areas. Some are created for each thread, while others are shared by threads. Important areas include:
Program Counter (PC) Register
JVM Stack
Heap
Method Area
Runtime Constant Pool
Native Method Stack
The JVM specification defines these runtime areas as part of the JVM architecture.
Bytecode Verification
Before bytecode is executed, the JVM performs verification as part of the class loading and linking process.
Bytecode verification helps ensure that class files satisfy the structural and type-safety requirements expected by the JVM.
For example, verification helps check that:
Instructions are used correctly.
Type information is used consistently.
Branches and control-flow information are valid.
Access-control rules are respected.
The JVM specification describes verification as part of the linking process.
JVM Stack
Each JVM thread has its own JVM stack.
The JVM stack contains frames, and a new frame is created when a method is invoked. A frame contains information such as local variables, an operand stack, and information used for dynamic linking.
For example:
Thread
|
+-- JVM Stack
|
+-- Frame for main()
|
+-- Frame for methodA()
|
+-- Frame for methodB()
When a method completes, its frame is removed from the stack.
The JVM specification defines JVM stacks and frames as important parts of the runtime environment.
Heap
The heap is the runtime data area from which memory for objects and arrays is allocated.
For example:
Employee employee = new Employee();
When the new operation creates an Employee object, the object is allocated in the heap.
Java does not require developers to manually free this object using a free() operation as in languages such as C or C++. Instead, Java uses Garbage Collection (GC) to automatically reclaim heap memory that is no longer reachable by the application.
Garbage collection is one of the important features of the Java runtime.
A simple way to visualize this is:
JVM
|
+-- Heap
| |
| +-- Object 1
| +-- Object 2
| +-- Array
|
+-- JVM Stack
|
+-- Local variables
+-- Object references
It is common to explain that an object reference can be held in a stack frame while the actual object is located in the heap. However, the exact implementation details of references and memory placement are JVM-implementation dependent, so this should be treated as a conceptual model rather than a strict physical-memory rule.
Arrays in Java are objects, so they are also managed as heap objects.
Method Area
The Method Area is a JVM runtime data area that is shared among threads.
It stores per-class structures such as the runtime representation of classes, methods, fields, and other class-related information.
The method area is not simply a place where "all bytecode is stored." Class files are loaded and linked by the JVM, and the JVM maintains the runtime representation required for execution.
The JVM specification defines the Method Area conceptually, while the exact implementation is JVM-specific.
Runtime Constant Pool
Each class or interface has a runtime constant pool associated with it.
It contains information derived from the constant pool in the class file, including constants and symbolic references used by the class.
The runtime constant pool is important for operations such as dynamic linking.
Final Thoughts
The JVM is much more than a simple program that executes .class files.
It provides a complete runtime environment for loading classes, verifying bytecode, managing memory, executing methods, handling threads, performing garbage collection, and optimizing frequently executed code.
Understanding these JVM runtime areas helps Java developers understand what happens behind the scenes when a Java application runs.
Java: JVM Inside — The Story Behind the JVM
The JVM (Java Virtual Machine) is a core component of the Java platform. JVM stands for Java Virtual Machine.
The JVM is software that provides an execution environment for running Java bytecode. It acts as an abstraction layer between Java bytecode and the underlying operating system and hardware.
Java source code is first compiled into bytecode, which is stored in .class files. The JVM then loads and executes this bytecode.
A simple way to understand the process is:
Java Source Code → Java Compiler (javac) → Bytecode → JVM → Operating System / HardwareThe important point is that the same Java bytecode can generally run on different operating systems as long as a compatible JVM implementation is available.
This is one of the key ideas behind Java's well-known WORA (Write Once, Run Anywhere) concept.
For example, the same .class file can be executed using a compatible JVM on different platforms:
Java Source File (.java)
|
|
Java Compiler
(javac)
|
|
Bytecode (.class)
|
+------------+------------+
| | |
JVM JVM JVM
| | |
Windows Linux macOS
The JVM specification defines how Java class files and bytecode are handled, while JVM implementations provide the actual runtime environment for a particular platform.
Why is JVM important?
The JVM provides several important capabilities, including:
Loading and executing Java class files
Managing memory and runtime data areas
Garbage collection
Bytecode verification
Exception handling
Supporting Java's platform-independent execution model
Providing runtime services needed by Java applications
The JVM specification defines areas such as the heap, JVM stacks, method area, runtime constant pool, and native method stacks.
Therefore, the JVM is one of the fundamental components that makes the Java platform portable across different operating systems and hardware environments.
JAVA: Implementing the Singleton Design Pattern for Creating a Single Instance with Example
Implementing the Singleton Design Pattern helps in creating only a single instance of a class. Below is a simple example for better understanding.
Class with Main Function
// Class with Main function for calling Singleton class
public class TestSingleTon {
public static void main(String[] args) {
SingleTonClass classInstance = SingleTonClass.getInstance();
System.out.println(
"My SingleTon member value is=" + classInstance.testval
);
}
}
Singleton Class
// Singleton class
public class SingleTonClass {
// Create an instance
private static SingleTonClass my_instance = new SingleTonClass();
// Private constructor
private SingleTonClass() {
// Private Constructor here
// Does not allow an object to be created outside this class
}
// Method to access the instance
public static SingleTonClass getInstance() {
return my_instance;
}
// Member variable
int testval = 10;
// If the comment is removed from the below line,
// the program will not compile.
// SingleTonClass s1 = new SingleTonClass();
}
Output
The output of this program is:
My SingleTon member value is=10
This is a simple implementation of the Singleton Design Pattern that ensures only one object is created.
There are also other ways to implement the Singleton Design Pattern, such as lazy initialization, thread-safe implementation, and handling Singleton instances across multiple JVMs.
Thursday, September 3, 2026
Find Duplicate Strings in a List Using Java | Java Interview Question
In this article, we will see how to find duplicate strings and their counts from an array or a list using Java. This is one of the common programming questions asked in technical interviews.
In this program, we will use both Map and List, so it is also a good example for understanding Java Collections. You can find a few more Java Collection interview questions.
Today, we will see how to find duplicate strings in a list and count how many times each string is repeated.
Logic
The logic is quite simple:
First, we create a Map to store the key-value pair. The key will be the array element, and the value will be the number of times that element occurs.
Then, we iterate through the array or list and add each element to the Map. If the element is already present in the Map, we increase its count by 1.
After completing the iteration, the Map will contain each string along with the number of times it occurs.
Finally, we iterate through the Map and check for entries where the count is greater than 1. These are the duplicate or repeated strings.
CountDuplicate.java
package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(
Arrays.asList("JDG", "AA", "AA", "JAVA", "JavaScript", "Java", "Stream", "hibernate", "Hibernate"));
System.out.println("Input List = " + list);
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.isEmpty()) {
map.put(list.get(i).toUpperCase(), 1);
} else if (map.containsKey(list.get(i).toUpperCase())) {
map.put(list.get(i).toUpperCase(), map.get(list.get(i).toUpperCase()) + 1);
} else {
map.put(list.get(i).toUpperCase(), 1);
}
}
int counter = 0;
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
counter++;
System.out.println("String Found " + entry.getKey() + " with count " + entry.getValue());
}
}
System.out.println("Total Duplicate String - " + counter);
}
}
Output
Input List = [JDG, AA, AA, JAVA, JavaScript, Java, Stream, hibernate, Hibernate] String Found: AA with count 2 String Found: JAVA with count 2 String Found: HIBERNATE with count 2 Total Duplicate Strings: 3
Happy Learning!
Saturday, July 13, 2019
Find Palindrome Strings in an Array Using Java
PalindromeStrings.java
package com.techbyteslearn.lab.basic; /** * This program illustrates how to find palindrome strings from an array. */ public class PalindromeStrings { public static void main(String[] args) { String[] stringArray = { "eye", "jdg", "javadevelopersguide", "aabaa", "hello", "pip" }; for (int i = 0; i < stringArray.length; i++) { printOnlyPalindrome(stringArray[i]); } } private static void printOnlyPalindrome(String str) { String oldString = str; StringBuilder builder = new StringBuilder(str); if (builder.reverse().toString().equals(oldString)) { System.out.println(oldString + " is a Palindrome String."); } } }Output:
eye is a Palindrome String. aabaa is a Palindrome String. pip is a Palindrome String.
Happy Learning.Find All Palindrome Numbers from an Array in Java
FindAllPalindrome.java
package com.techbyteslearn.lab.basic;
public class FindAllPalindrome {
public static void main(String[] args) {
int numberArray[] = { 120, 990, 121, 777, 808, 1280 };
for (int i = 0; i < numberArray.length; i++) {
printOnlyPalindrom(numberArray[i]);
}
}
private static void printOnlyPalindrom(int number) {
int finalNumber = 0;
int oldNumber = number;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and oldNumber both are same or not.
if (finalNumber == oldNumber)
System.out.println(finalNumber + " is a Palindrome.");
}
}
121 is a Palindrome.
777 is a Palindrome.
808 is a Palindrome.
How to Check Whether a Number Is a Palindrome in Java
Palindrome.java
package com.techbyteslearn.lab.basic; public class Palindrome { public static void main(String[] args) { int number = 121; int temp = number; int finalNumber = 0; // Repeat the loop until the number becomes zero. while (number != 0) { // Get the last digit. int lastDigit = number % 10; // Build the reversed number. finalNumber = (finalNumber * 10) + lastDigit; // Remove the last digit from the number. number = number / 10; } // Compare the reversed number with the original number. if (finalNumber == temp) { System.out.println("This number is a Palindrome."); } else { System.out.println("This number is not a Palindrome."); } } }
Output:
This number is a Palindrome. One important correction from the original comments: % 10 gets the last digit, not the first digit. Also, number has already become 0 by the time of the final comparison, so comparing with temp is the correct approach.
Thursday, July 11, 2019
Find Duplicate Values in a List Using Java
The logic is very simple here, see the below.
- At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
- Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
- Finally we will have the map , which holds the array elements with the counter for repentance.
- Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).
DuplicateFinder.java
package com.techbyteslearn.lab.basic; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class DuplicateFinder { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>( Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90)); System.out.println("Input List Data = " + list); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < list.size(); i++) { if (map.isEmpty()) { map.put(list.get(i), 1); } else if (map.containsKey(list.get(i))) { map.put(list.get(i), map.get(list.get(i)) + 1); } else { map.put(list.get(i), 1); } } System.out.println("\nDuplicate values are: "); // Iterate the Map and display the duplicate values. for (Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey()); // TODO: We can now put these values into any list. } } } }Output:
Input List Data = [4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90] Duplicate values are: 4 5 25Note- One small point: because
HashMapdoes not guarantee iteration order, the order of4,5, and25in the output can vary.
Happy Learning.