You are on page 1of 36

NATIONAL P.

G COLLEGE
An Autonoumous,CPE and NAAC Grade ‘A’

PROJECT FILE

Object Oriented Concepts Using


JAVA
&

GIVEN BY :- PRAMOD DIXIT & ANEES ALAM

SUBMITTED BY :- AMAN AHMAD


Java OOPs Concepts
OOPs. Object-Oriented Programming is a paradigm that provides many concepts,
such as inheritance, data binding, polymorphism, etc.
 Simula is considered the first object-oriented programming language. The
programming paradigm where everything is represented as an object is known as
a truly object-oriented programming language
 Smalltalk is considered the first truly object-oriented programming language.
 The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
 The main aim of object-oriented programming is to implement real-world
entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:

 Object

 Class

 Inheritance

 Polymorphism

 Abstraction

 Encapsulation

JAVA & DBMS PROJECT 1


Object
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and


takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well
as behaviors like wagging the tail, barking, eating, etc.

Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space

Inheritance

JAVA & DBMS PROJECT 2


When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example:
to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It
arises when classes are aware of each other. If a class has the details information of
another class, there is strong coupling. In Java, we use private, protected, and public
modifiers to display the visibility level of a class, method, and field.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined
task. A single well-defined task is done by a highly cohesive method. The weakly
cohesive method will split the task into separate parts. The java.io package is a highly
cohesive package because it has I/O related classes and interface. However, the
java.util package is a weakly cohesive package because it has unrelated classes and
interfaces.

 Association

Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association
between the objects:

JAVA & DBMS PROJECT 3


 One to One
 One to Many
 Many to One, and
 Many to Many

One country can have one prime minister (one to one), and a prime minister can have
many ministers (one to many). Also, many MP's can have one prime minister (many
to one), and many ministers can have many departments (many to many)

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship
where one object contains other objects as a part of its state. It represents the weak
relationship between objects. It is also termed as a has-a relationship in Java. Like,
inheritance represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a
strong relationship between the containing object and the dependent object. It is the
state where containing objects do not have an independent existence. If you delete the
parent object, all the child objects will be deleted automatically.

Advantage of OOPs over Procedure-oriented


programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-
oriented programming language, it is not easy to manage if code grows as project size
increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming


language, global data can be accessed from anywhere.

JAVA & DBMS PROJECT 4


Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.

JAVA & DBMS PROJECT 5


LIBRARY CONCEPT IN JAVA
Library Classes :- These are the predefined classes provided by Java system present
in packages. These classes contain related library functions like String Math, etc. All
the library classes belong to some package.

Library Functions:- These are the inbuilt functions present in Java library classes,
provided by Java system to help programmers to perform their task in an easier way.

Library Classes are to be included in java program using a package.

Package:-Packages are collection of classes or subclasses. We have different


packages defined to import or include the classes required in the Java program.

Java the platform contains around 4,000 classes/interfaces .

Some of the important java libraries are

 Java.lang is for all the basic classes that are actually imported automatically
(implicitly) because it is all the basic ones (String, Integer, Double, etc)
 Java.util contains all your data structures you learned in school and more.
Read the documentation, and the more you know and practice, the better
 Java.io for file reading. Look into java.util.Scanner for simple file reading, but
for any more complicated, low level file reading info, use its built for efficiency,
while Scanner is for simplicity
 Java.math if you ever need to use arbitrary precision values (built-in in
python, not in java)
 Java.net for sockets, connections, etc
 Java.swing for GUI, which is an extension of the older java.awt

JAVA STRING FUNCTIONS

 Tolowercase-Converts characters in the string to lower case.


 ToupperCase-Converts characters in the string to upper case.
 IndexOf(Int n)-Returns the index of the character/susbtring.
 Substring()overloadedfuction-Returns a substring from the given string.
 startsWith(String)-Checks if the string begins with the given string.
 endsWith(String)-Checks if the string ends with the given string.
 chartAt(Int i)-Returns the character at the given index
 compareTo()- Compares two strings in the dictionary order.
 equals()- Compares two strings.
 equalsIgnoreCase()- Compares two strings ignoring case differences.

JAVA & DBMS PROJECT 1


