Java programming examples

 

 Core Java Code Examples for Beginners

 

Basics

Conditions

Loops

Arrays

 

 

 

 Basics

 

This tutorial provides you a practice programs on Java topics. You will find the code with output. Straight away,  you can copy and run on your machine. These programs run on any platform. Just install java and  use any code-editor like Eclipse, NetBeans, VS Code or even notepad is fine. If you run at command line, make sure you set the class path. Many of these programs can be run on Online Compiler too. In case any questions, please comment below.

 


  1. Print Hello World in java
  2. Using Datatypes  in Java
  3. Swapping  two interger variables in Java
  4. Using command line aruguments in Java
  5. Arguments Demo example2
  6. Arguments Demo example3

 

 

 

Print Hello World in java

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

Using  Java Arithmetic operators

class Second
{
	
	public static void main(String args[])
    
	{
		
	      int a=5;
	      int b=10;
	      int c=0;
	      int d=0;
		c=a+b;   
		d=a*b;
		System.out.println("a="+a);
		System.out.println("b="+b);
		System.out.println("c="+c);
		System.out.println("d="+d);
	}
	
}
 
 
 

Using Datatypes  in Java

 
class DataDemo
{
	public static void main(String args[]){
		
		char gender='m';
		int empcode=100;
		short age=34;
		long phoneno=123456;
		float height=5.8f;
		double salary=25.000d;
		
		System.out.println("Gender="+gender);
              System.out.println("Empcode="+empcode);
		System.out.println("Age="+age);
		System.out.println("PhoneNO="+phoneno);    
		System.out.println("Emp height="+height);
		System.out.println("Salary="+salary);
	}
} 
 
 output
 
C:\javabasics>javac DatatypeDemo.java

C:\javabasics>java DatatypeDemo
Emp height=5.8
Salary=25.0 
 
 

Swapping  two interger variables in Java

 
class Interchange
{
	
	public static void main(String args[])
	
	{
		int i=10;
		int j=12;
		int k; 
             System.out.println(i+"  "+j);
             k=i;
		i=j;
		j=k;
		System.out.println(i+"  "+j);
	}
} 
 
output:
C:\javabasics>java Int

10 12 
12  10 
 
 

Using command line aruguments in Java 

 
class ArgsDemo
{  //class begin
	public static void main(String args[])
	{  //main begin
		
		String name=args[0];
		String address=args[1];
		System.out.println("Name: "+name);
		System.out.println("Address: "+address);
	}   // main end
}  // class end
 
How to run
At command prompt give the following command to Run the code
 
c:\javabasics>java ArgsDemo John Delhi
 
output :
Name: John
Address: Delhi
 
 
 

Arguments Demo example2

 
class CalDemo{
	
	public static void main(String args[]){
		int a;
		int b;
		int c;
		//   a=args[0];
		a=Integer.parseInt(args[0]);
		b=Integer.parseInt(args[1]);
		c=a+b;
		System.out.println("c="+c);
	}
} 
 
output
C:\javabasics> javac CalDemo.java
C:\javabasics>java CalDemo 3 4
c=7 
 
 

Arguments Demo example3

 
class Grade

{
	public static void main(String args[])
	{
		
		int math;
		int sci;
		int eng;
		int chem;
		math=Integer.parseInt(args[0]);
		sci=Integer.parseInt(args[1]);
		eng=Integer.parseInt(args[2]);
		chem=Integer.parseInt(args[3]);
		
		int tot;
		tot=(math+sci+eng+chem);
		
		if(tot>=500)
		{
			System.out.println("excellent");
		}
		
		else if(tot>=400 && tot<500)
		{
			System.out.println("good");
		}
		else if(tot>=300 && tot<400)
		{
			System.out.println("average");
		}
		else
		{
			System.out.println("fail");
		}
                {
			System.out.println(tot);
		}
		
	}
} 
 
 
 

This program you need to run at command prodprompt as show below 

 
 output:
 
C:\javabasics>java Grade 85 96 76 78
average
335 
 
 class Escapesequence

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

Conditions  


 
 
  1. Terinary operator example program
  2. Find the given number belongs to which range using java Switch
  3. Print the given number in a character-form using Java Switch-Case.
  4. Print Week name for a given week day using Java switch-case
  5. Switch case menu example
  6. Switch case color menu example2
 
 
 
 

 Terinary operator example program 

 
 class Terinary
 
    public static void main(String args[]){ 
 
             int a=15;
		int b=26;
		
		System.out.println((a>b)?"A is big":"B is Big");
		
	}
}
 


 

