Use of comments
• Enhanced Readability:
• Documentation:
• Debugging:
• Collaboration:
• Learning:
• Personal Note:
• Stress Relief:
• Communication:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = sc.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("Area of the circle is: " + area);
sc.close();
}
}
public: method can be accessed from outside the class.
static: method belongs to the class itself, not to a specific instance of the class.
void: main method doesn't return any value.
main: name of the method.
(String[] args): method's parameter list, accepts an array of strings.
Default Constructor : without parameter
Parameterized Constructor : with parameters
Constructor Overloading: same name but different signatures
Chaining Constructors :calling constructor from another constructor
Copy Constructor : Parameters with instance variables
Constructor with Validation: parameterized constructor that initializes these variables with validation
Constructor with Default Values :assigns default values if not provided. Print the values of the variables.
Overloading Constructors with Different Data Types
public class Main {
private int MainId;
private String MainName;
private String grade;
public Main() {
this(0, "Unknown", "None");
}
public Main(int MainId, String MainName, String grade) {
this.MainId = MainId;
this.MainName = MainName;
this.grade = grade;
}
public static void main(String[] args) {
Main Main1 = new Main();
System.out.println("Main1 ID: " + Main1.MainId);
System.out.println("Main1 Name: " + Main1.MainName);
System.out.println("Main1 Grade: " + Main1.grade);
Main Main2 = new Main(101, "Om", "A");
System.out.println("Main2 ID: " + Main2.MainId);
System.out.println("Main2 Name: " + Main2.MainName);
System.out.println("Main2 Grade: " + Main2.grade);
}
}
public class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber, double balance) {
if (accountNumber == null || accountNumber.isEmpty()) {
System.err.println("Error: Account number cannot be null or empty.");
return;
}
if (balance < 0) {
System.err.println("Error: Balance cannot be negative.");
return;
}
this.accountNumber = accountNumber;
this.balance = balance;
}
public static void main(String[] args) {
Account account1 = new Account("12340009", 1000.00);
System.out.println("Account 1 Number: " + account1.accountNumber);
System.out.println("Account 1 Balance: " + account1.balance);
Account account2 = new Account("", 400.00);
Account account3 = new Account("1230000873", -200.00);
}
}
public class Classroom {
private String className;
private String[] students;
public Classroom(String className, String[] students) {
this.className = className;
this.students = students;
}
public void printClassroom() {
System.out.println("Class Name: " + className);
System.out.print("Students: ");
for (String student : students) {
System.out.print(student + " ");
}
System.out.println();
}
public static void main(String[] args) {
String[] studentArray = {"Mihir ", "Rishabh ", "Om"};
Classroom classroom = new Classroom("Science 101", studentArray);
classroom.printClassroom();
}
}
public class Singleton {
private static Singleton singleInstance = null;
private Singleton() {
System.out.println("Singleton instance created.");
}
public static Singleton getInstance() {
if (singleInstance == null) {
singleInstance = new Singleton();
}
return singleInstance;
}
public static void main(String[] args) {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
if (instance1 == instance2) {
System.out.println("Both instances are the same.");
} else {
System.out.println("Instances are different.");
}
}
}
Naming conventions
Pascal Naming : first alphabet of every word should be capital and rest small
for class names, variable names
Camel Naming : same like Pascal
except: first word should be completely in small case
for methods
Snake Naming : Everything should e capital
Every word should be delimmted by underscore
for constants
class Main {
class Processor {
void displayDetails() {
System.out.println("Processor Brand: Intel");
System.out.println("Processor Speed: 3.5 GHz");
}
}
void showProcessorDetails() {
Processor processor = new Processor();
processor.displayDetails();
}
public static void main(String[] args) {
Main computer = new Main();
computer.showProcessorDetails();
}
}
[1:41 PM, 6/13/2025] Pushpam Computers: public class Main {
public static void main(String args[]) {
String format = "|%1$-15s|%2$-10s|%3$-20s|\n";
System.out.format(format, "Particulars", "Price", "Qty");
System.out.format(format, "1", "Computer", "40000");
System.out.format(format, "2", "Printer", "4000");
String ex[] = { "3", "Speaker", "500" };
System.out.format(String.format(format, (Object[]) ex));
}
}
[1:51 PM, 6/13/2025] Pushpam Computers: public class Main {
public static void main(String args[]) {
String a[] = { "Pushpam", "Computers" };
System.out.println(String.format("Welcome for Learning at %s at %s", a[0], a[1]));
}
}
public class Main
{
public static void main(String [] ss)
{
int[] Marks = {10, 20, 30, 40};
int totalmarks = 0;
for (int i : Marks)
{
totalmarks += i;
}
System.out.println("Sum: " + totalmarks);
}
}
[9:03 AM, 6/14/2025] Pushpam Computers: public class Main
{
public static void main(String [] ss)
{
int[] scores = {85, 92, 78, 95, 88};
int max = scores[0];
for (int i : scores)
{
if (i > max)
{
max = i;
}
}
System.out.println("Biggest score is : " + max);
}
}
[9:07 AM, 6/14/2025] Pushpam Computers: public class Main
public class Main
{
public static void main(String [] ss)
{
int[] nums = {1, 45, 63, 72, 8, 10};
int EvenNumbers = 0;
for (int i : nums)
{
if (i % 2 == 0)
{
EvenNumbers++;
}
}
System.out.println("Even numbers: " + EvenNumbers);
}
}
public class Main
{
public static void main(String [] ss)
{
String[] nm = {"Om", "Shekhar", "Ashtikar"};
String fullname = "";
for (String i : nm)
{
fullname += i + " ";
}
System.out.println(fullname.trim());
}
}
public class Main
{
public static void main(String [] ss)
{
int[] data = {3, 7, 2, 9};
int search = 7;
boolean found = false;
for (int i : data)
{
if (i == search)
{
found = true;
break;
}
}
if (found ==true)
{
System.out.println(" found");
}
else
{
System.out.println("Not found");
}
}
}
public class Main
{
public static void main(String [] ss)
{
int[] numbers = {-2, 50, -1, 8, 0};
for (int i : numbers)
{
if (i > 0)
{
System.out.println(i);
}
}
}
}
public class Main
{
public static void main(String [] ss)
{
char[] letters = {'A', 'B', 'C', 'D'};
for (char ch : letters)
{
System.out.println("Letter: " + ch);
}
}
}
public class Main {
public static void main(String[] args) {
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6}
};
int sum = 0,total=0;
for (int i =0;i<2;i++)
{
for(int j=0;j<3;j++)
{
total += matrix[i][j];
}
}
System.out.println(" "+total);
for (int[] row : matrix) {
for (int element : row) {
sum += element;
}
}
System.out.println("Sum " + sum);
}
}
public class Main {
public static void main(String[] args) {
int[][] matrix =
{
{3, 8, 1},
{2, 7, 9}
};
int max = matrix[0][0];
int min = matrix[0][0];
int i,j;
for (i=0;i<2;i++)
{
for (j=0;j<3;j++)
{
if(max <matrix[i][j])
{
max = matrix[i][j];
}
}
}
System.out.println("Motha: " + max);
for (int[] row : matrix)
{
for (int element : row)
{
if (element <min)
{
min = element;
}
}
}
System.out.println("choota: " + min);
}
}
public class Main {
public static void main(String[] args) {
int[][] shelfdata = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(" Shelf Data:");
for (int[] row : shelfdata) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
int rows = shelfdata.length;
int cols = shelfdata[0].length;
int[][] HorizontalShelfData = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
HorizontalShelfData[j][i] = shelfdata[i][j];
}
}
System.out.println("Horizontal Shelf Data:");
for (int[] row : HorizontalShelfData) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
class Animal {
void makeSound()
{
System.out.println("Some generic sound");
}
}
public class Main
{
public static void main(String[] args)
{
Animal dog = new Animal() {
void makeSound() {
System.out.println("Bho Bho");
}
};
dog.makeSound();
Animal manimau = new Animal(){
void makeSound()
{
System.out.println("Mau mau");
}
};
manimau.makeSound();
}
}
interface Greeting {
void say();
}
public class Main {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
public void say() {
System.out.println("Good Morning, World!");
}
};
greeting.say();
Greeting wish = new Greeting() {
public void say() {
System.out.println("Happy birthday!");
}
};
wish.say();
Greeting sorry = new Greeting() {
public void say() {
System.out.println("I am sorry");
}
};
sorry.say();
}
}
// note use of enum
// enum : giving names to numbers
public class Main {
public enum WeekDays {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
public static void main(String[] args) {
WeekDays today = WeekDays.MONDAY;
System.out.println("Today is " + today);
WeekDays examday = WeekDays.FRIDAY;
System.out.println("Exam on "+examday);
}
}
public class Main {
public enum Saptah {
SATURDAY, SUNDAY
}
public enum Mahina {
January, February, March, April, May, June, July
}
public static void main(String[] args) {
Saptah d1 = Saptah.SATURDAY;
Saptah d2 = Saptah.SUNDAY;
System.out.println("First day: " + d1);
System.out.println("Second day: " + d2);
System.out.println("Months:");
for (Mahina m : Mahina.values()) {
System.out.println(m);
}
}
}
public class Main {
public enum Shape {
SQUARE,
CIRCLE,
RECTANGLE,
TRIANGLE,
HEXAGON
}
public static void main(String[] args) {
Shape[] shapes = Shape.values();
for (Shape shape : shapes) {
System.out.println("\nShape: " + shape);
switch (shape) {
case SQUARE:
double side = 5;
double squareArea = side * side;
System.out.println("Side = " + side);
System.out.println("Area of Square = " + squareArea);
break;
case CIRCLE:
double radius = 3;
double circleArea = Math.PI * radius * radius;
System.out.println("Radius = " + radius);
System.out.println("Area of Circle = " + circleArea);
break;
case RECTANGLE:
double length = 6;
double width = 4;
double rectangleArea = length * width;
System.out.println("Length = " + length + ", Width = " + width);
System.out.println("Area of Rectangle = " + rectangleArea);
break;
case TRIANGLE:
double base = 4;
double height = 5;
double triangleArea = 0.5 * base * height;
System.out.println("Base = " + base + ", Height = " + height);
System.out.println("Area of Triangle = " + triangleArea);
break;
case HEXAGON:
double sideHex = 2;
double hexagonArea = (3 * Math.sqrt(3) * sideHex * sideHex) / 2;
System.out.println("Side = " + sideHex);
System.out.println("Area of Hexagon = " + hexagonArea);
break;
default:
System.out.println("Unknown Shape!");
}
}
}
}
public class Main {
public static void main(String[] args) {
String name = "Pushpam";
System.out.println("Length: " + name.length());
String name1 = "Computer";
System.out.println("Length: " + name1.length());
String name2 = "Pushpam Computer";
System.out.println("Length: " + name2.length());
}
}
public class Main {
public static void main(String[] args) {
String nara = "Jai Hind";
System.out.println("Uppercase: " + nara.toUpperCase());
System.out.println("Lowercase: " + nara.toLowerCase());
}
}
ublic class Main {
public static void main(String[] args) {
String sentence = "this is mail from xyz to abc. attack";
String[] suspiciouswords = {"attack", "bomb"};
boolean spammail = false;
for (String s : suspiciouswords) {
if (sentence.contains(s)) {
spammail = true;
break;
}
}
if (spammail) {
System.out.println("Spam mail");
} else {
System.out.println("Normal");
}
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
String setpassword = "Pushpam";
String userpassword = "";
Scanner sc = new Scanner(System.in);
System.out.println("Password please :");
userpassword = sc.next();
if(userpassword.equals(setpassword))
System.out.println("Welcome");
else
System.out.println("Try again");
}
}
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)
{
String data ="madam";
int i =0,j = data.length()-1;
boolean palindrome = true;
while(i<j)
{
char alpha1 = data.charAt(i);
char alpha2 = data.charAt(j);
if(alpha1 != alpha2)
{
palindrome = false;
break;
}
i=i+1;
j=j-1;
}
if(palindrome ==true)
{
System.out.println(""+data+"is palindrome");
}
else
{
System.out.println(""+data+"is not palindrome");
}
}
}
public class Main {
public static void main(String[] args) {
String text = "I like C++";
String newText = text.replace("C++", "Java");
System.out.println(newText);
}
}
// Interfaces [Pascal]
interface Addition {
int calculateSum(int a, int b);
}
interface Subtraction {
int calculateDifference(int a, int b);
}
public class Main {
public static void main(String[] args) {
Addition adder = (x, y) -> x + y;
Subtraction subtractor = (x, y) -> x - y;
int result = adder.calculateSum(7, 6);
System.out.println("Sum (7 + 6): " + result);
result = adder.calculateSum(15, -35);
System.out.println("Sum (15 + -35): " + result);
result = subtractor.calculateDifference(10, 4);
System.out.println("Difference (10 - 4): " + result);
}
}
interface gm { void sayGm();}
interface ga { void sayGa();}
interface ge{ void sayGe();}
interface gn { void sayGn();}
class Morning implements gm
{
public void sayGm() {
System.out.println("Good Morning!");
}
}
class Afternoon implements ga
{
public void sayGa(){
System.out.println("Good Afternoon");
}
}
class Evening implements ge
{
public void sayGe()
{
System.out.println("Good Evening");
}
}
class Night implements gn
{
public void sayGn()
{
System.out.println("Good Night");
}
}
public class Main {
public static void main(String[] args) {
Morning m = new Morning(); m.sayGm();
Afternoon a = new Afternoon(); a.sayGa();
Evening e = new Evening(); e.sayGe();
Night n = new Night(); n.sayGn();
}
}
import java.io.*;
import java.util.*;
interface Slate
{
int add(int a, int b);
int subtract(int a, int b);
float multiply(float a,float b);
float divide (float a,float b);
}
class Ganak implements Slate {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public float multiply(float a,float b){
return a*b;
}
public float divide(float a,float b){
return a/b;
}
}
public class Main {
public static void main(String[] args) {
Slate calc = new Ganak();
System.out.println("5 + 3 = " + calc.add(5, 3));
System.out.println("5 - 3 = " + calc.subtract(5, 3));
System.out.println(" "+ calc.multiply(24,10));
}
}
interface walk {
void amble();
void footIt();
void march();
void mince();
void mosey();
void nip();
void promenade();
void sashay();
void saunter();
void stroll();
}
interface runnable {
void bounce();
void hike();
void parade();
void powerWalk();
void prance();
void stride();
void strut();
void swagger();
void traipse();
void wander();
}
class Kid implements walk, runnable {
public void amble() {
System.out.println("Kid ambling: walking easily and aimlessly");
}
public void footIt() {
System.out.println("Kid footing it: departing by walking");
}
public void march() {
System.out.println("Kid marching: walking rhythmically");
}
public void mince() {
System.out.println("Kid mincing: walking delicately");
}
public void mosey() {
System.out.println("Kid moseying: ambling or moving along");
}
public void nip() {
System.out.println("Kid nipping: walking briskly or lightly");
}
public void promenade() {
System.out.println("Kid promenading: parading or showing off");
}
public void sashay() {
System.out.println("Kid sashaying: parading ostentatiously");
}
public void saunter() {
System.out.println("Kid sauntering: walking about easily");
}
public void stroll() {
System.out.println("Kid strolling: sauntering leisurely");
}
public void bounce() {
System.out.println("Kid bouncing: walking energetically");
}
public void hike() {
System.out.println("Kid hiking: taking a long walk in nature");
}
public void parade() {
System.out.println("Kid parading: walking ostentatiously");
}
public void powerWalk() {
System.out.println("Kid power walking: walking briskly for fitness");
}
public void prance() {
System.out.println("Kid prancing: walking joyfully like dancing");
}
public void stride() {
System.out.println("Kid striding: walking purposefully with long steps");
}
public void strut() {
System.out.println("Kid strutting: parading confidently");
}
public void swagger() {
System.out.println("Kid swaggering: walking with aggressive confidence");
}
public void traipse() {
System.out.println("Kid traipsing: walking lightly and aimlessly");
}
public void wander() {
System.out.println("Kid wandering: walking or traveling aimlessly");
}
}
public class Main {
public static void main(String[] args) {
Kid kid = new Kid();
kid.amble();
kid.bounce();
kid.footIt();
kid.hike();
kid.march();
kid.mince();
kid.mosey();
kid.nip();
kid.parade();
kid.powerWalk();
kid.prance();
kid.promenade();
kid.sashay();
kid.saunter();
kid.stride();
kid.stroll();
kid.strut();
kid.swagger();
kid.traipse();
kid.wander();
}
}
interface Ganit {
static int square(int x)
{
return x * x;
}
static int cube(int m)
{
return m * m * m;
}
}
public class Main {
public static void main(String[] args)
{
int result = Ganit.square(5);
System.out.println("Square of 5: " + result);
result = Ganit.cube(3);
System.out.println("cube of 3: " + result);
}
}
interface Converter {
double convert(double value);
}
public class Main {
public static void main(String[] args) {
// Fahrenheit to Celsius
Converter fahrenheitToCelsius = fahrenheit -> (fahrenheit - 32) * 5.0 / 9.0;
// Meter to Centimeter
Converter meterToCentimeter = meter -> meter * 100;
// Centimeter to Meter
Converter centimeterToMeter = centimeter -> centimeter / 100;
// Inch to Centimeter
Converter inchToCentimeter = inch -> inch * 2.54;
// Radian to Degree
Converter radianToDegree = radian -> radian * (180 / Math.PI);
// Degree to Radian
Converter degreeToRadian = degree -> degree * (Math.PI / 180);
// Celsius to Kelvin
Converter celsiusToKelvin = celsius -> celsius + 273.15;
// Kelvin to Celsius
Converter kelvinToCelsius = kelvin -> kelvin - 273.15;
// Test conversions
System.out.println("68°F = " + fahrenheitToCelsius.convert(68) + "°C");
System.out.println("2.5 meters = " + meterToCentimeter.convert(2.5) + " cm");
System.out.println("250 cm = " + centimeterToMeter.convert(250) + " meters");
System.out.println("10 inches = " + inchToCentimeter.convert(10) + " cm");
System.out.println("π radians = " + radianToDegree.convert(Math.PI) + " degrees");
System.out.println("180 degrees = " + degreeToRadian.convert(180) + " radians");
System.out.println("100°C = " + celsiusToKelvin.convert(100) + " K");
System.out.println("373.15 K = " + kelvinToCelsius.convert(373.15) + "°C");
}
}
interface TextDecoration {
default String makeItBold(String text) {
return makeItItalic(trimText(text));
}
default String trimText(String text) {
return text.trim();
}
default String makeItItalic(String text) {
return "[" + text + "]";
}
}
class Message implements TextDecoration {}
public class Main {
public static void main(String[] args) {
TextDecoration td = new Message();
System.out.println(td.makeItBold(" Hello World "));
System.out.println(td.makeItItalic("Hi"));
System.out.println(td.trimText(" bye "));
}
}
interface PaymentStrategy {
void bill(double amount);
}
class CreditCardPayment implements PaymentStrategy {
public void bill(double amount) {
System.out.println("Paid Rs." + amount + " via Credit Card");
}
}
class PayPalPayment implements PaymentStrategy {
public void bill(double amount) {
System.out.println("Paid Rs." + amount + " via PayPal");
}
}
class GooglePay implements PaymentStrategy
{
public void bill(double amt)
{
System.out.println(" Rs."+ amt+" by Google pay");
}
}
class ShoppingCart {
private PaymentStrategy paymentMethod;
void setPaymentMethod(PaymentStrategy method) {
paymentMethod = method;
}
void checkout(double amount) {
paymentMethod.bill(amount);
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.setPaymentMethod(new CreditCardPayment());
cart.checkout(100.0);
cart.setPaymentMethod(new PayPalPayment());
cart.checkout(50.0);
cart.setPaymentMethod(new GooglePay());
cart.checkout(23.50);
}
}
interface Printer {
void printDocument(String document);
}
class LegacyPrinter {
void print(String text) {
System.out.println("Legacy Printing: " + text);
}
}
class PrinterAdapter implements Printer {
private LegacyPrinter legacyPrinter;
PrinterAdapter(LegacyPrinter printer) {
legacyPrinter = printer;
}
public void printDocument(String document) {
legacyPrinter.print(document);
}
}
class DotMatrixPrinter implements Printer {
public void printDocument(String document) {
System.out.println("Dot Matrix Printing: " + document);
}
}
class InkjetPrinter implements Printer {
public void printDocument(String document) {
System.out.println("Inkjet Printing: " + document);
}
}
class LaserPrinter implements Printer {
public void printDocument(String document) {
System.out.println("Laser Printing: " + document);
}
}
public class Main {
public static void main(String[] args) {
Printer legacyAdapter = new PrinterAdapter(new LegacyPrinter());
legacyAdapter.printDocument("Adapter Pattern Example");
Printer dotMatrix = new DotMatrixPrinter();
Printer inkjet = new InkjetPrinter();
Printer laser = new LaserPrinter();
dotMatrix.printDocument("Receipt copy");
inkjet.printDocument("Family photo");
laser.printDocument("Business report");
System.out.println("\n--- Printer Characteristics ---");
System.out.println("DOT MATRIX:");
System.out.println("- Type: Impact printer using pins and ribbon");
System.out.println("- Cost: Low (Rs.100-Rs.500)");
System.out.println("- Per-page cost: Lowest");
System.out.println("- Do's: Carbon copies, multi-part forms");
System.out.println("- Don'ts: High-res images, quiet environments");
System.out.println("\nINKJET:");
System.out.println("- Type: Sprayed ink droplets on paper");
System.out.println("- Cost: Medium (Rs.50-Rs.300)");
System.out.println("- Per-page cost: High (especially color)");
System.out.println("- Do's: Photos, color documents");
System.out.println("- Don'ts: High-volume printing, water exposure");
System.out.println("\nLASER:");
System.out.println("- Type: Toner powder fused with heat");
System.out.println("- Cost: Hhttps://www.onlinegdb.com/online_java_compiler#tab-stdinigh (Rs.200-Rs.2000+)");
System.out.println("- Per-page cost: Low (especially mono)");
System.out.println("- Do's: High-volume, text documents");
System.out.println("- Don'ts: Specialty papers, low-use environments");
}
}
import java.util.ArrayList;
import java.util.List;
class Prani
{
private String name;
private String youngName;
static int i =0;
public Prani(String name, String youngName) {
this.name = name;
this.youngName = youngName;
}
public void show() {
if (++i% 2==0)
{
System.out.println(name + " gives birth to : " + youngName);
}
else
System.out.println(name +" parent of : "+youngName);
}
}
public class Main {
public static void main(String[] args) {
List<Prani> Pranis = new ArrayList<>();
Pranis.add(new Prani("Cat", "Kitten"));
Pranis.add(new Prani("Dog", "Puppy"));
Pranis.add(new Prani("Cow", "Calf"));
Pranis.add(new Prani("Horse", "Foal"));
Pranis.add(new Prani("Sheep", "Lamb"));
Pranis.add(new Prani("Pig", "Piglet"));
Pranis.add(new Prani("Goat", "Kid"));
Pranis.add(new Prani("Lion", "Cub"));
Pranis.add(new Prani("Tiger", "Cub"));
Pranis.add(new Prani("Elephant", "Calf"));
Pranis.add(new Prani("Deer", "Fawn"));
Pranis.add(new Prani("Rabbit", "Bunny"));
Pranis.add(new Prani("Kangaroo", "Joey"));
Pranis.add(new Prani("Monkey", "Infant"));
Pranis.add(new Prani("Bear", "Cub"));
Pranis.add(new Prani("Whale", "Calf"));
Pranis.add(new Prani("Wolf", "Pup"));
Pranis.add(new Prani("Fox", "Pup"));
Pranis.add(new Prani("Otter", "Pup"));
Pranis.add(new Prani("Seal", "Pup"));
Pranis.add(new Prani("Walrus", "Cub"));
Pranis.add(new Prani("Mouse", "Pup"));
Pranis.add(new Prani("Rat", "Pup"));
Pranis.add(new Prani("Leopard", "Cub"));
Pranis.add(new Prani("Donkey", "Foal"));
Pranis.add(new Prani("Chicken", "Chick"));
Pranis.add(new Prani("Duck", "Duckling"));
Pranis.add(new Prani("Penguin", "Chick"));
Pranis.add(new Prani("Owl", "Owlet"));
Pranis.add(new Prani("Swan", "Signet"));
Pranis.add(new Prani("Turtle", "Hatchling"));
Pranis.add(new Prani("Frog", "Tadpole"));
Pranis.add(new Prani("Fish", "Fry"));
Pranis.add(new Prani("Turkey", "Poult"));
for (Prani Prani : Pranis) {
Prani.show();
}
}
}
import java.util.ArrayList;
import java.util.List;
class Prani {
private String name;
private String noise;
private String shelter;
static int i = 0;
public Prani(String name, String noise, String shelter) {
this.name = name;
this.noise = noise;
this.shelter = shelter;
}
public void show() {
if (++i % 2 == 0) {
System.out.println(name + " makes sound: " + noise+ " enjoy in "+ shelter);
} else {
System.out.println(name + " cries " + noise+ " lives in "+ shelter);
}
}
}
public class Main {
public static void main(String[] args) {
List<Prani> Pranis = new ArrayList<>();
Pranis.add(new Prani("Cat", "Meow", "House"));
Pranis.add(new Prani("Dog", "Bark", "Kennel"));
Pranis.add(new Prani("Cow", "Moo", "Shed"));
Pranis.add(new Prani("Horse", "Neigh", "Stable"));
Pranis.add(new Prani("Sheep", "Baa", "Pen"));
Pranis.add(new Prani("Pig", "Oink", "Sty"));
Pranis.add(new Prani("Goat", "Bleat", "Pen"));
Pranis.add(new Prani("Lion", "Roar", "Den"));
Pranis.add(new Prani("Tiger", "Growl", "Den"));
Pranis.add(new Prani("Elephant", "Trumpet", "Forest"));
Pranis.add(new Prani("Deer", "Grunt", "Forest"));
Pranis.add(new Prani("Rabbit", "Squeak", "Burrow"));
Pranis.add(new Prani("Kangaroo", "Chortle", "Grassland"));
Pranis.add(new Prani("Monkey", "Chatter", "Tree"));
Pranis.add(new Prani("Bear", "Growl", "Cave"));
Pranis.add(new Prani("Whale", "Sing", "Ocean"));
Pranis.add(new Prani("Wolf", "Howl", "Den"));
Pranis.add(new Prani("Fox", "Bark", "Burrow"));
Pranis.add(new Prani("Otter", "Squeak", "Den"));
Pranis.add(new Prani("Seal", "Bark", "Coast"));
Pranis.add(new Prani("Walrus", "Grunt", "Ice"));
Pranis.add(new Prani("Mouse", "Squeak", "Hole"));
Pranis.add(new Prani("Rat", "Squeak", "Burrow"));
Pranis.add(new Prani("Leopard", "Roar", "Den"));
Pranis.add(new Prani("Donkey", "Bray", "Stable"));
Pranis.add(new Prani("Chicken", "Cluck", "Coop"));
Pranis.add(new Prani("Duck", "Quack", "Pond"));
Pranis.add(new Prani("Penguin", "Honk", "Colony"));
Pranis.add(new Prani("Owl", "Hoot", "Tree Hollow"));
Pranis.add(new Prani("Swan", "Trumpet", "Nest"));
Pranis.add(new Prani("Turtle", "Hiss", "Beach"));
Pranis.add(new Prani("Frog", "Croak", "Pond"));
Pranis.add(new Prani("Fish", "Bubble", "Aquarium"));
Pranis.add(new Prani("Turkey", "Gobble", "Coop"));
for (Prani prani : Pranis) {
prani.show();
}
}
}
class Animal {
public String eat() {
return "food";
}
public String drink() {
return "water";
}
}
class Cat extends Animal {
public String eat() {
return "fish";
}
public String drink() {
return "milk";
}
}
class Elephant extends Animal {
public String eat() {
return "grass, banana, sugarcane";
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
Elephant elephant = new Elephant();
System.out.println("Cat eats " + cat.eat());
System.out.println("Cat drinks " + cat.drink());
System.out.println("Elephant eats " + elephant.eat());
System.out.println("Elephant drinks " + elephant.drink());
}
}
public class Main {
public static void main(String[] args) {
final double PI = 3.14159;
System.out.println("PI value: " + PI);
}
}
class Animal {
final void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// void sound() {} //Cannot override final method
}
public class Main {
public static void main(String[] args) {
new Dog().sound();
}
}
final class ImmutableClass {
void display() {
System.out.println("This class cannot be extended");
}
}
// class SubClass extends ImmutableClass {} Cannot extend final class
public class Main {
public static void main(String[] args) {
new ImmutableClass().display();
}
}
public class Main {
static void processValue(final int value) {
System.out.println("Value received: " + value);
// value = 100; // Cannot change final parameter
}
public static void main(String[] args) {
processValue(50);
}
}
public class Main {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("Java Programming..!");
sb.append(" World"); // Allowed: Modifying object content
System.out.println(sb);
}
}
public class Circle {
public static final double PI = 3.14159;
static void area(final double radius) {
System.out.println("Area: " + PI * radius * radius);
}
public static void main(String[] args) {
area(5.0);
}
}
public class Main {
final String name; // to be initialized in constructor
Main(String name) {
this.name = name;
}
public static void main(String[] args) {
Main p = new Main("Pushpam");
System.out.println("Name: " + p.name);
// p.name = "Pushpam"; // Cannot change final variable
}
}
public class Main {
public static void main(String[] args) {
final int[] numbers = {1, 2, 3, 4, 5};
for(final int num : numbers) {
System.out.println(num);
// num = 10; // Cannot change final loop variable
}
}
}
class Bicycle {
final void maintenance() {
System.out.println("puncture, filling air");
}
}
class Scooter extends Bicycle {
// Cannot override maintenance() here
}
public class Main {
public static void main(String[] args) {
new Scooter().maintenance();
}
}
public class Main {
public static void main(String[] args) {
String original = "Marksheet";
String xerox = original;
System.out.println(original);
System.out.println(xerox);
}
}
public class Main {
public static void main(String[] args) {
StringBuilder wish = new StringBuilder("Happy Birthday");
StringBuilder person = wish;
wish.append(" friend name");
System.out.println(person);
}
}
public class Main {
public static void main(String[] args) {
String s = "Java";
System.out.println(s.length()); // 4
s = null;
// System.out.println(s.length());
}
}
public class Main {
public static void main(String[] args) {
int[] roughMarksheet = {78, 45, 29};
int[] finalMarksheet = roughMarksheet; // References same array
finalMarksheet[0] = 100;
System.out.println(roughMarksheet[0]); // 100 (change through reference)
for(int r : roughMarksheet)
System.out.print(" "+r);
System.out.println();
for (int f : finalMarksheet)
System.out.print(" "+f);
}
}