Inheritance
Inheritance is a mechanism that allows one class to inherit properties or
behaviors from another class. Multiple classes can inherit from the same
parent class, forming a tree-like hierarchy structure. Inheriting classes can
add features beyond those inherited from the parent class to allow for unique
behavior.
Inheritance is essential to advanced Object Oriented Programming (OOP) as
it allows you to reuse one class’s features across your program without
replicating code.
Inheritance is often used to represent categories (parent classes) and sub-
categories (subclasses). The parent class sets the features present in all
objects regardless of subcategory, while each subclass represents a smaller,
more specific category.
Inheritance has three main advantages:

1. Reusability: Inheritance allows you to reuse the features of an


existing class an unlimited number of times across any class that
inherits that class. You can keep consistent functionality across all
objects of the same type without rewriting the code.
2. Code Structure: Inheritance provides a clear, drawable logic
structure for your program. It allows developers to understand your
code as a collection of related but unique categories rather than
simply a block of code.
3. Data Hiding: The base class can be set to keep some data private so
that it cannot be altered by the derived class. This is an example of
encapsulation, where access to data is restricted to only the classes
that need it for their role.
Each programming language has slightly different terminology for
inheritance. In Java, the parent class is called the superclass, and the
inheritor class is called the subclass. Developers may also call superclasses
base or parent classes and subclasses derived or child classes.
Subclasses are linked to superclasses using the extends keyword during their
definition. Subclasses can define new local methods or fields to use or can
use the super keyword to call inherited methods or the super constructor.

EXAMPLE
class Animal {

// field and method of the parent class


String name;

JAVA & DBMS PROJECT 1


public void eat() {
System.out.println("I can eat");
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass


public void display() {
System.out.println("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access field of superclass


labrador.name = "Rohu";
labrador.display();

// call method of superclass


// using object of subclass
labrador.eat();

}
}

output

My name is Rohu

I can eat

RECURSION
A method that calls itself is known as a recursive method. And, this process
is known as recursion.

JAVA & DBMS PROJECT 2


A physical world example would be to place two parallel mirrors facing
each other. Any object in between them would be reflected recursively.

FOR EXAMPLE

1) public class Recursion1

 {  

static int count=0;  

static void p(){  

count++;  

if(count<=5){  

System.out.println("hello "+count);  

p();  

}  

}  

public static void main(String[] args) {  

p();  

}  

}  

hello 1 hello 2 hello 3 hello 4 hello 5

2) public class Recursion2

 {  

    static int factorial(int n){      

          if (n == 1)      

            return 1;      

          else      

            return(n * factorial(n-1));      

}    

public static void main(String[] args) {  

System.out.println("Factorial of 5 is: "+factorial(5));  

}  

}  
Factorial of 5 is: 120

JAVA & DBMS PROJECT 3


Abstracts & Interface
INTERFACE :-The interface is a blueprint that can be used to implement a
class. The interface does not contain any concrete methods (methods that
have code). All the methods of an interface are abstract methods.

An interface cannot be instantiated. However, classes that implement


interfaces can be instantiated. Interfaces never contain instance variables
but, they can contain public static final variables (i.e., constant class
variables)

ABSTRACT :- A class which has the abstract keyword in its declaration is


called abstract class. Abstract classes should have at least one abstract
method. , i.e., methods without a body. It can have multiple concrete
methods.

Abstract classes allow you to create blueprints for concrete classes. But the
inheriting class should implement the abstract method.

Abstract classes cannot be instantiated.

Important Reasons For Using Interfaces

 Designed to support dynamic method resolution at run time


 It helps you to achieve loose coupling.
 Allows you to separate the definition of a method from the inheritance
hierarchy.
 Interaces are used to achieve abstraction

Important Reasons For Using Abstract Class

 Abstract classes offer default functionality for the subclasses.


 Provides a template for future specific classes
 Helps you to define a common interface for its subclasses
 Abstract class allows code reusability.

Abstract class vs Interface

JAVA & DBMS PROJECT 4