Find the given number belongs to which range using java Switch

 

import java.io.*;

class Range
{
	public static void main(String args[]) throws IOException{
				
		int no = 5;
		
		switch(no)
	        {
		case 1:
		case 2:
		case 3:
		case 4:
		
		System.out.println("No is below 5");
		break;
		case 5:
		System.out.println("No is equal to 5");
		break;
		case 6:
		case 7:
		case 8:
		case 9:
		
		System.out.println("No is above 5");
		break;
		default:
		System.out.println("The No is out of range");
	}
}
} 
 


  Print the given number in a character form using Java Switch-Case.  

 
 class SwitchDemo{
	 
public static void main(String args[]){
		int choice=2;
		
		switch(choice)
		{
			case 1:
			System.out.println("One");
			break;            
			
			case 2:
			System.out.println("Two");
			break;            
			
			case 3:
			System.out.println("Three");
			break;            
			default:
			System.out.println("Wrong choice");                       
			
			
		}
	}
}

output 
 Two     
 


"

 Print Week name for a given week day using Java switch-case

 

class Week
	{
	public static void main(String args[])
	{
	int week=4;
	switch(week)
	{
	case:1
	System.out.println("MON");
	break;
	case:2
	System.out.println("TUE");
	break;
	case:3
	System.out.println("WED");
	break;
	case:4
	System.out.println("THU");
	break;
	case:5
	System.out.println("FRI");
	break;

       case:5
	System.out.println("SAT"); 

       break;         
	System.out.println("SUN"); 

       break;  

       default; 

       System.out.println("WRONG CHOICE");             

    }
  }
}  
 
 
output  THU  
 
 


Switch case menu example


class
MenuDemo { public static void main(String args[]) throws IOException{ System.out.println("1. Spring"); System.out.println("2. Autom"); System.out.println("3. Summer"); System.out.println("4. winter"); System.out.println("5. Exit"); System.out.println("Enter your choice"); char ch; ch=(char)System.in.read(); switch(ch) { case '1': System.out.println("Your choice Spring"); break; case '2': System.out.println("Your choice Autum"); break; case '3': System.out.println("Your choice Summer "); break; case '4': System.out.println("Your choice Summer "); default: System.out.println("Your exiting"); } } }
 
 

Switch case menu example 2- choose the color of your choice

 
 
import java.io.*;

class Color
{
	public static void main(String args[])throws IOException
    {
		System.out.println("1.Blue");
		System.out.println("2.Green");
		System.out.println("3.Green");
		System.out.println("Enter ur choice");
		
		char c;
		c=(char)System.in.read();
		switch(c)
		{
			case '1': 
			System.out.println("Ur choice is Blue");
			break;
			
			case '2': 
			System.out.println("Ur choice is Green");
			break;
			case '3': 
			System.out.println("Ur choice is Red");
			break;
                default:
		       System.out.println("Your exiting"); }
		
	}
	
	
} 

Conditions

 
 
C:\javabasics>javac Color.java

C:\javabasics>java Color
1. Blue
2.Green
3.Green
Enter ur choice
1
Ur choice is Blue

C:\javabasics>java Color
1. Blue
2.Green
3.Green
Enter ur choice
5
C:\javabasics> 
 
 
 
 

Looping Examples


 

  1. While Loop
  2. Do-while example
  3. Do-while example2
  4. Break in Loop  
  5. Continue in Loop  
  6. Nested For
  7. 3 by 3 Matrix




 

 

Printing Hello Ten times using While Loop


class Nat
{    
    public static void main(String args[])
	{
	int i=1;
	while( i <= 10 )
	{
		System.out.println(i + ".Hello");
		i=i+1;  // same as i++;
	}	
		 
   }
} 
output:
1.Hello
2.Hello
3.Hello
4.Hello
5.Hello
6.Hello
7.Hello
8.Hello
9.Hello
10.Hello 


 do-while loop with interactive example

 
import java.io.*;

