[Go to site: main page, start]

0% found this document useful (0 votes)
4 views11 pages

Java Programs

The document provides a practical guide for Java programming with various examples, including basic operations like printing, odd/even checks, factorial calculations, and area of a circle. It also covers advanced topics such as class constructors, sorting arrays, prime number checks, and file operations. Additionally, it includes applet programming examples for creating graphical user interfaces and handling mouse events.

Uploaded by

sujaltrivedib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Java Programs

The document provides a practical guide for Java programming with various examples, including basic operations like printing, odd/even checks, factorial calculations, and area of a circle. It also covers advanced topics such as class constructors, sorting arrays, prime number checks, and file operations. Additionally, it includes applet programming examples for creating graphical user interfaces and handling mouse events.

Uploaded by

sujaltrivedib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaPrograms - Practical List(Easy Guide)

1. Simple Print, Odd/Even, Factorial

(a)HelloWorld -Screen pe print karo


public class HelloWorld {
public static void main(String[] args) {
[Link]("Wel come");
}
}

(b)Odd and Even Number


public class OddEven {
public static void main(String[] args) {
int n = 7; // koi bhi number
if (n % 2 == 0) {
[Link](n + " is Even");
} else {
[Link](n + " is Odd");
}
}
}

(c)Factorial usingCommand LineArgument


public class Factorial {
public static void main(String[] args) {
int n = [Link](args[0]); // command line se number lo
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
[Link]("Factorial = " + fact);
}
}
// Run: java Factorial 5

2. Areaof Circle & Productof Two Numbers

(a)AreaofCircle(command linese radius)


public class CircleArea {
public static void main(String[] args) {
double radius = [Link](args[0]);
double area = [Link] * radius * radius;
[Link]("Area = " + area);
}
}
// Run: java CircleArea 5

(b)Product ofTwoDouble Numbers


public class Product {
public static void main(String[] args) {
double a = [Link](args[0]);
double b = [Link](args[1]);
double product = a * b;
[Link]("Product = " + product);
}
}
// Run: java Product 3.5 2.0

3. Circle Class with Two Constructors


public class Circle {
double radius, x, y;

// 1st Constructor: sirf radius


Circle(double r) {
[Link] = r;
this.x = 0;
this.y = 0;
}

// 2nd Constructor: center + radius


Circle(double x, double y, double r) {
this.x = x;
this.y = y;
[Link] = r;
}

void display() {
[Link]("Center: (" + x + "," + y + ") Radius: " + radius);
}

public static void main(String[] args) {


Circle c1 = new Circle(5); // origin pe center
Circle c2 = new Circle(3, 4, 7); // custom center
[Link]();
[Link]();
}
}

4a. SortArray (Command Line Argument)


import [Link];
public class SortArray {
public static void main(String[] args) {
int[] arr = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
arr[i] = [Link](args[i]);
}
[Link](arr);
[Link]("Sorted: " + [Link](arr));
}
}
// Run: java SortArray 5 2 8 1 9
4b. Prime Number Check
public class PrimeCheck {
public static void main(String[] args) {
int n = [Link](args[0]);
boolean isPrime = true;
if (n < 2) isPrime = false;
for (int i = 2; i <= [Link](n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
[Link](n + (isPrime ? " is Prime" : " is Not Prime"));
}
}
// Run: java PrimeCheck 7

4c. Pattern Display

public class Pattern {


public static void main(String[] args) {
int rows = 4;
for (int i = 1; i <= rows; i++) {
// Left side: i repeated i times
for (int j = 1; j <= i; j++)
[Link](i + " ");
[Link](" ");
// Right side: 1 to i
for (int j = 1; j <= i; j++)
[Link](j + " ");
[Link]();
}
}
}

5. Power, Series 1+1/2+1/3, Fibonacci

(a)Power usingCommand Line


public class Power {
public static void main(String[] args) {
double base = [Link](args[0]);
int exp = [Link](args[1]);
double result = [Link](base, exp);
[Link]("Result = " + result);
}
}
// Run: java Power 2 10

(b)Series:1+ 1/2+ 1/3+...


public class Series {
public static void main(String[] args) {
int n = 10; // kitni terms tak
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
[Link]("Sum = " + sum);
}
}

(c)FibonacciSeries
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
[Link](" " + c);
a = b; b = c;
}
}
}

6. StringBuffer & Alphabetical Order

(a)StringBuffer -beginningmecharacter insertkaro


public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link](0, ">> "); // beginning me insert
[Link](sb);
}
}