Type of methods: Interface can have only abstract methods. An abstract
class can have abstract and non-abstract methods. From Java 8, it can have
default and static methods also.
Final Variables: Variables declared in a Java interface are by default final.
An abstract class may contain non-final variables.
Type of variables: Abstract class can have final, non-final, static and non-
static variables. The interface has only static and final variables.
Implementation: Abstract class can provide the implementation of the
interface. Interface can’t provide the implementation of an abstract class.
Inheritance vs Abstraction: A Java interface can be implemented using the
keyword “implements” and an abstract class can be extended using the
keyword “extends”.
Multiple implementations: An interface can extend another Java interface
only, an abstract class can extend another Java class and implement multiple
Java interfaces.
Accessibility of Data Members: Members of a Java interface are public by
default. A Java abstract class can have class members like private,protected
etc.

FUNCTION OVERLOADING IN JAVA

Function Overloading in Java occurs when there are functions having the
same name but have different numbers of parameters passed to it, which can
be different in data like int, double, float and used to return different values
are computed inside the respective overloaded method. Function
overloading is used to reduce complexity and increase the efficiency of the
program by involving more functions that are segregated and can be used to
distinguish among each other with respect to their individual functionality.
Overloaded functions are related to compile-time or static polymorphism.
There is also a concept of type conversion, which is basically used in
overloaded functions used to calculate the conversion of type in variables.
EXAMPLE:-
//Java program with overloaded main()
import java.io.*;
public class Test
{
// First main method which is created
public static void main(String[] args)
{
System.out.println("Main function called");
Test.main("Everyone");
}
// First overloaded main method
public static void main(String ar1)
{

JAVA & DBMS PROJECT 5


System.out.println("Hi, " + ar1);
Test.main("Hello Everyone", "Buenos dias");
}
//Second overloaded main method
public static void main(String ar1, String ar2)
{
System.out.println("Mi todo eres tu, " + ar1 + ", " + ar2);
}
}

EXCEPTION HANDELLING
An exception is an unexpected event that occurs during program execution.
It affects the flow of the program instructions which can cause the program
to terminate abnormally.

An exception can occur for many reasons. Some of them are:

 Invalid user input


 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Java Exception hierarchy

Here is a simplified diagram of the exception hierarchy in Java.

JAVA & DBMS PROJECT 6


As you can see from the image above, the Throwable class is the root class in the
hierarchy.

Note that the hierarchy splits into two branches: Error and Exception.

Errors

Errors represent irrecoverable conditions such as Java virtual


machine (JVM) running out of memory, memory leaks, stack overflow
errors, library incompatibility, infinite recursion, etc.

Errors are usually beyond the control of the programmer.

Exceptions

Exceptions can be caught and handled by the program.


When an exception occurs within a method, it creates an object. This object
is called the exception object.
It contains information about the exception such as the name and description
of the exception and state of the program when the exception occurred

.Java Exception Types

JAVA & DBMS PROJECT 7


The exception hierarchy also has two branches:Runtime
exception and IO exception.

RuntimeException

A runtime exception happens due to a programming error. They are


also known as unchecked exceptions.

These exceptions are not checked at compile-time but run-time.


Some of the common runtime exceptions are:

 Improper use of an API - Illegalargumentexception

 Null pointer access (missing the initialization of a variable)


- Nullpointerexception

 Out-of-bounds array access


- ArrayIndexOutOfBoundsException

 Dividing a number by 0 - ArthemeticException

You can think about it in this way. “If it is a runtime exception, it is


your fault”.

The NullPointerException would not have occurred if you had


checked whether the variable was initialized or not before using it.

An ArrayIndexOutOfBoundsException would not have occurred if


you tested the array index against the array bounds.

 IOException
An IOException is also known as a checked exception. They are
checked by the compiler at the compile-time and the programmer is
prompted to handle these exceptions.

Some of the examples of checked exceptions are:

 Trying to open a file that doesn’t exist results


in Filenotfoundexception

JAVA & DBMS PROJECT 8


 Trying to read past the end of a file
Different approaches to handle exceptions in Java.

 try...catch block
 finally block
 throw and throws keyword

1.  try...catch block

The try-catch block is used to handle exceptions in Java. Here's the syntax


of try....catch block:

