Skip to main content

Posts

Showing posts from February, 2020

Array in Java

In this post we’ll talk about one of the programming construct; Array in Java . Topics covered are how to declare an array, how to create and initialize an array, how to store elements in an array and how to access those elements using array indexes, types of arrays in Java. Array in Java Array in Java is a fundamental programming construct that holds a fixed number of values of a single type . For every type there is a corresponding array type so you can have array of any primitive data type like int, double, char etc. as well as an array of objects like String, BigInteger or any user defined object. Array elements are stored in contiguous memory locations, in case of primitive types values are stored in those locations, for an array of objects array holds reference to those objects. Each item in an array is called an element, and each element is accessed by its numerical index. Index numbering begins with 0. If there are n elements in an array, you can access them using

How to Reverse a Number in Java

In this post we’ll see how to reverse a number in Java. The Java program to reverse a number can be written in both iterative as well as recursive way. Both solutions are given here. Logic for both of the method is similar; you need to do a modulo division by 10 to get the last digit and using that remainder you need to create the reversed number. In iterative method this will be done in a loop where as in a recursive method you will call the method again after removing the last digit. Java code to reverse a number – Iterative and Recursive public class ReverseNumber { public static void main(String[] args) { int reverseNum = numberReverse(145); System.out.println("Reversed number is " +reverseNum); System.out.println("------------------"); reverseNum = numberReverseRecursive(1997, 0); System.out.println("Reversed number is (recursive) " +reverseNum); } private static int numberReverse(int number){ int reverseNum = 0;

Display Prime Numbers in Java

This post shows how you can generate and display prime numbers in Java in the given range. A number is a prime number if can be divided either by 1 or by the number itself. So every number with in the given range has to be divided starting from 2 till number/2 in the loop. You only need to run your loop from 2 to N/2 (where N is the passed number), reason being no number is completely divisible by a number more than its half. Java code to display prime numbers within the given range import java.util.Scanner; public class DisplayPrime { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter start number for displaying prime numbers - "); int start = sc.nextInt(); // Since 1 and 0 are not considered prime if(start == 0 || start == 1){ start = 2; } System.out.println("Enter end number for displaying prime numbers - "); int end = sc.nextInt(); for(int i = start; i <=

Fibonacci Series Java Program

In this post we’ll see a Java program to display Fibonacci series. Fibonacci series is a series of natural number where next number is the sum of previous two numbers i.e. fn = fn-1 + fn-2. For example 0, 1, 1, 2, 3, 5, 8, 13, 21 ...... Java program for displaying Fibonacci series can be written using- Recursive logic. See example . Non-recursive logic. See example . Fibonacci series program using recursion logic import java.util.Scanner; public class FibonacciSeries { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //user input System.out.println("Enter length of the Fibonacci series: "); int num = sc.nextInt(); for(int i = 0; i < num; i++){ System.out.print(displayFibonacci(i) + " "); } } private static int displayFibonacci(int num){ if(num == 0){ return 0; } if(num == 1){ return 1; } // sum of previous two numbers - calling recursively r

How to Convert String to int in Java

To convert String to int in Java you can use one of the following options- Integer.parseInt(String str) method which returns the passed String as int. Integer.valueOf(String str) method which returns the passed String as Integer. Java example to convert String to int using Integer.parseInt() public class StringToInt { public static void main(String[] args) { String str = "12"; try{ int num = Integer.parseInt(str); System.out.println("value - " + num); // can be used in arithmetic operations now System.out.println(num+"/3 = " + num/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); } } } Output value - 12 12/3 = 4 Java example to convert String to int using Integer.valueOf public class StringToInt { public static void main(String[] args) { String str = "12"; try{ Integer num = Integer.valueOf(str);

How to Convert String to float in Java

To convert String to float in Java you can use one of the following options- Float.parseFloat(String str) - Returns a new float initialized to the value represented by the specified String. Float.valueOf(String s) - Returns a Float object holding the float value represented by the argument string s. As you can see parseFloat() method returns a float primitive where as valueOf() method returns a Float object. Java example to convert String to float using Float.parseFloat public class StringToFloat { public static void main(String[] args) { String str = "56.45f"; try{ float f = Float.parseFloat(str); System.out.println("value - " + f); // can be used in arithmetic operations now System.out.println(f+"/3 = " + f/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } } Output value - 56.45 56.45/3 = 18.816668 Fo

How to Convert int to String in Java

This post shows several ways to convert int to String in Java. Table of contents Convert using Integer.toString() method Convert using String.valueOf() method Converting using String concatenation Converting using append method of StringBuilder or StringBuffer class Convert using Integer.toString() method Wrapper class Integer has a toString() method that returns a String object representing the passed integer. Using this method you can convert int to String in Java. public class IntToString { public static void main(String[] args) { int val = 35; String strVal = Integer.toString(val); System.out.println("Converted String value = " + strVal); } } Output Converted String value = 35 Convert using String.valueOf() method String.valueOf(int i) - Returns the string representation of the int argument. public class IntToString { public static void main(String[] args) { int val = -35; String strVal = String.valueOf(val); Sy

Spring Boot and Dependency Injection

Dependency injection in Spring Boot is no different from the dependency injection in Spring framework . You can use any of the standard Spring Framework techniques to define your beans and their injected dependencies. SpringBoot suggests using @ComponentScan (to find your beans) and using @Autowired (to do constructor injection). Spring Boot Dependency Injection Example We’ll create a simple Spring Boot stand alone application to show Spring Boot dependency injection. For a stand alone application you need to add dependency for spring-boot-starter apart from the dependency for spring-boot-starter-parent. Maven Dependencies <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.knpcode</groupId> <artifactId>

Spring Boot Starters

In a project generally there are dependencies on third party libraries and looking for the correct version jar or dependency descriptors manually is a tedious process. Spring Boot which promises Rapid Application Development provides you a one-stop shop for all the Spring and related technologies that you need through Spring Boot starters . Starters in Spring Boot Starters are a set of convenient dependency descriptors that you can include in your application. The starter for any technology contains all the related dependencies to get that technology integrated with your project. Once you include correct starter in your application, Spring Boot ensures that all the required dependencies for the selected starter are in your classpath. For example if you want to create a web application include spring-boot-starter-web which gets all dependencies for building web (including RESTful) applications using Spring MVC. This starter even includes Tomcat as the default embedded conta

Spring Boot Hello World Application

In this tutorial we’ll see how to create your first Spring Boot Hello World web application using Eclipse and Maven. Creating Maven project In Eclipse select File-New-Maven Project to create a Maven project. In the “New Maven Project” window check “Create a simple project (skip archetype selection)” and click Next. In the next window provide Group Id and Artifact Id values and click Finish. GroupId - This is an Id of project's group. This ID uniquely identifies the group that may have many sub-projects. For example com.knpcode.spring may contain other projects related to Spring. ArtifactId - This is an Id of the project. This ID uniquely identifies a project, for example SpringXML. GroupId + ArtifactId defines the artifact's location with in the repository for example com.knpcode.spring.SpringXML That will create a Maven project structure. You may need to change the Java version as Maven Project may add Java SE5 as default, you can do it using build path