(b)StringkoAlphabeticalOrder melagao(AMPICS-> ACIMPS)


import [Link];
public class AlphaSort {
public static void main(String[] args) {
String input = args[0]; // command line se string lo
char[] chars = [Link]();
[Link](chars);
[Link](new String(chars));
}
}
// Run: java AlphaSort AMPICS -> Output: ACIMPS

7. Uppercase Check in Arguments


public class UpperCheck {
public static void main(String[] args) {
for (String arg : args) {
if (![Link]([Link](0))) {
[Link]("Error: \"" + arg + "\" does not start with
uppercase.");
[Link](1); // terminate
}
}
[Link]("All arguments start with uppercase!");
}
}
// Run: java UpperCheck Hello World -> OK
// Run: java UpperCheck hello -> Error

8a. Package with Three Classes

// File: mypackage/[Link]
package mypackage;
public class Add {
public int sum(int a, int b) { return a + b; }
}

// File: mypackage/[Link]
package mypackage;
public class Sub {
public int subtract(int a, int b) { return a - b; }
}

// File: [Link] (package ke bahar)


import mypackage.*;
public class Main {
public static void main(String[] args) {
Add a = new Add();
[Link]("Sum = " + [Link](10, 5));
}
}

8b. Multiple Threads


public class MultiThread extends Thread {
String name;
MultiThread(String name) { [Link] = name; }

public void run() {


for (int i = 1; i <= 3; i++)
[Link](name + " - Count: " + i);
}

public static void main(String[] args) {


MultiThread t1 = new MultiThread("Thread-1");
MultiThread t2 = new MultiThread("Thread-2");
[Link]();
[Link]();
}
}

9. File Operations

(a)File mewords, lines, characters count karo


import [Link].*;
public class FileCount {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
int lines = 0, words = 0, chars = 0;
String line;
while ((line = [Link]()) != null) {
lines++;
chars += [Link]();
words += [Link]("\\s+").length;
}
[Link]();
[Link]("Lines: " + lines);
[Link]("Words: " + words);
[Link]("Chars: " + chars);
}
}

(b)File ki infoprint karo


import [Link].*;
public class FileInfo {
public static void main(String[] args) {
File f = new File("[Link]");
[Link]("Name: " + [Link]());
[Link]("Size: " + [Link]() + " bytes");
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());
[Link]("Path: " + [Link]());
}
}

(c)Word occurrences count karo


import [Link].*;
import [Link].*;
public class WordCount {
public static void main(String[] args) throws Exception {
String searchWord = args[0];
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
int count = 0;
String line;
while ((line = [Link]()) != null) {
for (String w : [Link]("\\s+")) {
if ([Link](searchWord)) count++;
}
}
[Link]();
[Link]("Occurrences of \"" + searchWord + "\": " + count);
}
}

10. AppletPrograms

(a)AppletLifeCycle
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=300 height=200></applet>*/
public class AppletLife extends Applet {
public void init() { [Link]("init() - applet start hua"); }
public void start() { [Link]("start() - run ho raha hai"); }
public void paint(Graphics g) { [Link]("Hello Applet!", 50, 100); }
public void stop() { [Link]("stop() - ruk gaya"); }
public void destroy() { [Link]("destroy() - khatam"); }
}
(b)Indian FlagDesign
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=300></applet>*/
public class IndianFlag extends Applet {
public void paint(Graphics g) {
// Saffron
[Link](new Color(255, 153, 51));
[Link](50, 50, 300, 67);
// White
[Link]([Link]);
[Link](50, 117, 300, 67);
// Green
[Link](new Color(19, 136, 8));
[Link](50, 184, 300, 67);
// Ashoka Chakra (blue circle)
[Link](new Color(0, 0, 128));
[Link](175, 117, 50, 50);
}
}

(c)Red &Green Button Applet


import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=300></applet>*/
public class ButtonApplet extends Applet implements ActionListener {
Button red, green;
public void init() {
red = new Button("Red");
green = new Button("Green");
add(red); add(green);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == red) setBackground([Link]);
if ([Link]() == green) setBackground([Link]);
repaint();
}
}

11. Circle with MagentaFill


import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=400></applet>*/
public class MagentaCircle extends Applet {
public void paint(Graphics g) {
[Link]([Link]);
int w = getWidth(), h = getHeight();
[Link](w/2 - 50, h/2 - 50, 100, 100);
}
}

12. NAME and PASSWORD Label + Textbox