try {

// code

}catch(Exception e) {

// code

Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block


cannot be used without the try block.

EXAMPLE
class Main {

public static void main(String[] args) {

try {

// code that generate exception

int divideByZero = 5 / 0;

System.out.println("Rest of code in try block");

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

JAVA & DBMS PROJECT 9


}

ArithmeticException => / by zero

2. finally block

In Java, the finally block is always executed no matter whether there is an


exception or not.
The finally block is optional. And, for each try block, there can be only
one finally block.
The basic syntax of finally block is:

try {

//code

}catch (ExceptionType1 e1) {

// catch block

}finally {

// finally block always executes

If an exception occurs, the finally block is executed after


the try...catch block. Otherwise, it is executed after the try block. For
each try block, there can be only one finally block.

EXAMPLE
class Main {
public static void main(String[] args) {
try {

JAVA & DBMS PROJECT 10


// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}

ArithmeticException => / by zero

This is the finally block

3.  throw and throws keyword

The Java throw keyword is used to explicitly throw a single


exception.
When we throw an exception, the flow of the program moves from
the try block to the catch block.

class Main {

public static void divideByZero() {

// throw an exception

throw new ArithmeticException("Trying to divide by 0");

public static void main(String[] args) {

divideByZero();

JAVA & DBMS PROJECT 11


}

Exception in thread "main" java.lang.ArithmeticException: Trying


to divide by 0

at Main.divideByZero(Main.java:5)

at Main.main(Main.java:9)

n the above example, we are explicitly throwing


the  ArithmeticException  using the  throw  keyword.

Similarly, the  throws  keyword is used to declare the type of


exceptions that might occur within the method. It is used in the
method declaration.

Example:

Java throws keyword

import java.io.*;

class Main {

// declareing the type of exception

public static void findFile() throws IOException {

// code that may generate IOException

File newFile = new File("test.txt");

FileInputStream stream = new FileInputStream(newFile);

JAVA & DBMS PROJECT 12


public static void main(String[] args) {

try {

findFile();

catch (IOException e) {

System.out.println(e);

Output

java.io.FileNotFoundException: test.txt (The system cannot find


the file specified)

When we run this program, if the file test.txt does not


exist, fileInputStreamthrows a FileNotFoundException which
extends the IOException class.

The findfile() method specifies that an IOException can be thrown.


The main() method calls this method and handles the exception if it
is thrown.

If a method does not handle exceptions, the type of exceptions that


may occur within it must be specified in the throw clause

program.

JAVA & DBMS PROJECT 13


 How to Print an Integer entered by an user
import java.util.Scanner;
public class HelloWorld {

public static void main(String[] args) {

// Creates a reader instance which takes


// input from standard input - keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");

// nextInt() reads the next integer from the keyboard


int number = reader.nextInt();

// println() prints the following line to the output screen


System.out.println("You entered: " + number);
}
}

 Program to Add Two Integers


class Main {

public static void main(String[] args) {

System.out.println("Enter two numbers");


int first = 10;
int second = 20;

System.out.println(first + " " + second);

// add two numbers


int sum = first + second;
System.out.println("The sum is: " + sum);
}
}

JAVA & DBMS PROJECT 14


 Multiply Two Floating-Point Numbers
public class MultiplyTwoNumbers {

public static void main(String[] args) {

float first = 1.5f;


float second = 2.0f;

float product = first * second;

System.out.println("The product is: " + product);


}
}

Find ASCII value of a character


public class AsciiValue {

public static void main(String[] args) {

char ch = 'a';
int ascii = ch;
// You can also cast char to int
int castAscii = (int) ch;

System.out.println("The ASCII value of " + ch + " is: " +


ascii);
System.out.println("The ASCII value of " + ch + " is: " +
castAscii);
}
}

 Compute Quotient and Remainder


public class QuotientRemainder {

public static void main(String[] args) {

int dividend = 25, divisor = 4;

int quotient = dividend / divisor;


int remainder = dividend % divisor;

System.out.println("Quotient = " + quotient);


System.out.println("Remainder = " + remainder);
}
}

JAVA & DBMS PROJECT 15


 Swap two numbers using temporary variable
public class SwapNumbers {

public static void main(String[] args) {

float first = 1.20f, second = 2.45f;

System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);

// Value of first is assigned to temporary


float temporary = first;

// Value of second is assigned to first


first = second;

// Value of temporary (which contains the initial value of


first) is assigned to second
second = temporary;

System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}

 Check whether a number is even or odd using


if...else statement
import java.util.Scanner;
public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

if(num % 2 == 0)
System.out.println(num + " is even");
else

JAVA & DBMS PROJECT 16


System.out.println(num + " is odd");
}
}

 Check whether an alphabet is vowel or


consonant using if..else statement
public class VowelConsonant {

public static void main(String[] args) {

char ch = 'i';

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==


'u' )
System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");

}
}

 Find the largest number among three using


nested if..else statement
public class Largest {

public static void main(String[] args) {

double n1 = -4.5, n2 = 3.9, n3 = 5.5;

if(n1 >= n2) {


if(n1 >= n3)
System.out.println(n1 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
} else {
if(n2 >= n3)
System.out.println(n2 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
}
}
}

JAVA & DBMS PROJECT 17


 Java Program to Find Roots of a Quadratic
Equation
public class Main {

public static void main(String[] args) {

// value a, b, and c
double a = 2.3, b = 4, c = 5.6;
double root1, root2;

// calculate the determinant (b2 - 4ac)


double determinant = b * b - 4 * a * c;

// check if determinant is greater than 0


if (determinant > 0) {

// two real and distinct roots


root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
}

// check if determinant is equal to 0


else if (determinant == 0) {

// two real and equal roots


// determinant is equal to 0
// so -b + 0 == -b
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}

// if determinant is less than zero


else {

// roots are complex number and distinct


double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}

 Java Program to Check a Leap Year


public class Main {

public static void main(String[] args) {

// year to be checked
int year = 1996;
boolean leap = false;

JAVA & DBMS PROJECT 18


// if the year is divided by 4
if (year % 4 == 0) {

// if the year is century


if (year % 100 == 0) {

// if year is divided by 400


// then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}

// if the year is not century


public class Main {

public static void main(String[] args) {

// year to be checked
int year = 1996;
boolean leap = false;

// if the year is divided by 4


if (year % 4 == 0) {

// if the year is century


if (year % 100 == 0) {

// if year is divided by 400


// then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}

// if the year is not century

 Check if a Number is Positive or Negative


using if else
public class PositiveNegative {

public static void main(String[] args) {

double number = 12.3;

// true if number is less than 0


if (number < 0.0)
System.out.println(number + " is a negative number.");

// true if number is greater than 0


else if ( number > 0.0)
System.out.println(number + " is a positive number.");

JAVA & DBMS PROJECT 19


// if both test expression is evaluated to false
else
System.out.println(number + " is 0.");
}
}

 Java Program to Check Alphabet using


ternary operator
public class Alphabet {

public static void main(String[] args) {

char c = 'A';

String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <=
'Z')
? c + " is an alphabet."
: c + " is not an alphabet.";

System.out.println(output);
}
}

 Sum of Natural Numbers using for loop


public class SumNatural {

public static void main(String[] args) {

int num = 100, sum = 0;

for(int i = 1; i <= num; ++i)


{
// sum = sum + i;
sum += i;
}

System.out.println("Sum = " + sum);


}
}

 Find Factorial of a number using for loop

JAVA & DBMS PROJECT 20


public class Factorial {

public static void main(String[] args) {

int num = 10;


long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}

 Generate Multiplication Table using for


loop
public class MultiplicationTable {

public static void main(String[] args) {

int num = 5;
for(int i = 1; i <= 10; ++i)
{
System.out.printf("%d * %d = %d \n", num, i, num * i);
}
}
}

 Display Fibonacci Series Using for Loop


class Main {
public static void main(String[] args) {

int n = 10, firstTerm = 0, secondTerm = 1;


System.out.println("Fibonacci Series till " + n + " terms:");

for (int i = 1; i <= n; ++i) {


System.out.print(firstTerm + ", ");

JAVA & DBMS PROJECT 21


// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

 Find GCD of two numbers using for loop and


if statement
class Main {
public static void main(String[] args) {

// find GCD between n1 and n2


int n1 = 81, n2 = 153;

// initially set to gcd


int gcd = 1;

for (int i = 1; i <= n1 && i <= n2; ++i) {

// check if i perfectly divides both n1 and n2


if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}

System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);


}
}

 LCM using while Loop and if Statement


public class Main {
public static void main(String[] args) {

int n1 = 72, n2 = 120, lcm;

// maximum number between n1 and n2 is stored in lcm


lcm = (n1 > n2) ? n1 : n2;

// Always true
while(true) {
if( lcm % n1 == 0 && lcm % n2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", n1, n2,
lcm);
break;
}
++lcm;
}

JAVA & DBMS PROJECT 22


  }
}

 Display uppercased alphabet using for loop


class Main {
public static void main(String[] args) {

char c;

for(c = 'A'; c <= 'Z'; ++c)


System.out.print(c + " ");
}
}

 Count Number of Digits in an Integer using


while loop
public class Main {

public static void main(String[] args) {

int count = 0, num = 0003452;

while (num != 0) {
// num = num/10
num /= 10;
++count;
}

System.out.println("Number of digits: " + count);


}
}

 Reverse a Number using a while loop


class Main {
public static void main(String[] args) {

int num = 1234, reversed = 0;

// run loop until num becomes 0


while(num != 0) {

// get last digit from num


int digit = num % 10;
reversed = reversed * 10 + digit;

JAVA & DBMS PROJECT 23


// remove the last digit from num
num /= 10;
}

System.out.println("Reversed Number: " + reversed);


}
}

 Calculate power of a number using a while


loop
class Main {
public static void main(String[] args) {

int base = 3, exponent = 4;

long result = 1;

while (exponent != 0) {
result *= base;
--exponent;
}

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


}
}

 Program to Check Palindrome String


class Main {
public static void main(String[] args) {

String str = "Radar", reverseStr = "";

int strLength = str.length();

for (int i = (strLength - 1); i >=0; --i) {


reverseStr = reverseStr + str.charAt(i);
}

if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
}
}

JAVA & DBMS PROJECT 24


 Program to Check Prime Number using a for
loop
public class Main {

public static void main(String[] args) {

int num = 29;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

 Prime Numbers Between two Intervals


public class Prime {

public static void main(String[] args) {

int low = 20, high = 50;

while (low < high) {


boolean flag = false;

for(int i = 2; i <= low/2; ++i) {


// condition for nonprime number
if(low % i == 0) {
flag = true;
break;
}
}

if (!flag && low != 0 && low != 1)


System.out.print(low + " ");

++low;
}
}
}

JAVA & DBMS PROJECT 25


 Program to Add Two Matrices
public class AddMatrices {

public static void main(String[] args) {


int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };

// Adding Two matrices


int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}

// Displaying the result


System.out.println("Sum of two matrices is: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

 Program to print half pyramid using *


public class Main {

public static void main(String[] args) {


int rows = 5;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= i; ++j) {
System.out.print("* ");
}
System.out.println();
}
}
}

JAVA & DBMS PROJECT 26


 Program to print half pyramid a using numbers
public class Main {

public static void main(String[] args) {


int rows = 5;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

 Program to print half pyramid using alphabets


public class Main {

public static void main(String[] args) {


char last = 'E', alphabet = 'A';

for (int i = 1; i <= (last - 'A' + 1); ++i) {


for (int j = 1; j <= i; ++j) {
System.out.print(alphabet + " ");
}
++alphabet;

System.out.println();
}
}
}

JAVA & DBMS PROJECT 27


 Program to print full pyramid using *
public class Main {

public static void main(String[] args) {


int rows = 5, k = 0;

for (int i = 1; i <= rows; ++i, k = 0) {


for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}

while (k != 2 * i - 1) {
System.out.print("* ");
++k;
}

System.out.println();
}
}
}

 Print Pascal's triangle


public class Main {

public static void main(String[] args) {


int rows = 6, coef = 1;

for(int i = 0; i < rows; i++) {


for(int space = 1; space < rows - i; ++space) {
System.out.print(" ");
}

for(int j = 0; j <= i; j++) {


if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

System.out.printf("%4d", coef);
}

System.out.println();
}
}
}

JAVA & DBMS PROJECT 28


JAVA & DBMS PROJECT 29

You might also like