class  Interactiveloop
{
	public static void main(String args[])throws IOException{
		
		
		char ans='y';
		
		do{
						
			System.out.println("Welcome to JavaCoding \n\n");
						
			System.out.println("Do you want to continue...");
						
			ans=(char)System.in.read();         	
		}
		while(ans!='n');
	}
} 
 
output:
 
Welcome to JavaCoding
Do you want to continue... 
y
Welcome to JavaCoding
Do you want to continue... 
n
 

 do-while loop with interactive example2

 
 
import java.io.*;

class  DoDemo
{
	public static void main(String args[])throws IOException{
		
		int i=1;
		char ch='y';
		
		
		do{
			i=1;
			do{
				System.out.println(i);
				i++;
			}
			while(i<=5);
			
			
			System.out.println("Do you want to continue...");
			
			ch=(char)System.in.read();
		}
		while(ch!='n');
	}
} 
 
 
output:
 
C:\javabasics>javabasics>javac DoDemo.java
C:\javabasics>java DoDemo
1
2
3
4
5
Do you want to continue...

1
2
3
4
5
Do you want to continue...
1
2
3
4
5
Do you want to continue...
n

H:\JavaNotes\javabasics>
 

 

Break in Loop - terminates/breaks  the loop when loop reaches to  the condition 

 
 class Breakinloop

{
	
    public static void main(String args[])
	
	{
	    int k;
		int n=Integer.parseInt(args[0]);
		int sum=0;
	    for(k=n;k>=1;k--)
		{
			
		    if(k==6)
			break;
			System.out.println(k);
			sum=sum+k;
			
		}
		System.out.println("sum="+sum);
	}
	}
 
output:
C:\javabasics>java Breakinloop 10
10
9
8
7
sum=34 
 

Continue in Loop - Skips  the current iteration when loop reaches to  the condition 

 
 
 class Continueinloop

{
	
    public static void main(String args[])
	
	{
	    int k;
		int n=Integer.parseInt(args[0]);
		int sum=0;
	    for(k=n;k>=1;k--)
		{
			
		    if(k==6)
			continue;
			System.out.println(k);
			sum=sum+k;
			
		}
		System.out.println("sum="+sum);
	}
	
}  
output: 
C:\javabasics>java Continueinloop 10
9
8
7
5
4
3
2
1
sum=49

 

 

Using Nested For Loop printing 3 by 3 matrix



class Nestedfor { public static void main(String args[]) { int i,j,k; k=1; for(i=1;i<=3;i++) { for(j=1;j<=3;j++) { System.out.print(k++); } System.out.println(); } } }
output

123
456
789 
 

 

 

Printing 3 by 3 Matrix  inJava  with for loop



class Diagnal
{
	
    public static void main(String args[])
	
	{
	    int i,j;
		
		for(i=1;i<=3;i++)
		{
                for(j=1;j<=3;j++)
			{
				if(i!=j) 
				System.out.print(0);
				else
				System.out.print(1);
			}
			System.out.println();
		}
	}
	
}
 
output:
100
010
001




 Array Programs


  Menu

  1. Printing array elements in reverse 
  2. Single Dimentaional array - addition of two arrays in Java
  3. Characters array example in Java
  4. Sorting an Array in Java
  5. Sum of odd nos. using array and for-each loop in java
  6. Find the Evaluation
  7. Find the Smallest Number  in an array
  8. Find the index of a given element in an array
  9. Count Howmany times the given digit  repeated in an array.
  10. Calculate total marks using array and for loop  in Java
  11. Print 1 to 5 tables in Java  with nested for loop
  12. Printing DoubleDimentional Char Array Java  with for loop
  13. Printing DoubleDimentional String Array Java  with for loop
  14. Printing DoubleDimentional Int Array Java  with nested for loop
  15. Print stars in a triangle shape. Using java nested For loop
  16. Using for-each Loop with Double Dimentional Array
  17. Array Copy  example- Java

 

 

Printing array elements in reverse

class Reverse
{
	public static void main(String args[]){
		int n[]={5,3,2,8,2,2};
		
		//  System.out.println(n.length);
		
		for(int i=n.length-1;i>=0;i--)
		{
			System.out.print(n[i]+" ");
		} 
	}
}

 output:

2 2 8 2 3 5 

 

 