import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=200></applet>*/
public class LoginApplet extends Applet {
public void init() {
setLayout(new FlowLayout());
add(new Label("NAME:"));
add(new TextField(20));
add(new Label("PASSWORD:"));
add(new TextField(20)); // masked nahi hai (basic)
}
}

13. Draw Lines, Rectangles, Ovals


import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=400></applet>*/
public class DrawShapes extends Applet {
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 50, 200, 50); // Line
[Link]([Link]);
[Link](50, 100, 150, 80); // Rectangle
[Link]([Link]);
[Link](50, 220, 150, 80); // Oval
}
}

14. Nested Layout


import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=300></applet>*/
public class NestedLayout extends Applet {
public void init() {
setLayout(new BorderLayout());
Panel top = new Panel(new FlowLayout());
[Link](new Button("North Button 1"));
[Link](new Button("North Button 2"));
Panel center = new Panel(new GridLayout(2, 2));
[Link](new Button("A"));
[Link](new Button("B"));
[Link](new Button("C"));
[Link](new Button("D"));
add(top, [Link]);
add(center, [Link]);
}
}

15. Scrolling Listwith Choice


import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=300></applet>*/
public class ScrollList extends Applet implements ItemListener {
Label msg;
public void init() {
List list = new List(5, false);
[Link]("Apple"); [Link]("Banana");
[Link]("Cherry"); [Link]("Date");
[Link](this);
msg = new Label("Select a fruit:");
add(list); add(msg);
}
public void itemStateChanged(ItemEvent e) {
[Link]("You selected: " + [Link]());
}
}

16. Mouse Event Handlers


import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=400 height=300></applet>*/
public class MouseEvents extends Applet implements MouseListener {
String msg = "";
public void init() { addMouseListener(this); }
public void mouseClicked(MouseEvent e) { msg = "Clicked at " + [Link]() + "," +
[Link](); repaint(); }
public void mouseEntered(MouseEvent e) { msg = "Mouse Entered"; repaint(); }
public void mouseExited(MouseEvent e) { msg = "Mouse Exited"; repaint(); }
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void paint(Graphics g) { [Link](msg, 50, 150); }
}

17. Calculator using Grid Layout


import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=300 height=350></applet>*/
public class Calculator extends Applet implements ActionListener {
TextField display;
double num1, num2, result;
char op;

public void init() {


setLayout(new BorderLayout());
display = new TextField();
add(display, [Link]);

Panel p = new Panel(new GridLayout(4, 4));


String[] buttons =
{"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
for (String b : buttons) {
Button btn = new Button(b);
[Link](this);
[Link](btn);
}
add(p, [Link]);
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();
if ([Link]("=")) {
num2 = [Link]([Link]());
if (op == '+') result = num1 + num2;
else if (op == '-') result = num1 - num2;
else if (op == '*') result = num1 * num2;
else if (op == '/') result = num1 / num2;
[Link]([Link](result));
} else if ([Link]("+") || [Link]("-") || [Link]("*") ||
[Link]("/")) {
num1 = [Link]([Link]());
op = [Link](0);
[Link]("");
} else {
[Link]([Link]() + cmd);
}
}
}

18. Loan EMI Calculator Applet


import [Link].*;
import [Link].*;
import [Link].*;
/*
* <applet code="[Link]" width=400 height=300>
* <param name="monthly" value="true">
* </applet>
*/
public class LoanCalc extends Applet implements ActionListener {
TextField loanField, rateField, monthsField, resultField;
Button calc;

public void init() {


setLayout(new GridLayout(5, 2, 5, 5));
add(new Label("Loan Amount:")); loanField = new TextField(); add(loanField);
add(new Label("Interest Rate %:")); rateField = new TextField(); add(rateField);
add(new Label("Months:")); monthsField = new TextField();
add(monthsField);
calc = new Button("Calculate EMI"); add(calc); [Link](this);
add(new Label("Monthly EMI:")); resultField = new TextField();
add(resultField);
}

public void actionPerformed(ActionEvent e) {


double P = [Link]([Link]());
double r = [Link]([Link]());
int n = [Link]([Link]());

// Check karo monthly hai ya annual


String monthly = getParameter("monthly");
if (monthly == null || ![Link]("true")) {
r = r / 12; // annual se monthly convert
}
r = r / 100; // percentage to decimal

// EMI Formula
double emi = (P * r * [Link](1+r, n)) / ([Link](1+r, n) - 1);
[Link]([Link]("%.2f", emi));
}
}
✅ Saareprogramscomplete!Koibhiprogramsamajhnahotoh poochh sakteho.

You might also like