Java Basic Programs
Explore our extensive repository of Java programming examples. Java is a versatile, object-oriented programming language used for building enterprise-scale applications, mobile apps (Android), and web services. Below, you will find practical Java snippets covering topics like OOP principles, collections framework, exception handling, and multithreading. Whether you are preparing for an interview or learning Java for the first time, these code snippets will enhance your problem-solving skills.
1. Hello World Example
Concept: A fundamental program that prints a message to the console. It demonstrates the basic structure of a Java class and the main method.
program_1.java
class Prog1
{
public static void main(String args[])
{
System.out.println("Hello Java World!");
System.out.println("Telugu IT Tutorials");
System.out.println("Ongole");
}
}
Analysis
- Time Complexity: O(1) - Constant time.
- Space Complexity: O(1) - Constant space.
Telugu IT Tutorials
Ongole
2. Scanner Input
Concept: Demonstrates reading data from the user via the command line using the Scanner class.
program_2.java
import java.util.*;
class Prog2
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int a,b,c;
System.out.println("Enter a,b values");
a=scanner.nextInt();
b=scanner.nextInt();
c=a+b;
System.out.println("A=" + a);
System.out.println("B=" + b);
System.out.println("Sum=" + c);
}
}
Analysis
- Time Complexity: O(1) - The execution depends only on user input.
- Space Complexity: O(1) - Only primitive variables are used.
Enter Age: 25
Given Name : John
Given Age : 25
3. Arithmetic Operations
Concept: Shows how to perform basic arithmetic operations like addition using inputs provided by the Scanner.
program_3.java
import java.util.*;
class Prog3
{
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
float r,area,pi=3.1416f;
System.out.println("Enter radius value");
r=scanner.nextFloat();
area=pi*r*r;
System.out.println(r + " Area is " + area);
}
}
Analysis
- Time Complexity: O(1) - Constant time for arithmetic.
- Space Complexity: O(1) - Constant space.
10
20
Addition : 30
4. Calculate Total and Average
Concept: Calculates the total and average marks based on user input for multiple subjects.
program_4.java
import java.util.*;
class Prog1
{
public static void main(String args[])
{
int m,p,c,avg;
Scanner in=new Scanner(System.in);
System.out.println("Enter m,p,c values");
m=in.nextInt();
p=in.nextInt();
c=in.nextInt();
avg=((m+p+c)/3);
if(m>34 && c>34 && p>34)
{
if(avg>34 && avg<50)
{
System.out.println("Ordianary");
}
else if(avg>=50 && avg<60)
{
System.out.println("Second class");
}
else if(avg>=60 && avg<75)
{
System.out.println("First Class");
}
else if(avg>=75 && avg<=100)
{
System.out.println("Distinction");
}
else if(avg>100)
{
System.out.println("Given Marks is Wrong");
}
}
else
{
if(m<35)
System.out.print("Maths ");
if(p<35)
System.out.print("Phy ");
if(c<35)
System.out.print("Che ");
System.out.print(" Failed");
}
}
}
Analysis
- Time Complexity: O(1) - Simple calculation.
- Space Complexity: O(1) - Stores fixed number of variables.
80
90
85
Total : 255
Average : 85.0
5. For Loop Example
Concept: Uses a for loop to print numbers from 1 to N, demonstrating basic iterative control flow.
program_5.java
import java.util.Scanner;
class Prog2
{
public static void main(String args[])
{
int n,i;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
i=1;
while(i<=10)
{
System.out.println(n + "X" + i + "=" + n*i);
i++;
}
}
}
Analysis
- Time Complexity: O(N) - Where N is the input number.
- Space Complexity: O(1) - Reuses the loop counter.
1
2
3
4
5
6. Number Pattern
Concept: Generates a triangular number pattern using nested loops, an excellent exercise for nested iterations.
program_6.java
/*
1
12
123
1234
12345
*/
import java.util.*;
class Prog3
{
public static void main(String args[])
{
int n;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j + " ");
}
System.out.println("");
}
for(int i=n-1;i>=1;i--)
{
for(int j=1;j<=i;j++)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}
Analysis
- Time Complexity: O(N^2) - Nested loops run proportional to N^2.
- Space Complexity: O(1) - Minimal space overhead.
12
123
1234
12345
7. Currency Denomination
Concept: Calculates the minimum number of currency notes required for a given amount using division and modulo operators.
program_7.java
import java.util.*;
class Prog4
{
public static void main(String args[])
{
int amount,sum=0;
Scanner in=new Scanner(System.in);
do
{
System.out.println("Enter Amount");
amount=in.nextInt();
if(amount>0)
{
sum=sum+amount;
System.out.println("Cumilative Amount is :" + sum);
}
}while(amount>0);
System.out.println("The Total Amount is " + sum);
}
}
Analysis
- Time Complexity: O(1) - Fixed number of denomination checks.
- Space Complexity: O(1) - Only amount variables are stored.
2000 X 1 = 2000
500 X 1 = 500
...
8. Biggest of Three Numbers
Concept: Finds the largest of three numbers using conditional if-else statements.
program_8.java
import java.util.*;
class Prog5
{
public static void main(String args[])
{
int a,b,c;
Scanner in=new Scanner(System.in);
System.out.println("Enter a,b values");
a=in.nextInt();
b=in.nextInt();
do{
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
System.out.println("5.Modulus");
System.out.println("6.Exit");
System.out.println("Enter Your Choice ");
c=in.nextInt();
switch(c)
{
case 1:
System.out.println("A+B=" + (a+b));
break;
case 2:
System.out.println("A-B=" + (a-b));
break;
case 3:
System.out.println("AXB=" + (a*b));
break;
case 4:
System.out.println("A/B=" + (a/b));
break;
case 5:
System.out.println("A%B=" + (a%b));
break;
default:
System.out.println("Your Exit");
}
}while(c<=5);
}
}
Analysis
- Time Complexity: O(1) - Simple comparisons.
- Space Complexity: O(1) - Constant space usage.
10
30
20
Biggest is 30
9. One-Dimensional Array
Concept: Initializes and prints elements from a 1D array, illustrating basic data structures.
program_9.java
import java.util.*;
class Prog1
{
public static void main(String args[])
{
/*int a[],n,i;*/
int[] a;
int n,i;
Scanner in=new Scanner(System.in);
System.out.println("Enter array size");
n=in.nextInt();
a=new int[n]; //Re initilization array
System.out.println("Enter " + n + " Elements");
for(i=0;i<n;i++)
{
a[i]=in.nextInt();
}
System.out.println("The Elements are");
for(i=0;i<n;i++)
{
System.out.print(a[i] + " ");
}
System.out.println("\nThe Elements in Reverse is ");
for(i=n-1;i>=0;i--)
{
System.out.print(a[i] + " ");
}
}
}
Analysis
- Time Complexity: O(N) - Array traversal.
- Space Complexity: O(N) - Space for N elements.
10
20
30
40
50
10. Two-Dimensional Array
Concept: Initializes and prints a 2D matrix array, commonly used for grid or table representations.
program_10.java
import java.util.*;
class Prog2
{
public static void main(String args[])
{
int a[][],r,c,i,j;
Scanner in=new Scanner(System.in);
System.out.println("Enter r,c values");
r=in.nextInt();
c=in.nextInt();
a=new int[r][c];
System.out.println("Enter " + r + "X" + c + " Matrix values");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("The Matrix is ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}
}
Analysis
- Time Complexity: O(R * C) - Traversal of rows and columns.
- Space Complexity: O(R * C) - Matrix allocation.
10 20 30
40 50 60
70 80 90
11. Function: No Arguments, No Return
Concept: Defines a simple method that takes no arguments and returns nothing (void).
program_11.java
//No Arguments Pass and No Return values
import java.util.*;
class Prog1
{
public static void area()
{
float r,pi=3.1416f,a;
Scanner in=new Scanner(System.in);
System.out.println("Enter radius value");
r=in.nextFloat();
a=pi*r*r;
System.out.println(r + " Area is " + a);
}
public static void main(String args[])
{
int n,i;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
for(i=1;i<=n;i++)
{
area();
}
}
}
Analysis
- Time Complexity: O(1) - Single operation.
- Space Complexity: O(1) - Minimal footprint.
12. Function: With Arguments, No Return
Concept: Passes data to a method via arguments, calculating the result without returning a value.
program_12.java
import java.util.*;
class Prog2
{
public static void area(float r)
{
float pi=3.1416f,a;
a=pi*r*r;
System.out.println(r + " Area is " + a);
}
public static void main(String args[])
{
int n,i;
float r;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
for(i=1;i<=n;i++)
{
System.out.println("Enter Radius value");
r=in.nextFloat();
area(r);
}
}
}
Analysis
- Time Complexity: O(1) - Calculation in place.
- Space Complexity: O(1)
13. Function: With Arguments, Return Value
Concept: Passes inputs to a method which calculates and returns the output to the caller.
program_13.java
import java.util.*;
class Prog3
{
public static float area(float r)
{
float pi=3.1416f,a;
a=pi*r*r;
return(a);
}
public static void main(String args[])
{
int n,i;
float r,a;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
for(i=1;i<=n;i++)
{
System.out.println("Enter Radius value");
r=in.nextFloat();
a=area(r);
System.out.println(r + " Area is " + a);
}
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
14. Function: No Arguments, Return Value
Concept: A method that takes no parameters but returns a predefined or calculated value.
program_14.java
// No Arguments Pass But Return values
import java.util.*;
class Prog4
{
public static float area()
{
float r,pi=3.1416f,a;
Scanner in=new Scanner(System.in);
System.out.println("Enter Radius value");
r=in.nextFloat();
a=pi*r*r;
System.out.print(r);
return(a);
}
public static void main(String args[])
{
int n,i;
float a;
Scanner in=new Scanner(System.in);
System.out.println("Enter n value");
n=in.nextInt();
for(i=1;i<=n;i++)
{
a=area();
System.out.println(" Area is " + a);
}
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
15. Method Overloading
Concept: Demonstrates compile-time polymorphism by defining multiple methods with the same name but different signatures.
program_15.java
/*
Functions Overloading ?
The function name is the common and the parameters is different is called a
functions overloading
*/
import java.util.*;
class Prog1
{
public static int sum(int a,int b)
{
return(a+b);
}
public static int sum(int a,int b,int c)
{
return(a+b+c);
}
public static int sum(int a,int b,int c,int d)
{
return(a+b+c+d);
}
public static float sum(int a,float b)
{
return(a+b);
}
public static float sum(float a,int b)
{
return(a+b);
}
public static float sum(float a,float b)
{
return(a+b);
}
public static void main(String args[])
{
int a,b,c,d;
float e,f;
Scanner in=new Scanner(System.in);
System.out.println("Enter any four Integers");
a=in.nextInt();
b=in.nextInt();
c=in.nextInt();
d=in.nextInt();
System.out.println("Enter any two Float numbers");
e=in.nextFloat();
f=in.nextFloat();
System.out.println("A+B=" + sum(a,b));
System.out.println("A+B+C=" + sum(a,b,c));
System.out.println("A+B+C+D=" + sum(a,b,c,d));
System.out.println("A+E=" + sum(a,e));
System.out.println("E+A=" + sum(e,a));
System.out.println("E+F=" + sum(e,f));
}
}
Analysis
- Time Complexity: O(1) per call.
- Space Complexity: O(1)
Area of Rectangle : 150.0
16. Class and Object Creation
Concept: Shows how to define a Class and create Objects, covering instance variables and methods.
program_16.java
/*
What is the Class ?
The combination state and behaviour of the object is called class
What is the Object ?
A instance of the class is called object
*/
import java.util.*;
class Student
{
int code;
String name;
String course;
public void setStudent(int intcode,String strname,String strcourse)
{
code=intcode;
name=strname;
course=strcourse;
}
public void showStudent()
{
System.out.println("Code : " +code);
System.out.println("Name : " +name);
System.out.println("Course : " +course);
}
}
class Prog1
{
public static void main(String args[])
{
Student student1=new Student();
int code;
String name,course;
Scanner in=new Scanner(System.in);
System.out.println("Enter Code Name Course");
code=in.nextInt();
name=in.next();
course=in.next();
student1.setStudent(code,name,course);
Student student2=new Student();
System.out.println("Enter Code Name Course for Student 1");
code=in.nextInt();
name=in.next();
course=in.next();
student2.setStudent(code,name,course);
student1.showStudent();
student2.showStudent();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Sco : 100
Sname : Prasad
Marks : 90
17. Constructors
Concept: Demonstrates the use of a constructor to initialize object states during instantiation.
program_17.java
/*
What is the Constructor ?
The constructor can initialize the class members
note: whenever we instantiated the class then automatically the constructor
executed
Rules:
1)The constructor name must be a class name
2)No return type in constructors
Types of Constructors:
1)Default constructor(With out parameters or arguments)
2)Parameterised constructor( With parameters or arguments)
Overloading Construrctor:
if you are using default constructor and parameterised constructor
using a single class i.e overloading construcotrs
*/
import java.util.*;
class Employee
{
int code;
String name;
String desig;
Employee()
{
code=100;
name="SrinivasaRao.K";
desig="Engg";
}
public void setEmployee(int code,String name,String desig)
{
this.code=code;
this.name=name;
this.desig=desig;
}
public void showEmployee()
{
System.out.println("Code : " + code);
System.out.println("Name : " + name);
System.out.println("Desig : " + desig);
}
}
class Prog1
{
public static void main(String args[])
{
int code;
String name,desig;
Scanner in=new Scanner(System.in);
Employee employee=new Employee();
employee.showEmployee();
System.out.println("Enter code name desig");
code=in.nextInt();
name=in.next();
desig=in.next();
employee.setEmployee(code,name,desig);
employee.showEmployee();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Student Details
Sno : 100
Sname : Prasad
Marks : 90
18. Parameterized Constructor
Concept: Using arguments in constructors to initialize object fields dynamically.
program_18.java
/*Default Contructor and Parameterised Constructor*/
import java.util.*;
class Employee
{
int code;
String name;
String desig;
Employee()//default constructor
{
code=100;
name="SrinivasaRao.K";
desig="Engg";
}
Employee(int code,String name,String desig)//parameterised constructor
{
this.code=code;
this.name=name;
this.desig=desig;
}
public void setEmployee(int code,String name,String desig)
{
this.code=code;
this.name=name;
this.desig=desig;
}
public void showEmployee()
{
System.out.println("Code : " + code);
System.out.println("Name : " + name);
System.out.println("Desig : " + desig);
}
}
class Prog2
{
public static void main(String args[])
{
int code;
String name,desig;
Scanner in=new Scanner(System.in);
System.out.println("Enter code name desig");
code=in.nextInt();
name=in.next();
desig=in.next();
Employee employee=new Employee();//default constructor
employee.showEmployee();
employee.setEmployee(code,name,desig);
employee.showEmployee();
Employee employee1=new Employee(102,"Durrga","CSC");
//parameterised constructor
employee1.showEmployee();
employee1.setEmployee(code,name,desig);
employee1.showEmployee();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Ename : Kiran
Salary : 15000
19. Single Inheritance
Concept: Shows a Child class inheriting properties and methods from a Parent class using the 'extends' keyword.
program_19.java
/*
What is Inheritance?
A relation between the Parent class and Child class is called inheritance
or
A Mechanisam between the Base class and derived class is called inhertinace
Single Inheritance
*/
import java.util.*;
class Father
{
int fcode;
String fname;
Father(int fcode,String fname)
{
this.fcode=fcode;
this.fname=fname;
}
}
class Child extends Father
{
int code;
String name;
Child(int fcode,String fname,int code,String name)
{
super(fcode,fname);
this.code=code;
this.name=name;
}
void showDetails()
{
System.out.println("Father Code " + fcode);
System.out.println("Father Name " + fname);
System.out.println("Child Code " + code);
System.out.println("Child Name " + name);
}
}
class Prog1
{
public static void main(String args[])
{
int fcode,code;
String fname,name;
Scanner in=new Scanner(System.in);
System.out.println("Enter Father Code and Name");
fcode=in.nextInt();
fname=in.next();
System.out.println("Enter Child Code and Name");
code=in.nextInt();
name=in.next();
Child child =new Child(fcode,fname,code,name);
child.showDetails();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Parent Name: Parent
20. Multilevel Inheritance
Concept: Illustrates an inheritance chain where a class inherits from a derived class.
program_20.java
/*Multilevel Inheritance*/
import java.util.*;
class GFather
{
int gcode;
String gname;
GFather(int gcode,String gname)
{
this.gcode=gcode;
this.gname=gname;
}
}
class Father extends GFather
{
int fcode;
String fname;
Father(int gcode,String gname,int fcode,String fname)
{
super(gcode,gname);
this.fcode=fcode;
this.fname=fname;
}
}
class Child extends Father
{
int code;
String name;
Child(int gcode,String gname,int fcode,String fname,int code,String name)
{
super(gcode,gname,fcode,fname);
this.code=code;
this.name=name;
}
void showDetails()
{
System.out.println("GFather Code " + gcode);
System.out.println("GFather Name " + gname);
System.out.println("Father Code " + fcode);
System.out.println("Father Name " + fname);
System.out.println("Child Code " + code);
System.out.println("Child Name " + name);
}
}
class Prog2
{
public static void main(String args[])
{
int gcode,fcode,code;
String gname,fname,name;
Scanner in=new Scanner(System.in);
System.out.println("Enter GFather Code and Name");
gcode=in.nextInt();
gname=in.next();
System.out.println("Enter Father Code and Name");
fcode=in.nextInt();
fname=in.next();
System.out.println("Enter Child Code and Name");
code=in.nextInt();
name=in.next();
Child child =new Child(gcode,gname,fcode,fname,code,name);
child.showDetails();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Gname : Grand Father
Fname : Father
Cname : Child
21. Hierarchical Inheritance
Concept: Demonstrates multiple child classes inheriting from a single parent class.
program_21.java
/*Hirarchical Inheritance*/
import java.util.*;
class Father
{
int fcode;
String fname;
Father(int fcode,String fname)
{
this.fcode=fcode;
this.fname=fname;
}
}
class Child1 extends Father
{
int code;
String name;
Child1(int fcode,String fname,int code,String name)
{
super(fcode,fname);
this.code=code;
this.name=name;
}
void showDetails()
{
System.out.println("Father Code " + fcode);
System.out.println("Father Name " + fname);
System.out.println("Child Code " + code);
System.out.println("Child Name " + name);
}
}
class Child2 extends Father
{
int code;
String name;
Child2(int fcode,String fname,int code,String name)
{
super(fcode,fname);
this.code=code;
this.name=name;
}
void showDetails()
{
System.out.println("Father Code " + fcode);
System.out.println("Father Name " + fname);
System.out.println("Child Code " + code);
System.out.println("Child Name " + name);
}
}
class Prog3
{
public static void main(String args[])
{
int fcode,code1,code2;
String fname,name1,name2;
Scanner in=new Scanner(System.in);
System.out.println("Enter Father Code and Name");
fcode=in.nextInt();
fname=in.next();
System.out.println("Enter Child1 Code and Name");
code1=in.nextInt();
name1=in.next();
System.out.println("Enter Child2 Code and Name");
code2=in.nextInt();
name2=in.next();
Child1 child1 =new Child1(fcode,fname,code1,name1);
Child2 child2 =new Child2(fcode,fname,code2,name2);
child1.showDetails();
child2.showDetails();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Fname : Father
Son1 : Son 1
Son2 Details...
Fname : Father
Son2 : Son 2
22. Abstract Class Intro
Concept: Defines an abstract class containing both concrete and abstract methods, highlighting the need for child classes to provide implementations.
program_22.java
/*
Polymorphisam
method overridding
multiple Inheritance
Abstract Classes
The abstract class inside can accept ordinary methods
ordinary variables
Abstract methods(Declaration only)
Final variables
Note:Every abstract class before we must type abstract keyword
Interfaces
No need of to abstract key bofore the class name why becuase by default
all Interfaces are declared as abstract Classes
The interfaces can accept Static final varibales and
abstract methods(Declaration only)
*/
import java.util.*;
abstract class Bike
{
abstract void getBenifit();
}
class Honda extends Bike
{
void getBenifit()
{
System.out.println("Honda Running Smoothly");
}
}
class Bajaj extends Bike
{
void getBenifit()
{
System.out.println("Bajaj Gives More Milage");
}
}
class Bullet extends Bike
{
void getBenifit()
{
System.out.println("Bullet is More Power like (350 cc)");
}
}
class Prog1
{
public static void main(String args[])
{
int choice;
Scanner in=new Scanner(System.in);
do
{
System.out.println("Enter Your Choice(Honda-1,Bajaj-2,Bullet-3,Others-[4-9])");
choice=in.nextInt();
if(choice==1)
{
Bike honda = new Honda();
honda.getBenifit();
}
else if(choice==2)
{
Bike baja= new Bajaj();
baja.getBenifit();
}
else if(choice==3)
{
Bike bullet= new Bullet();
bullet.getBenifit();
}
else
{
System.out.println("Your Selection is out Range");
}
}while(choice>0 && choice<=3);
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
23. Abstract Class Implementation
Concept: Provides a concrete implementation for the abstract methods defined in the parent abstract class.
program_23.java
import java.util.*;
abstract class Area
{
String cname;
abstract float getArea(float param1,float param2);
public void showName()
{
cname="KKCC INFO SYSTEMS";
System.out.println(cname);
}
}
class Rectangle extends Area
{
float getArea(float l,float w)
{
return(l*w);
}
}
class Circle extends Area
{
float getArea(float r,float r1)
{
return(3.1416f*r*r);
}
}
class Prog2
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Area rectangle = new Rectangle();
Area circle= new Circle();
float a,r;
int l,w;
System.out.println("Enter l,w values");
l=in.nextInt();
w=in.nextInt();
a= rectangle.getArea(l,w);
rectangle.showName();
System.out.println("Rectangle Area = " + a);
System.out.println("Enter Radius value");
r=in.nextFloat();
circle.showName();
a=circle.getArea(r,0f);
System.out.println("Circle Area = " +a);
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
24. Interface Basics
Concept: Uses Interfaces to achieve full abstraction. Interfaces can contain only static final variables and abstract methods.
program_24.java
import java.util.*;
// interfaces are allowed only static final variables and abstract methods
// all interfaces are declared by default as abstract
interface Area
{
public float getArea(float l,float w);
public static final String objname="KKCC INFO SYSTEMS";
}
class Rectangle implements Area
{
public float getArea(float l,float w)
{
return(l*w);
}
}
class Circle implements Area
{
public float getArea(float r,float r1)
{
return(3.1416f*r*r);
}
}
class Square implements Area
{
public float getArea(float l,float w)
{
return(l*w);
}
}
class Prog3
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Area rectangle = new Rectangle();
Area circle= new Circle();
Area square=new Square();
float l,w,r,a;
System.out.println("Enter l,w values");
l=in.nextFloat();
w=in.nextFloat();
a= rectangle.getArea(l,w);
System.out.println("Rectangle Area = " + a);
System.out.println("Object Name=" + rectangle.objname);
System.out.println("Enter Radius values");
r=in.nextFloat();
a=circle.getArea(r,0.0f);
System.out.println("Circle Area = " + a);
System.out.println("Object Name=" + circle.objname);
System.out.println("Enter Side values");
l=in.nextFloat();
a=square.getArea(l,l);
System.out.println("Square Area ="+ a);
System.out.println("Object Name=" + square.objname);
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
25. Interface Inheritance
Concept: Shows how one interface can extend another, and how a class implements the derived interface.
program_25.java
interface Comp
{
public static final String objname="KKCC INFO SYSTEMS";
}
interface Area extends Comp
{
public float getArea(float a,float b);
}
class Rectangle implements Area
{
public float getArea(float l,float w)
{
return(l*w);
}
}
class Circle implements Area
{
public float getArea(float r,float r1)
{
return(3.1416f*r*r);
}
}
class Prog4
{
public static void main(String args[])
{
Area rectangle = new Rectangle();
Area circle= new Circle();
float a;
a= rectangle.getArea(5,6);
System.out.println("Rectangle Area = " + a);
System.out.println("Object Name=" + rectangle.objname);
a=circle.getArea(4.56f,0f);
System.out.println("Circle Area = " + a);
System.out.println("Object Name=" + circle.objname);
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Circle Area : 314.16
26. String Length and CharAt
Concept: String manipulation basics: finding the length of a string and extracting specific characters.
program_26.java
//String Functions Example
import java.util.*;
class Prog1
{
public static void main(String args[])
{
String name;
Scanner in=new Scanner(System.in);
int p;
name="Hellow How Are You";
System.out.println("Enter Which position character you want print");
p=in.nextInt();
System.out.println(name.charAt(p));
System.out.println(name.compareTo("hellow How Are You"));
System.out.println(name.compareToIgnoreCase("HELLOW HOW ARE YOU"));
System.out.println(name.concat(" Srinivas"));
System.out.println("Kunchala, ".concat(name));
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Length : 19
Char at 3 : U
27. Count Vowels and Consonants
Concept: Iterates through a string to count vowels, consonants, and digits, demonstrating conditional checks on characters.
program_27.java
import java.util.*;
class Prog2
{
public static void main(String args[])
{
String pwd,rpwd;
int cnt,r;
cnt=1;
Scanner in=new Scanner(System.in);
do {
System.out.println("Enter Password : ");
pwd=in.next();
System.out.println("Re-Type Password : ");
rpwd=in.next();
r=pwd.compareTo(rpwd);
if(r==0)
{
System.out.println("Passwors is Success");
}
else
{
System.out.println("Password Not Match Try Again !");
}
cnt+=1;
} while (r!=0 && cnt<=3);
if(r!=0 && cnt>0)
{
System.out.println("Your Attempts is completed. Try again after 30 Minutes!");
}
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(1)
Vowels : 2
Consonants : 3
Digits : 3
Spaces : 1
28. String Operations (Trim, Substring)
Concept: Utilizes common String class methods like trim(), toLowerCase(), and substring() for string formatting.
program_28.java
class Prog3
{
public static void main(String args[])
{
String name="SrinivasaRao",name1=" SrinivasaRao ";
System.out.println(name.length());
System.out.println(name.charAt(0));
System.out.println(name.indexOf('S'));
System.out.println(name.substring(3));
System.out.println(name.substring(3,6));
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
System.out.println("Rama is a good boy".replace("good","bad"));
System.out.println(name.equals("SrinivasaRao"));
System.out.println(name.equalsIgnoreCase("srinivasarao"));
System.out.println(name.concat(" Garu"));
System.out.println(name1.trim());
System.out.println(name.endsWith("Rao"));
System.out.println(name.startsWith("Sri"));
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(N) for string copies
Name1 : SrinivasaRao
Upper : SRINIVASARAO
Lower : srinivasarao
Sub String: nivas
29. String Tokenizer
Concept: Uses StringTokenizer to split a sentence into words based on delimiters.
program_29.java
//String Tokens
import java.util.Scanner;
import java.util.StringTokenizer;
public class Prog4 {
public static void main(String args[]) {
String name;
Scanner in = new Scanner(System.in);
name = in.nextLine();
StringTokenizer st = new StringTokenizer(name);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(N) string copies
Token : Welcome
Token : To
Token : Java
30. Math Methods
Concept: Explores the java.lang.Math class, using built-in methods for mathematical operations like max, pow, and sqrt.
program_30.java
/*Math Functions*/
class Prog5
{
public static void main(String args[])
{
int a = 28,b= 4;
double r;
System.out.println("Maximum number of a and b is: " + Math.max(a, b));
r= Math.sqrt(b);
System.out.println("Square root of b is: " +r);
System.out.println("Power of x and b is: " + Math.pow(a, b));
System.out.println("Logarithm of a is: " + Math.log(a));
System.out.println("Logarithm of b is: " + Math.log(b));
System.out.println("log10 of a is: " + Math.log10(a));
System.out.println("log10 of b is: " + Math.log10(b));
System.out.println("log1p of a is: " + Math.log1p(a)); // return the log of x + 1
System.out.println("exp of a is: " + Math.exp(a));
System.out.println("expm1 of a is: " + Math.expm1(a)); // return (a power of 2)-1
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Square root of 4 is: 2.0
Power of 28 and 4 is: 614656.0
31. Math Trigonometry
Concept: Converts degrees to radians and uses trigonometric functions provided by Math class.
program_31.java
class Prog6
{
public static void main(String args[])
{
double angle=30;
System.out.println("Degree to Radiuns is: " + Math.toRadians(angle));// converting values to radian
System.out.println("Degree to Radiuns is: " + Math.round(Math.toRadians(angle)));// converting values to radian
System.out.println("Sine value of a is: " + Math.sin(angle));
System.out.println("Cosine value of a is: " +Math.cos(angle));
System.out.println("Tangent value of a is: " +Math.tan(angle));
System.out.println("A Sine value of a is: " +Math.asin(angle));
System.out.println("A Cosine value of a is: " +Math.acos(angle));
System.out.println("A Tangent value of a is: " +Math.atan(angle));
System.out.println("H Sine value of a is: " +Math.sinh(angle));
System.out.println("H Cosine value of a is: " +Math.cosh(angle));
System.out.println("H Tangent value of a is: " +Math.tanh(angle));
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
cosine of 30.0 is: 0.8660254037844387
32. Decimal Format
Concept: Uses the DecimalFormat class to format floating point numbers to specific decimal places.
program_32.java
import java.text.DecimalFormat;
class Prog7
{
public static DecimalFormat df=new DecimalFormat("00.000");
public static void main(String args[])
{
double d=456.55656;
System.out.println("Absolute value of a is: " + Math.abs(-456));// converting values to radian
System.out.println("Max value of a is: " +Math.max(45,56));
System.out.println("Min value of a is: " +Math.min(45,56));
System.out.println("SQrt value of a is: " +Math.sqrt(12));
System.out.println("Cubic Root value of a is: " +Math.cbrt(12));
System.out.println("power value of a is: " +Math.pow(2,2));
System.out.println("sign value of a is: " +Math.signum(-456));
System.out.println("Ceil value of a is: " +Math.ceil(45.56f));
System.out.println("Floor value of a is: " +Math.floor(45.56f));
System.out.println("Round" + df.format(d));
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
Formatted : 10.12
33. Exception Handling
Concept: Demonstrates the use of try-catch blocks to handle runtime exceptions gracefully without crashing the program.
program_33.java
import java.util.*;
class Prog1
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int i,n,p;
String name[],element;
Vector vector=new Vector();
System.out.println("Enter n vaule");
n=in.nextInt();
System.out.println("Enter " + n + " Elements");
for(i=0;i<n;i++)
{
element=in.next();
vector.addElement(element);
}
for(i=0;i<vector.size();i++)
{
System.out.println((i + 1) + ")" + vector.elementAt(i));
}
System.out.println("Which position you want add element");
p=in.nextInt();
element=in.next();
vector.insertElementAt(element,p);
System.out.println("After Inserting Elements are");
for(i=0;i<vector.size();i++)
{
System.out.println((i + 1) + ")" + vector.elementAt(i));
}
System.out.println("Which position you want remove element");
p=in.nextInt();
vector.removeElementAt(p);
System.out.println("After Removing Elements are");
for(i=0;i<vector.size();i++)
{
System.out.println((i + 1) + ")" + vector.elementAt(i));
}
name=new String[vector.size()];
vector.copyInto(name);
vector.removeAllElements();
System.out.println("The String elements are");
for(i=0;i<name.length;i++)
{
System.out.println((i+1) + ")" + name[i]);
}
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
10
0
Divide By Zero Error !!
End of the code
34. Multithreading Intro
Concept: Theoretical overview of multithreading, allowing multiple processes to execute concurrently.
program_34.java
/*
What is multithread ?
multithread is a separate program.
A Single processor can do the multple programs simultaneously.
it executes concurrently or parallely depends upon the system speed.
In Operating system we are calling Multitasking
In Programming Languages we are calling Multithrading
*/
class Prog1 extends Thread
{
public void run()
{
try
{
System.out.println("\nMy First Thread is Started");
for(int i=1;i<=5;i++)
{
System.out.println("\ni=" + i);
if(i==1 || i==3)
{
sleep(1000);
}
}
System.out.println("\nThread is Completed");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
Prog1 mt=new Prog1 ();
mt.start();
System.out.println("The Above thread is started");
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
35. Thread extending Thread Class
Concept: Creates a separate execution thread by extending the Thread class and overriding the run() method.
program_35.java
class Count extends Thread {
Count() {
start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
System.out.println("Thread run is Complete");
}
}
class Prog2 {
public static void main(String args[]) {
Count cnt = new Count();
// cnt.start();
try {
while (cnt.isAlive()) {
System.out.println("Thread will be alive till the child thread is live");
Thread.sleep(3000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over");
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(1)
Count : 1
Count : 2
Count : 3
Main thread complete
36. Thread Implementing Runnable
Concept: Another way to create a thread, using the Runnable interface, allowing the class to inherit from another class if needed.
program_36.java
class MultiThread implements Runnable
/*class MultiThread extends Thread*/
{
public void run()
{
try
{
System.out.println("Thread is in running Start.");
for(int i=1;i<=5;i++)
{
System.out.println("I=" + i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Prog3
{
public static void main(String args[])
{
MultiThread mt=new MultiThread();
Thread newobj =new Thread(mt);
/*MultiThread newobj=new MultiThread();*/
newobj.start();
}
}
Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
37. Runnable Interface with Thread Class
Concept: Passes a Runnable object to a Thread constructor and starts concurrent execution.
program_37.java
class Count implements Runnable
//class Count extends Thread
{
Thread mythread=new Thread(this, "Child Thread");
Count()
{
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class Prog4
{
public static void main(String args[])
{
Count cnt = new Count();
// Thread mythread=new Thread(cnt);
// mythread.start();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Thread will be alive till the child thread is live");
Thread.sleep(3000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println("Thread run is over" );
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(1)
Printing from thread...
Main thread ending.
38. Multiple Threads Running
Concept: Demonstrates multiple threads running simultaneously and sleeping for specific intervals.
program_38.java
class ThreadA extends Thread
{
public void run()
{
try
{
System.out.println("\nThread A is running Start.");
for(int i=1;i<=5;i++)
{
System.out.println("\nThread A=" + i);
}
System.out.println("\nThread A Closed");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class ThreadB extends Thread
{
public void run()
{
try
{
System.out.println("\nThread B is running Start.");
for(int i=1;i<=5;i++)
{
System.out.println("\nThread B=" + i);
}
System.out.println("\nThread B Closed");
}
catch(Exception e)
{
}
}
}
class ThreadC extends Thread
{
public void run()
{
try
{
System.out.println("\nThread C is running Start.");
for(int i=1;i<=5;i++)
{
System.out.println("\nThread C=" + i);
}
System.out.println("\nThread C Closed");
}
catch(Exception e)
{
}
}
}
class Prog5
{
public static void main(String args[])
{
try
{
ThreadA a=new ThreadA();
ThreadB b=new ThreadB();
ThreadC c=new ThreadC();
a.setPriority(Thread.MIN_PRIORITY);
b.setPriority(Thread.MAX_PRIORITY);
c.setPriority(Thread.NORM_PRIORITY);
System.out.println(a.getPriority());
System.out.println(b.getPriority());
System.out.println(c.getPriority());
a.start();
b.start();
c.start();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Analysis
- Time Complexity: O(N)
- Space Complexity: O(1)
Thread B is running...
Thread C is running...
...
Conclusion & Next Steps
We hope these Java programs have helped you understand core Object-Oriented concepts and syntax. The best way to learn Java is by doing, so we encourage you to copy these snippets into your IDE, modify them, and see how they behave. Keep exploring more complex data structures to hone your skills.