Single Dimentaional array - addition of two arrays in Java

 
class SDarray
{
	public static void main(String args[]){
		
		int a[]={78,65,76,89,67,95};
		int b[]={7,5,6,9,7,5};
		int c[]={0,0,0,0,0,0};
		
		for(int i=0;i<6;i++)
		{
			c[i]=a[i]+b[i];
			
			System.out.print(c[i]+" ");
		}
		
		
		
	}
}
 
output:
85 70 82 98 74 100  
 
 

Characters array example in Java


class CharArrayDemo{
	public static void main(String args[])
	{
		/* 
			char n[]= new char[6];
			n[0]='A';
			n[1]='P';
			n[2]='T';
			n[3]='E';
			n[4]='C';
		       n[5]='H';*/
		
		char n[]={'J','A','V','A','D','E','M','O'};
		
        for( char i:n)
		{
			if(i=='A'||i=='E'||i=='I'||i=='O'||i=='U')
            {
				System.out.println(i);
				
				
			}
		}
	}
} 
 
C:\javabasics>javac CharArrayDemo.java

C:\javabasics>java CharArrayDemo
A

 

 

Sorting an Array in Java 

 
 
 
class Sort
{
	
	public static void main(String args[])
	
	{
		int i,j,k;
		
		int n[]={3,6,4,8,5};
		
		for(i=0;i<5;i++)
		{
			for(j=i+1;j<5;j++)
			{
				if(n[i]>n[j])
				
				{
					
					k=n[i];
					n[i]=n[j];
					n[j]=k;
				}
			}
			
		}
		
		for(i=0;i<5;i++)
		{
			System.out.print(n[i]+"  ");
			
		}
		
	}
} 
 
output:
3  4  5  6  8  
 
 

Sum of odd nos. using array and for-each loop in java


class ArrayDemo{
	public static void main(String args[])
	{
		int n[]= new int[5];
		n[0]=6;
		n[1]=7;
		n[2]=5;
		n[3]=4;
		n[4]=9;
		int sum=0;
		
		
        for( int i:n)
		{
			if((i%2)!=0)
            {
				System.out.println(i);
				
				sum+=i;
			}
		}
		System.out.println("----");
		
		System.out.println(sum);
		
		System.out.println("----");
	}
} 
 
 output:
7
5
9
----
21
---- 
 

 

Find the Evalueation 

 
class Evaluation
{
	public static void main(String args[])
	{
		int a,b,c,d;
		a=2;b=3;c=8;d=2;
		System.out.println((a*b)+(c/d)*22);
	}
	
} 
 
output:
94 
 
class Exe
{
	public static void main(String args[])
	{
		int a;
		a=Integer.parseInt(args[0]);
		System.out.println("a*a="+a*a);
	}
	
} 
 
 
output
 
C:\javabasics>java Exe 5
a*a=25 

 

Find the Smallest Number  in an array

 
 
class FindSmall
{
	public static void main(String args[]){
		int n[]={5,3,2,8,4};
		int small=n[0];
		for(int i:n)
		{
			if(small>i)
			small=i;
			
		}
		System.out.println("small="+small);
	}
}
 output:
 2
 
 

Find the index of a given element in an array

 
class FindIndex
{
	public static void main(String args[]){
		
		int subjects[]={78,65,76,89,67,95};
		int n=Integer.parseInt(args[0]);
		
		for(int i=0;i<6;i++)
		{
			if(n==subjects[i])
			System.out.println("the position of the "+n+" is "+(i+1));
		}
		
		
		}
}
 
 
output:
 
C:\javabasics>java FindIndex 65
the position of the 65 is 2 
 
 

 Using for-each Loop with Single Dimentional Array

 
class Foreach{
	public static void main(String args[])
	{
		int n[]={1,2,3,4,5,6,};
		for(int i :n)
		{
			System.out.println(i);
		}
	}
} 

 

Count Howmany times the given digit  repeated in an array.

 
 class Countdigit
{
	public static void main(String args[]){
		int n[]={5,3,2,8,2,2};
		int count=0;
		for(int i:n)
		{
			if(i==2)
			count++;
		}
		System.out.println("2 is repeated "+count+ " times");
	}
}
output
 
C:\javabasics>javac Countdigit.java

C:\javabasics>java Countdigit
2 is repeated 3 times

C:\javabasics> 
 
 

Calculate total marks using array and for loop  in Java

 
 
