0% found this document useful (0 votes)
3 views

Java Training Program

The document outlines a Java basics training program, covering fundamental concepts such as data types, input handling, control statements (if, else, switch), and operators. It includes multiple example programs demonstrating these concepts, such as addition, string comparison, and logical operators. The training is designed to help learners understand and apply Java programming skills effectively.

Uploaded by

santhoshupsc5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Training Program

The document outlines a Java basics training program, covering fundamental concepts such as data types, input handling, control statements (if, else, switch), and operators. It includes multiple example programs demonstrating these concepts, such as addition, string comparison, and logical operators. The training is designed to help learners understand and apply Java programming skills effectively.

Uploaded by

santhoshupsc5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

JAVA BASICS

Training Program
Program 1-Welcome

public class welcome


{
public static void main(String[] args) {
System.out.print("Welcome to Java
Training")
}
}
Program 2 – Data Type
• public class datatype {
• public static void main(String[] args) {
• boolean flag = false;
• byte b = 10;
• short s = 150;
• int i = 20000;
• long l = 1000000;
• float flo = 10.8234f;
• double d = 12.0987;
• char c = 'E';
• String str = "II CSE";

// Output the values of the variables
• System.out.println("Boolean type = " + flag);
• System.out.println("Character type = " + c);
• System.out.println("String Object = " + str);
• System.out.println("Integer: byte = " + b + ", short = " + s);
• System.out.println("Integer: int = " + i + ", long = " + l);
• //System.out.println("Floating point: float = " + flo + ", double = " +
d);
• System.out.println("Floating point: float = " + String.format("%.2f", flo) + ",
double = " + String.format("%.2f", d));
Program 3-Addition

public class addition


{
public static void main(String[] args)
{
int a=10;
int b=20;
int c=30;
System.out.print(a+b+c);
}
}
•public class addition
•{
• public static void main(String[] args)
{
• int a=10;
• int b=20;
• int c=30;
• int e=a+b+c;
• System.out.print(e);
• }
•}
Program 4 – Scanner Input

• import java.util.Scanner;
• import java.util.Scanner;
public class scanner {
public class scanner1 {
• public static void main(String[]
args) { public static void main(String[]
• Scanner doc = new
Scanner(System.in); args) {
• float a = doc.nextFloat(); Scanner doc = new
• System.out.print(a);
• } Scanner(System.in);
• } float a = doc.nextFloat();
import java.util.Scanner;
int b = doc.nextInt();
public class scanner2 System.out.print(a+b);
{
public static void main(String[] args) }
{ }
Scanner doc = new Scanner(System.in);
String a = doc.nextLine();
System.out.print(a);
}
Program 5 – Get Input Variable for Personal Details (name, Age and Address)

• import java.util.Scanner;

public class scanner3
• {
• public static void main(String[] args)
• {
• Scanner Personal = new Scanner(System.in);
• String Name = Personal.nextLine();
• int Age = Personal.nextInt();
• Personal.nextLine();
• String Address = Personal.nextLine();
• System.out.println("My name is " + Name);
• System.out.println("Age is" + Age);
• System.out.print("Address is" + Address);
• }
• }
•• Program 6 – Get Input Variable for all your subject marks and find its total and average

••
••
••
••
••







••Program 6 – Get Input Variable for all your subject marks and find its total and average in decimal

••
••
••
••
••






((English+Tamil+Maths+Science+EVS)/5)
+
•• " %");
Program 7 – if statement
• public class ifelse
public class ifelse1
• {
{
• public static void main(String[]
args) public static void main(String[]
• { args)
• boolean vidamuyarchi = true; {
• if (vidamuyarchi) boolean vidamuyarchi =
• { false;
• System.out.print("Watch if (vidamuyarchi)
FDFS"); {
• } System.out.print("Watch
• } FDFS");
• } }
}
}
System o/p – Watch FDFS System o/p – No o/p
Program 8 – if else statement

public class ifelse2 { public class ifelse2 {


public static void main(String[] args) public static void main(String[]
{ args)
boolean vidamuyarchi = true; {
if (vidamuyarchi) boolean vidamuyarchi = false;
{ if (vidamuyarchi)
System.out.print("Watch FDFS"); {
} System.out.print("Watch FDFS");
else }
{ else
System.out.print("Watch OTT {
movies"); System.out.print("Watch OTT
} movies");
} }
}
}
}
System o/p – Watch FDFS System o/p – Watch OTT movies
Program 9 – String Comparision

public class stringcompare { public class stringcompare {


public static void main(String[] args) { public static void main(String[] args) {
String a = "Raja"; String a = new String("Raja");
String b = "Raja"; String b = "Raja";
System.out.print(a==b); System.out.print(a==b);
} }
} }
Output : true Output : false

public class stringcompare {


public static void main(String[] args) {
String a = new String("Raja");
String b = "Raja";
System.out.print(a.equals(b));
}
}
Output : true
In string, if You are using == it will compare the address (reference).
To avoid that use a.equals(b),
Program 10 – String Comparision

import java.util.Scanner;
public class stringcompare1 {
Get input for the vijay’s next movie and public static void main(String[] args) {
comapre with his movie name. Scanner VNM = new Scanner(System.in);
If it is correct say
“You are right”
wrong then say
System.out.print("What is the name of
“you are wrong Vijay's next movie = ");

String a = VNM.nextLine();
String vijayNextMovie = "Jananayagam";

if (a.equals(vijayNextMovie))
{
System.out.print("You are Right");
}
else {
System.out.print("You are Wrong");
}
VNM.close();
} }
Operator – (Comparision ==, !=, <, >, <=, >=)

public class operator { public class operator2 {


public static void main(String[] args) public static void main(String[] args) {
{ int num1 = 20;
int num1 = 20; int num2 = 40;
int num2 = 40; System.out.print(num1 == num2);
System.out.print(num1>num2); }
} }
} Output - false
Output - false

public class operator1 { public class operator3 {


public static void main(String[] args) public static void main(String[] args)
{ {
int num1 = 20; int num1 = 20;
int num2 = 40; int num2 = 20;
System.out.println(num1<num2); System.out.print(num1<=num2);
} }
} }
Output - true Output – true
Program 11 – comparision Operator
import java.util.Scanner;

Problem Statement public class operator4


You call two values from user and {
compare it with any one of the operator public static void main(String[] args)
{
Scanner num = new Scanner(System.in);
System.out.print("Enter the first number = ");
Output: int number1 = num.nextInt();
Enter the first number = 20 System.out.print("Enter the second number = ");
Enter the second number = 30 int number2 = num.nextInt();
Both numbers are different
if (number1 == number2)
{
System.out.print(" Both number are same");
}
else
{
System.out.print(" Both number are different");
}
}
}
Operator – (Logical &&, ||, !)

Logical operators in Java are used to perform logical operations on boolean expressions. The most
common logical operators are:

1.AND (&&): Returns true if both conditions are true, otherwise returns false.
•Example: if (a > 0 && b > 0)
•This condition will be true if both a and b are greater than 0.

2.OR (||): Returns true if at least one of the conditions is true, otherwise returns false.
•Example: if (a > 0 || b > 0)
•This condition will be true if either a or b is greater than 0.

3.NOT (!): Reverses the logical state of its operand. If the condition is true, it becomes false, and vice
versa.
•Example: if (!(a > 0))
•This condition will be true if a is not greater than 0.
Program 12 – Logical Operator(Logical &&, ||, !)

Problem Statement: A bank offers loans only to applicants who meet both of the following criteria:
•Their credit score is greater than or equal to 700.
•They have a stable monthly income above 30000.

public class logicaloperator { public class logicaloperator {


public static void main(String[] args) { public static void main(String[] args) {
int a = 800; int a = 800;
int b = 20000; int b = 40000;
if (a>700 && b>30000) if (a>700 && b>30000)
{ {
System.out.print("Eligible for loan"); System.out.print("Eligible for loan");
} }
else { else {
System.out.print("Not Eligible for loan"); System.out.print("Not Eligible for loan");
} }
} }
} }
Output : Not Eligible for loan Output : Eligible for loan
Program 13 – Logical Operator(Logical &&, ||, !)
Problem Statement: A teacher wants to assign extra homework to students who either missed class or have grades lower
than 50%.
If either condition is true, the student should get additional homework.
import java.util.Scanner; Output:
Enter today Attendance (present/absent)= present
public class logicaloperator1 { Test Marks = 35
public static void main(String[] args) { Write the Assignment
Scanner student = new Scanner(System.in);
System.out.print("Enter today Attendance Enter today Attendance (present/absent)= absent
(present/absent)= "); Test Marks = 70
String attendance = student.nextLine(); Write the Assignment
System.out.print("Test Marks = ");
int marks = student.nextInt(); Enter today Attendance (present/absent)= present
Test Marks = 20
if (attendance.equals("absent") || marks < 50) Write the Assignment
{
System.out.print("Write the Assignment"); Enter today Attendance (present/absent)= present
} Test Marks = 70
else { No need to write the assignment
System.out.print("No need to write the assignment");
} } }
Program 14 – else if statement

Problem Statement: Customer Credit Limit Assignment System


Background:
You are developing a system for a bank to assign credit limits to customers based on their transaction
amounts. The system needs to assign different credit limits based on the customer's transaction amount
(referred to as the "transaction/year amount"). The customer’s credit limit will be determined as follows:

1.Transaction amount between 0 and 100,000: No credit limit (0).


2.Transaction amount between 100,001 and 300,000: Credit limit of 50,000.
3.Transaction amount between 300,001 and 500,000: Credit limit of 200,000.
4.Transaction amount between 500,001 and 1,000,000: Credit limit of 500,000.
5.Transaction amount greater than 1,000,000: Credit limit of 1,000,000.

The system should prompt the user to input their transaction/year amount and display the corresponding
credit limit.
Program 14 – else if statement
import java.util.Scanner;
public class ifelse3 {
public static void main(String[] args) {
Scanner credit = new Scanner(System.in);
System.out.print("Enter the customer transaction/year amount: ");
int amount = credit.nextInt();
int creditlimit;

if (amount >= 0 && amount <= 100000) {


creditlimit = 0;
}
else if (amount > 100000 && amount <= 300000) {
creditlimit = 50000;
}
else if (amount > 300000 && amount <= 500000) {
creditlimit = 200000;
}
else if (amount > 500000 && amount <= 1000000) {
creditlimit = 500000;
}
else {
creditlimit = 1000000;
}

System.out.println("The credit limit for the customer is: " +


creditlimit);
credit.close();
} }
Program 14 – nested if statement

import java.util.Scanner;
else if (gpa >= 6.0) {
public class ScholarshipEligibility { if (hasFinancialNeed) {
System.out.println("You are eligible for a
public static void main(String[] args) { partial scholarship based on financial need.");
Scanner scholar = new Scanner(System.in); } else {
System.out.println("You are not eligible for a
System.out.print("Enter your GPA: ");
double gpa = scholar.nextDouble();
scholarship.");
}
System.out.print("Do you have financial need }
(true/false)? "); else {
boolean hasFinancialNeed = scholar.nextBoolean(); System.out.println("Sorry, you are not eligible
for a scholarship.");
if (gpa >= 8.5) { }
if (hasFinancialNeed) {
System.out.println("Congratulations! You are
eligible for a full scholarship.");
scholar.close();
} else { }
System.out.println("Congratulations! You are }
eligible for a merit-based scholarship.");
}
}
Program 15 – Switch
import java.util.Scanner;
public class GradingSystem {
public static void main(String[] args) {
Scanner marks = new Scanner(System.in);
You are building a grading system for a school. The system
System.out.print("Enter the student's score: ");
needs to assign a grade to a student based on their score in an int score = marks.nextInt();
exam. The grading scheme is as follows:
char grade; // Calculate grade using switch-case
switch (score / 10) {
•Score 90 and above → Grade: A case 10: // Score between 90 to 100
•Score between 80 and 89 → Grade: B case 9: // Score between 90 to 99
grade = 'A';
•Score between 70 and 79 → Grade: C break;
•Score between 60 and 69 → Grade: D case 8: // Score between 80 to 89
•Score below 60 → Grade: F grade = 'B';
break;
case 7: // Score between 70 to 79
The goal is to write a Java program that takes the score as input grade = 'C';
break;
and prints the corresponding grade. case 6: // Score between 60 to 69
grade = 'D';
break;
default: // Score below 60
grade = 'F';
break;
}
System.out.println("The grade is: " + grade);

} }
Program 16 -Switch
Calculate the Shipping Cost Based on Package Type and Destination
You are building a simple application for an online e-commerce platform. The platform offers different types of shipping packages for customers,
and the shipping cost is based on the package type (Standard, Express, or Overnight) and the destination region (Local, National, or
International).
Objective:
Create a Java program using a switch statement to calculate the shipping cost based on the package type and destination.
Requirements:
•There are three types of shipping packages:
•Standard: Takes 5-7 days for delivery.
•Express: Takes 2-3 days for delivery.
•Overnight: Delivers within 24 hours.
•The destination regions are:
•Local: Within the same city or region.
•National: Within the same country but different cities.
•International: Shipping to other countries.
Shipping Cost Calculation: Sample Input and Output:
•Standard Shipping: Input :
•Local: Rs.50 •Package Type: Express
•National: Rs.100 •Destination: National
•International: Rs.350 Output: The shipping cost for Express shipping to National
•Express Shipping: destination is Rs.350.
•Local: Rs.150
•National: Rs.350
•International: Rs.500
•Overnight Shipping:
•Local: Rs.250
•National: Rs.750
•International: Rs.1550
int cost = 0;
switch(packageType) { case "overnight":
import java.util.Scanner; switch(destination) {
case "standard":
public class switch3 { switch(destination) {
case "local":
cost = 30;
public static void main(String[] case "local":
break;
cost = 5;
args) { break;
case "national":
cost = 50;
Scanner scanner = new case "national":
break;
cost = 10;
Scanner(System.in); break;
case "international":
cost = 100;
case "international":
break;
cost = 20;
System.out.print("Enter package break;
default:
System.out.println("Invalid
type (Standard, Express, default:
destination.");
System.out.println("Invalid destination.");
Overnight): "); return;
return;
}
String packageType = }
break;
break;
package.nextLine().toLowerCase( case "express":
default:
System.out.println("Invalid package type.");
); switch(destination) { return;
case "local": }
cost = 15;
System.out.print("Enter break;
System.out.println("The shipping cost for "
case "national":
destination (Local, National, cost = 25; + packageType + " shipping to " +
International): "); break; destination + " destination is Rs" + cost +
case "international":
String destination = cost = 40;
".");
package.nextLine().toLowerCase( break; scanner.close();
default: }
) System.out.println("Invalid destination."); }
return;
}
break;
Program 16 – for loop

public class ForLoop {


public static void main(String[] args)
{
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration number: " + i);
}
}
}

Output
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
Program 17 – for loop
Write a Java program that calculates the sum of all integers from 1 to a given number n using a for loop.
The program should take n as input from the user and then print the sum of all numbers from 1 to n.
import java.util.Scanner;
public class SumOfNumbers {
sum += i; can be read as:
public static void main(String[] args) {
Add the value of i to the current value
Scanner scanner = new Scanner(System.in); of sum and store the new total in sum.
System.out.print("Enter a number: ");

int n = scanner.nextInt();
int sum = 0;

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


sum += i;
}
System.out.println("The sum of numbers from 1 to " + n + " is: " + sum);
Output
scanner.close(); Enter a number: 10
} The sum of numbers from 1 to 10 is: 55
}
Program 18 – Nested for

public class nestedfor { public class nestedfor {


public static void main(String[] args) { public static void main(String[] args) {
int i; int i;
int j; int j;
for (i=1; i<=3; i++) for (i=1; i<=3; i++)
{ {
for(j=1; j<=3; j++) for(j=1; j<=i; j++)
{ {
System.out.print('*'); System.out.print('*');
} }
System.out.println(); System.out.println();
} }
} }
} }
Output: Output:
*** *
*** **
*** ***
Program 18 – For-else loop or enhanced for loop

public class EnhancedForLoopExample


{
public static void main(String[] args)
{
// Defining an array of integers
int[] numbers = {10, 20, 30, 40, 50};

// Using enhanced for loop to iterate over the array


for (int num : numbers)
{
System.out.println(num); Output:
} 10
} 20
} 30
40
50
Program 18 – While loop
import java.util.Random;
import java.util.Scanner; Problem Statement
Generate a random number until the number entered by
public class SumOfNumbers { you
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); Random class is part of the java.util package and provides
System.out.print("Enter a number: "); methods for generating random numbers of various types
int n = scanner.nextInt(); (integers, doubles, booleans, etc.) .

Random rand = new Random();


int num = 0;

while (num!=n){
num = rand.nextInt(101);
System.out.print(num +","); Output:
num++; Enter a number:
} 660,46,3,47,61,70,12,85,2,13,78,3,16,64,57,97,90,14,81,88,75,
75,95,90,89,67,10,47,9,15,20,30,68,45,19,64,36,85,93,81,29,86
scanner.close(); ,4,4,17,83,48,1,23,7,7,45,68,32,29,12,20,4,51,88,78,52,66,53,1
} 00,72,59,89,
}
Program 19 – do while loop

Enter a password.
The program should ensure the password entered is non-empty and should be at least 6
characters long. If the password does not meet these conditions, the program should repeatedly
prompt the user to re-enter the password until a valid one is entered.

Requirements:

•Password length: The password must be at least 6 characters long.


•Non-empty password: The password must not be an empty string.
Program 19 – do while loop

import java.util.Scanner;
public class PasswordEntry {
isEmpty() is used to check if a
public static void main(String[] args) { String is empty. A string is
Scanner scanner = new Scanner(System.in); considered empty if it contains no
String password; characters, i.e., its length is 0.

do {
System.out.print("Enter your password: ");
password = scanner.nextLine(); Output:
Enter your password:
if (password.isEmpty()) {
Password cannot be empty.
System.out.println("Password cannot be empty. Please enter a valid password.");
} Please enter a valid password.
else if (password.length() < 6) { Enter your password:
System.out.println("Password is too short. It must be at least 6 characters long."); nhjPassword is too short. It
} must be at least 6 characters
long.
} while (password.isEmpty() || password.length() < 6); Enter your password:
dfr123Password accepted.
System.out.println("Password accepted.");

scanner.close();
} }
Program 20 – class and object
•lass: public class laptop {
• A class in Java is a blueprint or template for String Name;
creating objects. It defines the properties String Processor;
(attributes/fields) and behaviors (methods) int Ram;
that the objects created from the class will int Price;
have.
• It is a fundamental building block in Java's public static void main(String[] args) {
Object-Oriented Programming (OOP) laptop lap1 = new laptop();
paradigm. lap1.Price = 10000;
• A class can contain fields (variables) and System.out.println(lap1.Price);
methods (functions), and it can also have
constructors, static blocks, inner classes, etc. laptop lap2 = new laptop();
lap2.Price = 8000;
System.out.println(lap2.Price);
Here
Class is a function System.out.println(lap2.Processor);
lap1 & lap2 are object System.out.print(lap1.Ram);
}
}
Program 21 – class, object and function

class movie
{
int ticket = 150;
int parking = 40;
int snacks = 200;
int sum;
void total()
{
sum = ticket + parking + snacks;
System.out.println(sum);
}
public static void main(String[] args)
{
movie expenditure = new movie();
expenditure.total();
}
}
Program 22 – class, object and function
public class Car {
String make;
Create a class called Car that String model;
int year;
represents a car with properties like
public void displayInfo() {
make, model, and year. The class System.out.println("Car Make: " + make);
should have methods to display the System.out.println("Car Model: " + model);
car's information and simulate driving System.out.println("Car Year: " + year);
the car. }
public void drive() {
System.out.println("The " + make + " " + model + " is now driving!");
}
public static void main(String[] args) {
Car myCar = new Car();
Output:
Car Make: Toyota myCar.make = "Toyota";
Car Model: Corolla myCar.model = "Corolla";
Car Year: 2020 myCar.year = 2020;
The Toyota Corolla is now driving!
myCar.displayInfo();
myCar.drive();
} }
Program 23 – Recursion
Fibonacci import java.util.Scanner; Factorial
public class Fibonacci { public class Factorial {
public static void main(String[] args) { public static void main(String[] args) {
int n = 6; Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
// Method to calculate nth Fibonacci number int number = scan.nextInt();
public static int fibonacci(int n) { // Call the factorial method and store the result
// Base Case: F(0) = 0, F(1) = 1 int result = facto(number);
if (n <= 1) { System.out.println("Factorial of " + number + " is " +
return n; result);
} scan.close();
// Recursive Case: F(n) = F(n-1) + F(n-2) }
return fibonacci(n - 1) + fibonacci(n - 2); public static int facto(int number) {
} // Base Case: if n is 0, the factorial is 1
if (number == 0) {
System.out.println("Fibonacci of " + n + " is: " + return 1;
fibonacci(n)); }
} // Recursive Case: n * factorial(n - 1)
} else {
return number * facto(number - 1);
}
}}
Program 24 – Parameter
public class snacks {
Method or function Parameters: These are defined in the void chocolate(int Rs)
function signature and allow data to be passed to the {
function when it is invoked. System.out.println("The cost of chocolate is " + Rs);
}
void juice (int Rs, int Rs1)
{
System.out.println("The cost of juice is "+ Rs + " & " + Rs1);
}
void icecream (String R, int Rs)
{
Output System.out.println("The cost of icecream " + R + " is " + Rs);
The cost of chocolate is 20 }
The cost of juice is 50 & 60 public static void main (String args [])
The cost of icecream vennila is 40 {
The cost of icecream strawberry is 40 snacks cost = new snacks();
cost.chocolate(20);
cost.juice(50,60);
cost.icecream("vennila ", 40);
cost.icecream("strawberry ", 40);

} }
Program 25 – parameter with integer return
public class snacks {
int chocolate (int Rs, int Rs1) {
*In void function the value cannot be return
int c = Rs + Rs1;
return c;
}
int juice (int Rs, int Rs1) {
int c = Rs + Rs1;
return c;
}
void icecream (String R, int Rs)
{
Output System.out.println("The cost of icecream " + R + " is " + Rs);
The cost of icecream vennila is 40 }
The cost of icecream strawberry is 40 public static void main (String args []) {
The cost of chocolate is 99 snacks cost = new snacks();
The cost of juice is 110 int choco = cost.chocolate(20,79);
int jui = cost.juice(50,60);
cost.icecream("vennila ", 40);
cost.icecream("strawberry ", 40);
System.out.println("The cost of chocolate is " + choco);
System.out.println("The cost of juice is " + jui);
} }
Program 26 – Parameter with string return
public class snacks {
int chocolate (int Rs, int Rs1) {
int c = Rs + Rs1;
return c;
}
int juice (int Rs, int Rs1) {
int c = Rs + Rs1;
return c;
}
String icecream (String a)
{
return a;
Output: }
The cost of chocolate is 99 public static void main (String args []) {
The cost of juice is 110 snacks cost = new snacks();
The name of icecream is vennila int choco = cost.chocolate(20,79);
int jui = cost.juice(50,60);
String Ju = cost.icecream("vennila ");
System.out.println("The cost of chocolate is " + choco);
System.out.println("The cost of juice is " + jui);
System.out.println("The name of icecream is " + Ju);
} }
Program 27 - Parameter with string return

Problem statement: import java.util.Scanner;


 Create a class called “number” with main function public class number {
 Create a function called oddorevent with integer String oddoreven(int x) {
parameter if (x%2 ==0)
 Inside main function get integer input from user {
 Pass that input to oddoreven function and let the return "The number is even
function decide wther the number is even or odd number";
 Print the result in main function }
else {
return "The number is odd
number" ;
}

}
Output: public static void main(String [] args)
Enter the Number 29 {
The number is odd number Scanner scan = new
Enter the Number 30 Scanner(System.in);
The number is even number System.out.print("Enter the Number
");
int a =scan.nextInt();
number type = new number();
Program 28 – function overloading

class number { class number { class number {


String oddoreven(int x) String oddoreven(int x) String oddoreven(int x)
{ { {
if (x%2 ==0) if (x%2 ==0) if (x%2 ==0)
{ { {
return "The number is even number"; return "The number is even number"; return "The number is even number";
} } }
else { else { else {
return "The number is odd number" ; return "The number is odd number" ; return "The number is odd number" ;
} } }
} } }
String oddoreven(int x, int y) String oddoreven(int x, int y) String oddoreven(int y)
{ { {
return "ha ha ha"; return "ha ha ha"; return "ha ha ha";
} } }
public static void main(String [] args) public static void main(String [] args) public static void main(String [] args)
{ { {
number type = new number(); number type = new number(); number type = new number();
String result1 = type.oddoreven(10,20); String result1 = type.oddoreven(10); String result1 = type.oddoreven(10);
System.out.print(result1); System.out.print(result1);
System.out.print(result1); } } Error Program: Function and
Output : ha ha ha Output : The number is even number
} } } parameter are same
Program 28 – constructor overloading

class hi { class hi { class constructor {


hi() hi(int a) hi(int a)
{ { {
System.out.print("hi KEC"); System.out.print("hi KEC"); System.out.print("hi KEC");
} } }
public static void main(String[] args) public static void main(String[] args) public static void main(String[] args)
{ { {
hi raj = new hi(); hi raj = new hi(20); hi raj = new hi();
Output:
} hi KEC } }
Output: Output:
} } }
hi KEC Program Error

*In java constructor and class name should be same


Program 29 – Constructor – this keyword
class Person { class Person {
String name; String name;
int age; int age;
// Constructor without using 'this'
Person(String name, int age) // Constructor using 'this' to distinguish between instance
{ variables and parameters
name = name; // Here, the parameter name is assigned to Person(String name, int age) {
itself, which doesn't affect the instance variable this.name = name; // Using 'this' to refer to the instance
age = age; // Same for the age parameter variable
} this.age = age; // Same for the 'age' field
void display() }
{
System.out.println("Name: " + name); void display() {
System.out.println("Age: " + age); Output: System.out.println("Name: " + name);
} Name: null System.out.println("Age: " + age);
public static void main(String[] args) Age: 0 }
{ public static void main(String[] args) {
Person person = new Person(“Stephen", 40); Person person = new Person(“Stephen", 40);
person.display(); person.display();
}} } Output
Without using this, the parameters name and age simply assign
} Name: Stephen
their values to themselves and not to the instance variables
.
Age: 40
Program 30 –Single Inheritance

Inheritance in Java public class SingleInheritance {


It allows a class to inherit properties and methods from another public static void main(String[] args) {
class. Dog dog = new Dog();
Inheritance provides a way to create a new class (child or dog.sound();
subclass) from an existing class (parent or superclass), allowing }
the child class to reuse code from the parent class. }

Single Inheritance means One class inherits from another class class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


Output void dogsound() {
Animal makes a sound System.out.println("Dog barks");
}
}
Program 31 – Multilevel Inheritance
public class MultilevelInheritance {
Multilevel Inheritance means a class inherits from another public static void main(String[] args) {
class, and that class inherits from another class Dog dog = new Dog();
dog.sound();
dog.walk();
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Mammal extends Animal {


void walk() {
Output System.out.println("Mammal walks");
Animal makes a sound }
Mammal walks }

class Dog extends Mammal {


void dogsound() {
System.out.println("Dog barks"); } }
Program 32– Hierarchical Inheritance

public class HierarchicalInheritance{


Hierarchical Inheritance means a multiple classes inherit public static void main(String[] args) {
from the same parent class. Dog dog = new Dog();
dog.sound();

Cat cat = new Cat();


cat.sound();
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
} }
class Dog extends Animal {
Output:
void dogsound() {
Animal makes a sound
System.out.println("Dog barks");
Animal makes a sound
} }
class Cat extends Animal {
void catsound() {
System.out.println("Cat meows");
}}
Program 33 - Override

public class MethodOverriding {


public static void main(String[] args) {
Dog D = new Dog();
D.sound();
}
}

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {

Output: @Override
Dog barks void sound() {
System.out.println("Dog barks");
}
}
Program 34 – inheritance & override
class vehicle {
String brand;
int year;
void startEngine () {
System.out.println("Engine Starts");
} }
class car extends vehicle {
String fuelType;

@Override
void startEngine() {
System.out.println("Car Engine Starts");
} Output
void drive()
{ Truck engine starts
System.out.println("Car is driving"); Truck is hauling
} }
class truck extends vehicle{ Car Engine Starts
int loadcapacity; Car is driving
@Override
void startEngine() {
System.out.println("Truck engine starts");
}
void haul(){
System.out.println("Truck is hauling");
} }
public class inheritance {
public static void main(String[] args) {
truck V1 = new truck();
V1.startEngine();
V1.haul();
car V2 = new car();
V2.startEngine();
V2.drive();
Program 35 – Super keyword

The super keyword in Java is used to refer to the public class Main {
immediate parent class and can be used to call the public static void main(String[] args) {
Vijay vijay = new Vijay();
parent class's constructor, methods, or fields. It helps
vijay.act();
in accessing or invoking members of the superclass }
from the subclass. }
class Actor {
Actor() {
Parent class’s constructor and methos accessing System.out.println("An actor likes to become a Chief Minister");
}
void act() {
System.out.println("Actor role is acting");
}
Output: }
An actor likes to become a Chief Minister class Vijay extends Actor {
Vijay likes to enter a politics Vijay() {
Actor role is acting super();
Vijay need to act in a movie. System.out.println("Vijay likes to enter a politics");
}
void act() {
super.act();
System.out.println("Vijay need to act in a movie.");
}
}
Program 36 – super keyword

public class main {


public static void main(String[] args)
{
Vijay v = new Vijay();
v.printNames();
}
}
Parent class Field accessing class act {
String name = "actor";
}
class Vijay extends act
{
String name = "vijay";
void printNames()
Output: {
Superclass name: actor System.out.println("Superclass name: " + super.name);
Subclass name: vijay System.out.println("Subclass name: " + this.name);
}
}
Program 37 - Abstract
public class Main {
 Abstract method always present in the abstract public static void main(String[] args) {
class Rajinikanth rajinikanth = new Rajinikanth();
 Abstract method donot specify a body KamalHassan kamalhassan = new KamalHassan();
Vijay vijay = new Vijay();
 If any method is created by parent abstract
rajinikanth.performance();
then it must be override by all the child class kamalhassan.performance();
vijay.performance();
}}
abstract class Actor {
We'll define an abstract class Actor with an abstract void performance();
abstract method performance(). Then, we }
create three classes—Rajinikanth, class Rajinikanth extends Actor {
KamalHassan, and Vijay—that override the void performance()
{
performance() method to provide their talents. System.out.println("Rajinikanth performs with style and power");
}}
class KamalHassan extends Actor {
void performance() {
System.out.println("Kamal Hassan performs with
Output: versatility"); }}
Rajinikanth performs with style and power class Vijay extends Actor {
Kamal Hassan performs with versatility void performance()
Vijay performs with energy and charm { System.out.println("Vijay performs with energy and charm");
}}
Program 38 - Interfaces
Program
Program
Program
Program
Program
Program
Program
Program

You might also like