Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
2K views

Java Programming Examples

This document provides examples of various Java programming concepts like displaying messages, printing integers using for loops, if/else control flow, command line arguments, Hello World program, if/else statements, for loops, while loops, arrays, user input, adding numbers, checking odd/even numbers, converting temperatures, using static blocks and methods, multiple classes, constructors, and exception handling. The examples range from simple programs printing messages to more complex programs demonstrating various Java features like loops, conditionals, methods, classes and exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

Java Programming Examples

This document provides examples of various Java programming concepts like displaying messages, printing integers using for loops, if/else control flow, command line arguments, Hello World program, if/else statements, for loops, while loops, arrays, user input, adding numbers, checking odd/even numbers, converting temperatures, using static blocks and methods, multiple classes, constructors, and exception handling. The examples range from simple programs printing messages to more complex programs demonstrating various Java features like loops, conditionals, methods, classes and exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Java programming examples

Example 1: Display message on computer screen.


class First {
public static void main(String[] arguments) {
System.out.println("Let's do something using Java technology.");
}
}

Output of program:

Example 2: Print integers


class Integers {
public static void main(String[] arguments) {
int c; //declaring a variable
/* Using for loop to repeat instruction execution */

for (c = 1; c <= 10; c++) {


System.out.println(c);
}

Output:

If else control instructions:


class Condition {
public static void main(String[] args) {
boolean learning = true;
if (learning) {
System.out.println("Java programmer");
}
else {
System.out.println("What are you doing here?");
}
}

Output:

Command line arguments:


class Arguments {
public static void main(String[] args) {
for (String t: args) {
System.out.println(t);
}
}
}

Hello world Java program :- Java code to print hello world.

Java programming source code


class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}

Download Hello world program class file.


"Hello World" is passed as an argument to println method, you can print
whatever you want. There is also a print method which doesn't takes the cursor to
beginning of next line as println does. System is a class, out is object of
PrintStream class and println is the method.
Output of program:

Java programming if else statement


// If else in Java code
import 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:

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 program
class ForLoop {
public static void main(String[] args) {
int c;

}
}

for (c = 1; c <= 10; c++) {


System.out.println(c);
}

Output of program:

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.

Output of program:

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");
}

Output of program:

Java source code


class Alphabets
{
public static void main(String args[])
{
char ch;
for( ch = 'a' ; ch <= 'z' ; ch++ )
System.out.println(ch);
}

You can easily modify the above java program to print alphabets in upper case.
Download Alphabets program class file.

Output of program:

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));
}

Download Multiplication table program class file.

Output of program:

Java 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);

Download User input program class file.

Output of program:

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);
}
}

Download Add numbers program class file.

Output of program:

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.");
else
System.out.println("You entered an odd number.");

Download Odd or even program class file.


Output of program:

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);
}

Download Fahrenheit to Celsius program class file.


Output of 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.");
}
}

Output of program:

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.");
}

Output of program:

Java static method vs instance method


Instance method requires an object of its class to be created before it can be called
while static method doesn't require object creation.
class Difference {
public static void main(String[] args) {
display(); //calling without object
Difference t = new Difference();
t.show(); //calling using object
}
static void display() {
System.out.println("Programming is amazing.");
}
void show(){
System.out.println("Java is awesome.");
}
}

Output of code:

Java program can contain more than one i.e. multiple classes. Following example
Java program contain two classes: Computer and Laptop. Both classes have their
own constructors and a method. In main method we create object of two classes
and call their methods.

Using two classes in Java program


class Computer {
Computer() {
System.out.println("Constructor of Computer class.");
}
void computer_method() {
System.out.println("Power gone! Shut down your PC soon...");
}
public static void main(String[] args) {
Computer my = new Computer();
Laptop your = new Laptop();
my.computer_method();
your.laptop_method();
}

class Laptop {
Laptop() {
System.out.println("Constructor of Laptop class.");
}

void laptop_method() {
System.out.println("99% Battery available.");
}

Output of program:

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 method
Programming() {
System.out.println("Constructor method called.");
}

public static void main(String[] args) {


Programming object = new Programming(); //creating object
}

Output of program:

Java exception handling tutorial: In this tutorial we will learn how to handle
exception with the help of suitable examples. Exceptions are errors which occur
when the program is executing. Consider the Java program below which divides
two integers.

import java.util.Scanner;
class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
result = a / b;

System.out.println("Result = " + result);


}

Now we compile and execute the above code two times, see the output of program
in two cases:

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);


}

Swap numbers program class file.


Output of program:

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);
}

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.");
else
System.out.println("Entered numbers are not distinct.");
}

Download Largest of three numbers program class file.


Output of program:

Enhanced for loop java: Enhanced for loop is useful when scanning the array
instead of using for loop. Syntax of enhanced for loop is:
for (data_type variable: array_name)

Here array_name is the name of array.

Java enhanced for loop integer array


class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
for (int t: primes) {
System.out.println(t);
}
}

Download Enhanced for loop program.


Output of program:

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);

Download Factorial program class file.

Output of program:

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++;
}
}

Download Prime numbers program class file.


Output of program:

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.");
else
System.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;

Download Armstrong number program class file.


Output of program:

This java program prints Floyd's triangle.

Java programming source code


import java.util.Scanner;
class FloydTriangle
{
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows of floyd's triangle you
want");
n = in.nextInt();
System.out.println("Floyd's triangle :-");

for ( c = 1 ; c <= n ; c++ )


{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
}
}

System.out.println();

Download Floyd's triangle program class file.


Output of program:

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);

Download Reverse string program class file.


Output of program:

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.");
}
}

Download Palindrome program class file.

Output of program:

nterface program in Java


In our program we create an interface named Info which contains a constant and
a method declaration. We create a class which implements this interface by
defining the method declared inside it.
interface Info {
static final String language = "Java";
public void display();
}
class Simple implements Info {
public static void main(String []args) {
Simple obj = new Simple();
obj.display();
}
// Defining method declared in interface
public void display() {
System.out.println(language + " is awesome");
}
}

Download Interface program class file.

Output of program:

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.");
else
System.out.println("Both strings are equal.");
}

Download Compare strings program class file.


Output of program:

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.");
}
}

Download Linear Search Java program class file.

Output of program:

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;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}

Download Binary Search Java program class file.


Output of program:

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);
}
}

Download Substrings of a string program class file.


Output of 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
System.out.println("Current time is
"+second);
}
}

"+day+"/"+(month+1)+"/"+year);
"+hour+" : "+minute+" :

Download Date and time program class file.


Output of program:

Java program to generate random numbers: This code generates random


numbers in range 0 to 100 (both inclusive).

Java programming code


import java.util.*;
class RandomNumbers {
public static void main(String[] args) {
int c;
Random t = new Random();
// random integers in [0, 100]
for (c = 1; c <= 10; c++) {
System.out.println(t.nextInt(100));
}
}

Download Random Numbers program class file.

Output of program:

This program prints reverse of a number i.e. if the input is 951 then output will be
159.

Java programming source code


import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
}

System.out.println("Reverse of entered number is "+reverse);

Download Reverse number program class file.

Output of program:

You might also like