class Student
{
	public static void main(String args[]){
		String name="John";
		int rno=123;
		int subjects[]={78,65,76,89,67,95};
		int total=0;
		float avg=0.0f
            for(int i=0;i<6;i++)
		{
			total = total + subjects[i];
		}
		avg=total/6;
		
		System.out.println("StudentName:"+name);
		System.out.println("RollNo:"+rno);
		System.out.println("Total :"+total);
		System.out.println("Average:"+avg);
	}
}
 
output:
 
StudentName:John
RollNo:123
Total :470
Average:78.0 

Print 1 to 5 tables in Java  with nested for loop

 
 
import java.io.*;

class  Table
{
	public static void main(String args[])throws IOException{
		
		int i=1;
		int c=1;
        
		do{
			i=1;			
			do{
				System.out.println(c+"*"+i+"="+(c*i));
				i++;
			}
			while(i<=10);			
			c++;			
			System.in.read();
		}
		while(c<=5);
	}
	} 
 
 prints all the tables 1-5.
 
 

Printing DoubleDimentional Char Array Java  with for loop

 
 
 class DDarray
{
	public static void main(String args[]){
		
		char names[][]=
		{{'a','a','a','a'},
                {'b','b','b'},
                {'c','c','c','c'},
                {'d','d','d','d'}
		};
		
		for(int i=0;i<4;i++)
		{
			System.out.println(names[i]);
		}
		
		
		
	}
}
 
 output:
aaaa
bbbb
cccc
dddd 
 
 
 

Printing DoubleDimentional String Array Java  with for loop

 
 
 class DDarray1
{
	public static void main(String args[]){
		
		String cnames[][]={{"India","Rupee"},
			{"France","Euro"}
		};
		
		
		/* printing  using index positions
			System.out.print(cnames[0][0]);
			System.out.print(cnames[0][1]);
			System.out.println("");
			System.out.print(cnames[1][0]);
			System.out.print(cnames[1][1]);
			
		*/
		// printing  using forloop 
		
		for(int i=0;i<2;i++)
		{
			for(int j=0;j<2;j++)
			{
			System.out.print(cnames[i][j]+" ");
				
			}
			System.out.println("");   
		}  
				
	}
}
 
output:
india Rupee
France Euro 
  

 

Printing DoubleDimentional Int Array Java  with nested for loop

 
class DDMatrix
{
	public static void main(String args[]){
		int a[][]={{2,3},{4,5}};
		
		for(int i=0;i<2;i++)
		{
			for(int j=0;j<2;j++)
			{
				System.out.print(a[i][j]);
			}
			System.out.println("");
		}
		
	}
	
}
 
output:
23
45 

 

Print stars in a triangle shape. Using java nested For loop



public class Tri {
	
	public static void main(String[] args) {
		
		int[][] tri = new int[10][10];		
		
		for (int i=0; i<tri.length-1; i++) {
			for(int j=0; j<=i; j++) {
				
				System.out.print("* ");
			}
			System.out.println();
		}
		
		
	}
}

output
* 
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
 
Explaination:
 
There is an array created 10 rows and 10 columns.
And take for loop with size of the array(given is length-1) 
column are equal to rows
if row 1 col also 1
if row 2 col also 2
 
 

 Using for-each Loop with Double Dimentional Array

 
public class ForeachDDarray{
	public static void main(String args[]) {
		int c = 0;
		int nums[][] = new int[3][3];
		
		
		
		// use for-each for to display and sum the values
		for (int x[] : nums) {
			for (int y : x) {
				
				
				System.out.print(c++);
			}
			
			System.out.println("");
		}
	}
}
output:
C:\javabasics>javac ForeachDDarray.java
C:\javabasics>java ForeachDDarray
012
345
678 
 

Array Copy  example- Java

public class Arraycopy{
public static void main(String[] args){
    char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
    char[] copyTo = new char[5];
    System.arraycopy(copyFrom, 2, copyTo, 0, 5);
    System.out.println(new String (copyTo));
}
} 
output:
cdefg 
 
// system class contains a method called arraycopy() which copies one array 
elements to another. So from the 1st array, starting from 2nd position to  the
destination array copyto's 0'position to 5th position

--> while printing, the char array copyto is sent to string. So the string is 
printed with the copied values

so here from 1st array's 2nd position means   c. 
copied in 0th position of copyto array, and it continues up to 5 elements
means c, d, e, f, g.


coding-zon-java-coding-examples



Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP