Basic Java Programs
- Java
program to check palindrome
Java palindrome program: Java program to check
if a string is a palindrome or not. Remember a string is a palindrome if it
remains unchanged when reversed, for example "dad" is a palindrome as
reverse of "dad" is "dad" whereas "program" is
not a palindrome. Some other palindrome strings are "mom",
"madam", "abcba".
Java programming source code
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
Another method to check palindrome:
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);
System.out.println("Input a string");
inputString = in.nextLine();
int length = inputString.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
}
}
- Java if else program
Java if else program uses if else to execute statement(s) when a condition is fulfilled. Below is a simple program which explains the usage of if else in java programming language.Java programming if else statement
// If else in Java codeimport java.util.Scanner;
class IfElse {public static void main(String[] args) {int marksObtained, passingMarks;
passingMarks = 40;
Scanner input = new Scanner(System.in);
System.out.println("Input marks scored by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {System.out.println("You passed the exam.");}else {System.out.println("Unfortunately you failed to pass the exam.");}}}Output of program:
Above program ask the user to enter marks obtained in exam and the input marks are compared against minimum passing marks. Appropriate message is printed on screen based on whether user passed the exam or not. In the above code both if and else block contain only one statement but we can execute as many statements as required.Nestd If Else statements
You can use nested if else which means that you can use if else statements in any if or else block.import java.util.Scanner;
class NestedIfElse {public static void main(String[] args) {int marksObtained, passingMarks;char grade;
passingMarks = 40;
Scanner input = new Scanner(System.in);
System.out.println("Input marks scored by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
if (marksObtained > 90)grade = 'A';else if (marksObtained > 75)grade = 'B';else if (marksObtained > 60)grade = 'C';elsegrade = 'D';
System.out.println("You passed the exam and your grade is " + grade);}else {grade = 'F';System.out.println("You failed and your grade is " + grade);}}}Java for loop
Java for loop used to repeat execution of statement(s) until a certain condition holds true.for
is a keyword in Java programming language.Java for loop syntax
for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {// Statements to execute i.e. Body of for loop}You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.// Infinite for loopfor (;;) {System.out.println("Java programmer");}You can terminate an infinite loop by pressing Ctrl+C.Simple for loop example in Java
Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.//Java for loop programclass ForLoop {public static void main(String[] args) {int c;
for (c = 1; c <= 10; c++) {System.out.println(c);}}}Java for loop example to print stars in console
Following star pattern is printed * ** *** **** *****class Stars {public static void main(String[] args) {int row, numberOfStars;
for (row = 1; row <= 10; row++) {for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {System.out.print("*");}System.out.println(); // Go to next line}}}Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.Java while loop
Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:while (condition(s)) { // Body of loop }1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.2. You can test multiple conditions such aswhile ( a > b && c != 0) {// Loop body}Loop body is executed till value of a is greater than value of b and c is not equal to zero.3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable.Java while loop example
Following program asks the user to input an integer and prints it until user enter 0 (zero).import java.util.Scanner;
class WhileLoop {public static void main(String[] args) {int n;
Scanner input = new Scanner(System.in);System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {System.out.println("You entered " + n);System.out.println("Input an integer");}
System.out.println("Out of loop");}}Above program can be written in a more compact way as follows:// Java while loop user inputimport java.util.Scanner;
class WhileLoop {public static void main(String[] args) {int n;
Scanner input = new Scanner(System.in);System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {System.out.println("You entered " + n);System.out.println("Input an integer");}}}Java while loop break program
Here we write above program but uses break statement. The condition in while loop here is always true so we test the user input and if its is zero then we use break to exit or come out of the loop.import java.util.Scanner;
class BreakWhileLoop {public static void main(String[] args) {int n;
Scanner input = new Scanner(System.in);
while (true) {System.out.println("Input an integer");n = input.nextInt();
if (n == 0) {break;}System.out.println("You entered " + n);}}}Java while loop break continue program
import java.util.Scanner;
class BreakContinueWhileLoop {public static void main(String[] args) {int n;
Scanner input = new Scanner(System.in);
while (true) {System.out.println("Input an integer");n = input.nextInt();
if (n != 0) {System.out.println("You entered " + n);continue;}else {break;}}}}Whatever you can do with while loop can be done with for and do while loop.Java program to print alphabets
This program print alphabets on screen i.e a, b, c, ..., z. Here we print alphabets in lower case.Java source code
class Alphabets
{public static void main(String args[]){char ch;
for( ch = 'a' ; ch <= 'z' ; ch++ )System.out.println(ch);}}print multiplication table
This java program prints multiplication table of a number entered by the user using afor
loop. You can modify it forwhile
ordo while
loop for practice.Java programming source code
import java.util.Scanner;
class MultiplicationTable
{public static void main(String args[]){int n, c;System.out.println("Enter an integer to print it's multiplication table");Scanner in = new Scanner(System.in);n = in.nextInt();System.out.println("Multiplication table of "+n+" is :-");
for ( c = 1 ; c <= 10 ; c++ )System.out.println(n+"*"+c+" = "+(n*c));}}Using nested loops we can print tables of number between a given range say a to b, For example if the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:import java.util.Scanner;
class Tables
{public static void main(String args[]){int a, b, c, d;
System.out.println("Enter range of numbers to print their multiplication table");Scanner in = new Scanner(System.in);
a = in.nextInt();b = in.nextInt();
for (c = a; c <= b; c++) {System.out.println("Multiplication table of "+c);
for (d = 1; d <= 10; d++) {System.out.println(c+"*"+d+" = "+(c*d));}}}}How to get input from user in java
This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed on the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statementScanner a = new Scanner(System.in);
Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :- 1) nextInt to input an integer 2) nextFloat to input a float 3) nextLine to input a stringJava programming source code
import java.util.Scanner;
class GetInputFromUser
{public static void main(String args[]){int a;float b;String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");s = in.nextLine();System.out.println("You entered string "+s);
System.out.println("Enter an integer");a = in.nextInt();System.out.println("You entered integer "+a);
System.out.println("Enter a float");b = in.nextFloat();System.out.println("You entered float "+b);}}Java program to add two numbers
Java program to add two numbers :- Given below is the code of java program that adds two numbers which are entered by the user.Java programming source code
import java.util.Scanner;
class AddNumbers
{public static void main(String args[]){int x, y, z;System.out.println("Enter two integers to calculate their sum ");Scanner in = new Scanner(System.in);x = in.nextInt();y = in.nextInt();z = x + y;System.out.println("Sum of entered integers = "+z);}}Above code can add only numbers in range of integers(4 bytes), if you wish to add very large numbers then you can use BigInteger class. Code to add very large numbers:import java.util.Scanner;import java.math.BigInteger;
class AddingLargeNumbers {public static void main(String[] args) {String number1, number2;Scanner in = new Scanner(System.in);
System.out.println("Enter first large number");number1 = in.nextLine();
System.out.println("Enter second large number");number2 = in.nextLine();
BigInteger first = new BigInteger(number1);BigInteger second = new BigInteger(number2);BigInteger sum;
sum = first.add(second);
System.out.println("Result of addition = " + sum);}}In our code we create two objects of BigInteger class in java.math package. Input should be digit strings otherwise an exception will be raised, also you cannot simply use '+' operator to add objects of BigInteger class, you have to use add method for addition of two objects.Output of program:Enter first large number
11111111111111Enter second large number
99999999999999Result of addition = 111111111111110Java program to find odd or even
This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operator to find remainder in our program.Java programming source code
import java.util.Scanner;
class OddOrEven
{public static void main(String args[]){int x;System.out.println("Enter an integer to check if it is odd or even ");Scanner in = new Scanner(System.in);x = in.nextInt();
if ( x % 2 == 0 )System.out.println("You entered an even number.");elseSystem.out.println("You entered an odd number.");}}import java.util.Scanner;
class EvenOdd
{public static void main(String args[]){int c;System.out.println("Input an integer");Scanner in = new Scanner(System.in);c = in.nextInt();
if ( (c/2)*2 == c )System.out.println("Even");elseSystem.out.println("Odd");}}There are other methods for checking odd/even one such method is using bitwise operator.Java program to convert Fahrenheit to Celsius
Java program to convert Fahrenheit to Celsius: This code does temperature conversion from Fahrenheit scale to Celsius scale.Java programming code
import java.util.*;
class FahrenheitToCelsius {public static void main(String[] args) {float temperatue;Scanner in = new Scanner(System.in);
System.out.println("Enter temperatue in Fahrenheit");temperatue = in.nextInt();
temperatue = ((temperatue - 32)*5)/9;
System.out.println("Temperatue in Celsius = " + temperatue);}}For Celsius to Fahrenheit conversion use T = 9*T/5 + 32 where T is temperature on Celsius scale. Create and test Fahrenheit to Celsius program yourself for practice.Java methods
Java methods tutorial: Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will learn about Java methods. Methods are known as functions in C and C++ programming languages. A method has a name and return type. Main method is a must in a Java program as execution begins from it.Syntax of methods
"Access specifier" "Keyword(s)" "return type" methodName(List of arguments) { // Body of method }Access specifier can be public or private which decides whether other classes can call a method. Kewords are used for some special methods such as static or synchronized. Return type indicate return value which method returns. Method name is a valid Java identifier name.Access specifier, Keyword and arguments are optional.Examples of methods declaration: public static void main(String[] args); void myMethod(); private int maximum(); public synchronized int search(java.lang.Object);Java Method example program
class Methods {
// Constructor method
Methods() {System.out.println("Constructor method is called when an object of it's class is created");}
// Main method where program execution begins
public static void main(String[] args) {staticMethod();Methods object = new Methods();object.nonStaticMethod();}
// Static method
static void staticMethod() {System.out.println("Static method can be called without creating object");}
// Non static method
void nonStaticMethod() {System.out.println("Non static method must be called by creating an object");}}Java methods list
Java has a built in library of many useful classes and there are thousands of methods which can be used in your programs. Just call a method and get your work done :) . You can find list of methods in a class by typing following command on command prompt:javap package.classnameFor example javap java.lang.String // list all methods and constants of String class. javap java.math.BigInteger // list constants and methods of BigInteger class in java.math packageJava String methods
String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class.Java string class program
class StringMethods
{public static void main(String args[]){int n;String s = "Java programming", t = "", u = "";
System.out.println(s);
// Find length of string
n = s.length();System.out.println("Number of characters = " + n);
// Replace characters in string
t = s.replace("Java", "C++");System.out.println(s);System.out.println(t);
// Concatenating string with another string
u = s.concat(" is fun");System.out.println(s);System.out.println(u);}}Java static block program
Java programming language offers a block known as static which is executed before main method executes. Below is the simplest example to understand functioning of static block later we see a practical use of static block.Java static block program
class StaticBlock {public static void main(String[] args) {System.out.println("Main method is executed.");}
static {System.out.println("Static block is executed before main method.");}}Static block can be used to check conditions before execution of main begin, Suppose we have developed an application which runs only on Windows operating system then we need to check what operating system is installed on user machine. In our java code we check what operating system user is using if user is using operating system other than "Windows" then the program terminates.class StaticBlock {public static void main(String[] args) {System.out.println("You are using Windows_NT operating system.");}
static {String os = System.getenv("OS");if (os.equals("Windows_NT") != true) {System.exit(1);}}}We are using getenv method of System class which returns value of environment variable name of which is passed an as argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, 7, 8 and others.Java static method
Java static method program: static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.Java static method example program
class Languages {public static void main(String[] args) {display();}
static void display() {System.out.println("Java is my favorite programming language.");}}Java constructor tutorial with code examples
Constructor java tutorial: Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. It is optional to write constructor method in a class but due to their utility they are used.Java constructor example
class Programming {//constructor methodProgramming() {System.out.println("Constructor method called.");}
public static void main(String[] args) {Programming object = new Programming(); //creating object}}This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed.Java constructor overloading
Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objects. See constructor overloading example:class Language {String name;
Language() {System.out.println("Constructor method called.");}
Language(String t) {name = t;}
public static void main(String[] args) {Language cpp = new Language();Language java = new Language("Java");
cpp.setName("C++");
java.getName();cpp.getName();}
void setName(String t) {name = t;}
void getName() {System.out.println("Language name: " + name);}}Java program to swap two numbers
This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below.Swapping using temporary or third variable
import java.util.Scanner;
class SwapNumbers
{public static void main(String args[]){int x, y, temp;System.out.println("Enter x and y");Scanner in = new Scanner(System.in);
x = in.nextInt();y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;x = y;y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);}}Swapping without temporary variable
import java.util.Scanner;
class SwapNumbers
{public static void main(String args[]){int x, y;System.out.println("Enter x and y");Scanner in = new Scanner(System.in);
x = in.nextInt();y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
x = x + y;y = x - y;x = x - y;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);}}For other methods to swap: C programming code to swap using bitwise XOR. Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.Java program to find largest of three numbers
This java program finds largest of three numbers and then prints it. If the entered numbers are unequal then "numbers are not distinct" is printed.Java programming source code
import java.util.Scanner;
class LargestOfThreeNumbers
{public static void main(String args[]){int x, y, z;System.out.println("Enter three integers ");Scanner in = new Scanner(System.in);
x = in.nextInt();y = in.nextInt();z = in.nextInt();
if ( x > y && x > z )System.out.println("First number is largest.");else if ( y > x && y > z )System.out.println("Second number is largest.");else if ( z > x && z > y )System.out.println("Third number is largest.");elseSystem.out.println("Entered numbers are not distinct.");}}Java program to find factorial
This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.Java programming code
import java.util.Scanner;
class Factorial
{public static void main(String args[]){int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )System.out.println("Number should be non-negative.");else{for ( c = 1 ; c <= n ; c++ )fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);}}}Java program for calculating factorial of large numbers
Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and cant be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.import java.util.Scanner;import java.math.BigInteger;
class BigFactorial
{public static void main(String args[]){int n, c;BigInteger inc = new BigInteger("1");BigInteger fact = new BigInteger("1");
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");n = input.nextInt();
for (c = 1; c <= n; c++) {fact = fact.multiply(inc);inc = inc.add(BigInteger.ONE);}
System.out.println(n + "! = " + fact);}}We run the above java program to calculate 100 factorial and following output is obtained.Input an integer
100100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000Java program print prime numbers
This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2.Java programming code
import java.util.*;
class PrimeNumbers
{public static void main(String args[]){int n, status = 1, num = 3;
Scanner in = new Scanner(System.in);System.out.println("Enter the number of prime numbers you want");n = in.nextInt();
if (n >= 1){System.out.println("First "+n+" prime numbers are :-");System.out.println(2);}
for ( int count = 2 ; count <=n ; ){for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ){if ( num%j == 0 ){status = 0;break;}}if ( status != 0 ){System.out.println(num);count++;}status = 1;num++;}}}Java program to check armstrong number
This java program checks if a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 4, 5, 9, 153, 371, 407, 8208 etc.Java programming code
import java.util.Scanner;
class ArmstrongNumber
{public static void main(String args[]){int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);System.out.println("Input a number to check if it is an Armstrong number");n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {digits++;temp = temp/10;}
temp = n;
while (temp != 0) {remainder = temp%10;sum = sum + power(remainder, digits);temp = temp/10;}
if (n == sum)System.out.println(n + " is an Armstrong number.");elseSystem.out.println(n + " is not an Armstrong number.");}
static int power(int n, int r) {int c, p = 1;
for (c = 1; c <= r; c++)p = p*n;
return p;}}Java program to reverse a string
This java program reverses a string entered by the user. We use charAt method to extract characters from the string and append them in reverse order to reverse the entered string.Java programming code
import java.util.*;
class ReverseString
{public static void main(String args[]){String original, reverse = "";Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);}}Reverse string using StringBuffer class
class InvertString
{public static void main(String args[]){StringBuffer a = new StringBuffer("Java programming is fun");System.out.println(a.reverse());}}StringBuffer class contains a method reverse which can be used to reverse or invert an object of this class.Java program to check palindrome
Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. Some other palindrome strings are "mom", "madam", "abcba".Java programming source code
import java.util.*;
class Palindrome
{public static void main(String args[]){String original, reverse = "";Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )reverse = reverse + original.charAt(i);
if (original.equals(reverse))System.out.println("Entered string is a palindrome.");elseSystem.out.println("Entered string is not a palindrome.");
}}Another method to check palindrome:import java.util.*;
class Palindrome
{public static void main(String args[]){String inputString;Scanner in = new Scanner(System.in);
System.out.println("Input a string");inputString = in.nextLine();
int length = inputString.length();int i, begin, end, middle;
begin = 0;end = length - 1;middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {if (inputString.charAt(begin) == inputString.charAt(end)) {begin++;end--;}else {break;}}if (i == middle + 1) {System.out.println("Palindrome");}else {System.out.println("Not a palindrome");}}}Both the above codes consider string as case sensitive, you can modify them so that they ignore the case of string. You can either convert both strings to lower or upper case for this. But do not modify original strings as they may be further required in program.Java program to compare two strings
This program compare strings i.e test whether two strings are equal or not, compareTo method of String class is used to test equality of two String class objects. compareTo method is case sensitive i.e "java" and "Java" are two different strings if you use compareTo method. If you wish to compare strings but ignoring the case then use compareToIgnoreCase method.Java programming code
import java.util.Scanner;
class CompareStrings
{public static void main(String args[]){String s1, s2;Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");s1 = in.nextLine();
System.out.println("Enter the second string");s2 = in.nextLine();
if ( s1.compareTo(s2) > 0 )System.out.println("First string is greater than second.");else if ( s1.compareTo(s2) < 0 )System.out.println("First string is smaller than second.");elseSystem.out.println("Both strings are equal.");}}Java program for linear search
Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesn't contain the element we are searching.Java programming code
import java.util.Scanner;
class LinearSearch
{public static void main(String args[]){int c, n, search, array[];
Scanner in = new Scanner(System.in);System.out.println("Enter number of elements");n = in.nextInt();array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)array[c] = in.nextInt();
System.out.println("Enter value to find");search = in.nextInt();
for (c = 0; c < n; c++){if (array[c] == search) /* Searching element is present */{System.out.println(search + " is present at location " + (c + 1) + ".");break;}}if (c == n) /* Searching element is absent */System.out.println(search + " is not present in array.");}}Java program for binary search
Java program for binary search: This code implements binary search algorithm. Please note input numbers must be in ascending order.Java programming code
import java.util.Scanner;
class BinarySearch
{public static void main(String args[]){int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);System.out.println("Enter number of elements");n = in.nextInt();array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)array[c] = in.nextInt();
System.out.println("Enter value to find");search = in.nextInt();
first = 0;last = n - 1;middle = (first + last)/2;
while( first <= last ){if ( array[middle] < search )first = middle + 1;else if ( array[middle] == search ){System.out.println(search + " found at location " + (middle + 1) + ".");break;}elselast = middle - 1;
middle = (first + last)/2;}if ( first > last )System.out.println(search + " is not present in the list.\n");}}Java program to find all substrings of a string
Java program to find substrings of a string :- This program find all substrings of a string and the prints them. For example substrings of "fun" are :- "f", "fu", "fun", "u", "un" and "n". substring method of String class is used to find substring. Java code to print substrings of a string is given below.Java programing code
import java.util.Scanner;
class SubstringsOfAString
{public static void main(String args[]){String string, sub;int i, c, length;
Scanner in = new Scanner(System.in);System.out.println("Enter a string to print it's all substrings");string = in.nextLine();
length = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < length ; c++ ){for( i = 1 ; i <= length - c ; i++ ){sub = string.substring(c, c+i);System.out.println(sub);}}}}Java program to display date and time, print date and time using java program
Java date and time program :- Java code to print or display current system date and time. This program prints current date and time. We are using GregorianCalendar class in our program. Java code to print date and time is given below :-Java programming code
import java.util.*;
class GetCurrentDateAndTime
{public static void main(String args[]){int day, month, year;int second, minute, hour;GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);month = date.get(Calendar.MONTH);year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);minute = date.get(Calendar.MINUTE);hour = date.get(Calendar.HOUR);
System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);System.out.println("Current time is "+hour+" : "+minute+" : "+second);}}
No comments:
Post a Comment