Java Tutorial Day 1

Java Tutorial Day 1

Learning Objective: Let’s start with Java Fundamental and Understand its syntax and usages in real life applications.

funda1.java

public class funda1{

    public static void main(String[] args)
    {
        System.out.println("Hello");
    }
}

funda2.java

/*
*  Variable Rules
*
* Names can contain letters, digits, underscores, and dollar signs
* Names must begin with a letter
* Names should start with a lowercase letter and it cannot contain whitespace
* Names are case sensitive ("Name" and "name" are different variables)
* Do not use Reserved words (like Java keywords, such as int or boolean) cannot be used as names
* 
* Data Types Supported: String, int, float, char, boolean
*/

public class funda2{
    public static void main(String[] args) {
        
        System.out.println("---------------------------------");

        System.out.println("int Variable Example");
        int mark = 10;
        System.out.println("Mark is :" + mark);  

        System.out.println("---------------------------------");

        System.out.println("String Variable Example");
        String fname = "Adarsh";
        String lname = "Patel";
        System.out.println(fname + " " + lname);  

      }
}

funda3.java

/*
*  Operators Supported in java
*
*  +	Addition
*  -	Subtraction
*  *	Multiplication
*  /	Division
*  %	Modulus
*  ++	Increment
*  --	Decrement
*
*/
public class funda3{
    public static void main(String[] args) {
        int no1 = 10;
        int no2 = 20;
        
        System.out.println("---------------------------------");
        System.out.println("      Operator Examples");
        System.out.println("---------------------------------");
        System.out.println("no1 is: " + no1 + ", no2 is: " + no2);
        System.out.println("---------------------------------");
       
        System.out.println("+ :" + (no1+no2));  
        System.out.println("- :" + (no1-no2));  
        System.out.println("* :" + no1*no2);  
        System.out.println("/ :" + no2/no1);  
        System.out.println("% :" + no2%no1);  
        System.out.println("++ (postfix) :" + no1++);
        System.out.println("++ (prefix) :" + ++no1);  
        System.out.println("-- (postfix) :" + no1--);
        System.out.println("-- (prefix) :" + --no1);  

        System.out.println("---------------------------------");
      }
}

funda4.java

public class funda4{
    public static void main(String[] args) {
        int no1 = 0;
                
        System.out.println("---------------------------------");
        System.out.println("      Conditional Structures");
        System.out.println("---------------------------------");
        System.out.println("no1 is: " + no1);
        System.out.println("---------------------------------");
       
        if(no1>0)
        {
            System.out.println("no1 is positive");
        }
        else if(no1<0)
        {
            System.out.println("no1 is Negative");
        }
        else 
        {
            System.out.println("no1 is zero");
        }

        if(no1==0)
        {
            System.out.println("no1 is zero");
        }
        else
        {
            System.out.println("no1 is Non Zero");
        }

        System.out.println("---------------------------------");
      }
}

funda5.java

public class funda5{
    public static void main(String[] args) {
        int no1 = 5;
        int i;
                
        System.out.println("---------------------------------");
        System.out.println("      For and While Loop");
        System.out.println("---------------------------------");
        System.out.println("no1 is: " + no1);
        System.out.println("---------------------------------");

        System.out.println("For Loop Example");

        for(i=1;i<=no1;i++)
        {
            System.out.println(i);
        }

        System.out.println("While Loop Example");

        i=1;
        while(i<=no1)
        {
            System.out.println(i);
            i++;
        }

        System.out.println("---------------------------------");
      }
}

funda6.java

public class funda6{
    String name = "";
    int mark1=0,mark2=0,mark3=0;


    public static void main(String[] args) {

                
        System.out.println("---------------------------------");
        System.out.println("      Class / Object Example");
        System.out.println("---------------------------------");
      
        System.out.println("Student Object Details");

        prog6 std = new prog6();
        std.name = "Adarsh";
        std.mark1 = 50;
        std.mark2 = 60;
        std.mark3 = 70;
        System.out.println("Name: " + std.name);
        System.out.println("Mark1: " + std.mark1);
        System.out.println("Mark2: " + std.mark2);
        System.out.println("Mark3: " + std.mark3);
        
        System.out.println("---------------------------------");

        
        prog6 std2 = new prog6();
        std2.name = "Raj";
        std2.mark1 = 70;
        std2.mark2 = 80;
        std2.mark3 = 90;
        System.out.println("Name: " + std2.name);
        System.out.println("Mark1: " + std2.mark1);
        System.out.println("Mark2: " + std2.mark2);
        System.out.println("Mark3: " + std2.mark3);
     
        System.out.println("---------------------------------");
      }
}

Java Tutorial Day 2

Java Tutorial Day 2

Learning Objective: Let’s start with Java Practical List and it’s example with detail explanations.

prog1.java

Write a program in Java to generate first n prime numbers

public class prog1 {
    public static void main(String[] args)   
    {  
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to generate first n prime numbers");
        System.out.println("---------------------------------");
        
        int ct=0,n=0,i=1,j=1;  
        while(n<10)  
        {  
            j=1;  
            ct=0;  
            while(j<=i)  
            {  
                if(i%j==0)  
                ct++;  
                j++;   
            }  
            if(ct==2)  
            {  
                System.out.printf("%d ",i);  
                n++;  
            }  
            i++;  
        }  
    }  
}

prog2.java

Write a program in Java to find maximum of three numbers using conditional operator

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

        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to find maximum of three numbers using conditional operator");
        System.out.println("---------------------------------");

        //initializing numbers to compare  
        int a=40, b=78, c=19;  
       
        if(a>=b && a>=c)  
        {
            System.out.println(a+" is the largest Number");  
        }
        else if (b>=a && b>=c)  
        {
            System.out.println(b+" is the largest Number");  
        }
        else  
        {
            System.out.println(c+" is the largest number");  
        }
    }  
}

prog3.java

Write a program in Java to find second maximum of n numbers without using arrays

import java.util.*;

public class prog9 {
    public static void main(String[] args)
    {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to find second maximum of n numbers without using arrays");
        System.out.println("---------------------------------");

        Scanner y = new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n = y.nextInt();

        System.out.println("Enter number 1");
        int num = y.nextInt();
        int max = num, max2 = num, min = num;
            
        for (int i = 2; i <= n; i++) {
            System.out.println("Enter number " + i);
            num = y.nextInt();
            if (num < min) {
                min = num;
            } else if (num > max) {
                max2 = max; // shift previous max to become the 2nd largest
                max = num;  // store max
            } else if (num > max2) {
                max2 = num;
            }
        }
        System.out.println("The largest number is     " + max);
        System.out.println("The 2nd largest number is " + max2);
        System.out.println("The smallest number is    " + min);
    }
}

prog4.java

Write a program in Java to reverse the digits of a number using while loop

public class prog4 {
    public static void main(String[] args)   
    {  
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to reverse the digits of a number using while loop");
        System.out.println("---------------------------------");

        int number = 987654, reverse = 0;  
        while(number != 0)   
        {  
            int remainder = number % 10;  
            reverse = reverse * 10 + remainder;  
            number = number/10;  
        }  
        System.out.println("The reverse of the given number is: " + reverse);  
    }  
}

prog5.java

Write a program in Java to convert number into words & print it

public class prog5 {
    static void numberToWords(char num[]) {

        int len = num.length;

        if (len == 0) {

            System.out.println("The string is empty.");
            return;
        }

        if (len > 4) {

            System.out.println("\n The given number has more than 4 digits.");
            return;
        }

        String[] onedigit = new String[] {
            "Zero",
            "One",
            "Two",
            "Three",
            "Four",
            "Five",
            "Six",
            "Seven",
            "Eight",
            "Nine"
        };

        String[] twodigits = new String[] {
            "",
            "Ten",
            "Eleven",
            "Twelve",
            "Thirteen",
            "Fourteen",
            "Fifteen",
            "Sixteen",
            "Seventeen",
            "Eighteen",
            "Nineteen"
        };

        String[] multipleoftens = new String[] {
            "",
            "",
            "Twenty",
            "Thirty",
            "Forty",
            "Fifty",
            "Sixty",
            "Seventy",
            "Eighty",
            "Ninety"
        };

        String[] poweroftens = new String[] {
            "Hundred",
            "Thousand"
        };

        System.out.print(String.valueOf(num) + ": ");

        if (len == 1) {

            System.out.println(onedigit[num[0] - '0']);
            return;
        }
        int x = 0;

        while (x < num.length) {

            if (len >= 3) {
                if (num[x] - '0' != 0) {
                    System.out.print(onedigit[num[x] - '0'] + " ");

                    System.out.print(poweroftens[len - 3] + " ");
                }

                --len;
            }

            else {

                if (num[x] - '0' == 1) {

                    int sum = num[x] - '0' + num[x + 1] - '0';
                    System.out.println(twodigits[sum]);
                    return;
                }

                else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) {

                    System.out.println("Twenty");
                    return;
                }

                else {
                    int i = (num[x] - '0');
                    if (i > 0)
                        System.out.print(multipleoftens[i] + " ");
                    else
                        System.out.print("");
                    ++x;
                    if (num[x] - '0' != 0)
                        //prints the ith index element of the array onedigit[]  
                        System.out.println(onedigit[num[x] - '0']);
                }
            }
            //increments the variable i by 1  
            ++x;
        }
    }
   
    public static void main(String args[]) {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to convert number into words & print it");
        System.out.println("---------------------------------");
        numberToWords("5555".toCharArray());
    }
}

prog6.java

Write a program in Java to multiply two matrix

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

        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to multiply two matrix");
        System.out.println("---------------------------------");

        int a[][] = {
            {
                1,
                1,
                1
            },
            {
                2,
                2,
                2
            },
            {
                3,
                3,
                3
            }
        };
        int b[][] = {
            {
                1,
                1,
                1
            },
            {
                2,
                2,
                2
            },
            {
                3,
                3,
                3
            }
        };

        int c[][] = new int[3][3]; //3 rows and 3 columns  

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                c[i][j] = 0;
                for (int k = 0; k < 3; k++) {
                    c[i][j] += a[i][k] * b[k][j];
                }   
                System.out.print(c[i][j] + " ");  
            } 
            System.out.println();    
        }
    }
}

prog7.java

Write a program to show the use of static keyword.

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

        System.out.println("---------------------------------");
        System.out.println("      Write a program to show the use of static keyword");
        System.out.println("---------------------------------");

        Student s1 = new Student(101, "Abc");
        Student s2 = new Student(102, "Xyz");
        s1.display();
        s2.display();
    }
}

class Student {
    int rollno; 
    String name;
    static String college = "Parul";  
    Student(int r, String n) {
        rollno = r;
        name = n;
    }
    void display() {
        System.out.println(rollno + " " + name + " " + college);
    }
}

prog8.java

Write a program in Java to develop overloaded constructor. Also develop the copy constructor to create a new object with the state of the existing object

public class prog8 {
    public static void main(String arg[]) {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to develop overloaded constructor. Also develop the copy constructor to create a new object with the state of the existing object");
        System.out.println("---------------------------------");

        OverloadCopyConst cp1 = new OverloadCopyConst(5, 6);
        OverloadCopyConst cp2 = new OverloadCopyConst(5);
        OverloadCopyConst cp3 = new OverloadCopyConst(cp2, 5);
    }
}

class OverloadCopyConst {
    int n;
    OverloadCopyConst() {
        System.out.println("Default Constructor");
    }

    OverloadCopyConst(int x, int y) {
        System.out.println("Addition is " + (x + y));
    }

    OverloadCopyConst(int a) {
        n = a;
        System.out.println("Number is " + n);

        int i, j, flag;

        for (i = 1; i <= n; i++) {
            flag = 0;
            for (j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    flag++;
                    break;
                }
            }

            if (flag == 0) {
                System.out.println("Prime is " + i);
            }
        }
    }

    OverloadCopyConst(OverloadCopyConst cp, int a) {
        n = cp.n;
        int max;
        max = a > n ? a : n;
        System.out.println("Maximum number is " + max);
    }
}

prog9.java

Write a program in Java to demonstrate the use of ‘final’ keyword in the field declaration. How it is accessed using the objects

public class prog9 {
    final int speedlimit = 90; //final variable  
    void run() {
        speedlimit = 400;
    }
    public static void main(String args[]) {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to demonstrate the use of 'final' keyword in the field declaration. How it is accessed using the objects.");
        System.out.println("---------------------------------");

        prog15 obj = new prog15();
        obj.run();
    }
}

prog10.java

Develop minimum 4 program based on variation in methods i.e. passing by value, passing by reference, returning values
and returning objects from methods.

/**
* Develop minimum 4 program based on variation in methods i.e. passing by value, passing by reference, returning values 
and returning objects from methods
*
*/

//=================================
//  PassByValue
//==================================
public class prog10 {
    String name="java";
    void display(String name)
    {
        name="Java Programming";
    }
    public static void main(String arg[])
    {
        prog16 p=new prog16();
        System.out.println("Before changes : "+p.name);
        p.display("C++");
        System.out.println("After changes : "+p.name);
    }
}


//=================================
//  PassByReference
//==================================
public class prog10 {
    String name="Java";
    void display(PassByReference p)
    {
        name="Java Programming";
    }
    public static void main(String arg[])
    {
        PassByReference p=new PassByReference();
        System.out.println("Before changes : "+p.name);
        p.display(p);
        System.out.println("After changes : "+p.name);
    }
}


//=================================
//  ReturningValue
//==================================

public class prog10 {
    int n1,n2;
    void getValue(int a,int b)
    {
        n1=a;
        n2=b;
    }
    int returnMax()
    {
        return n1>n2?n1:n2;
    }
    public static void main(String arg[])
    {
        ReturningValue R=new ReturningValue();
        R.getValue(12,44);
        System.out.println("Maximum is : "+R.returnMax());
    }
}


//=================================
//  ReturningObject
//==================================


public class prog10 {
    int n1,n2;
    ReturningObject(int a,int b)
    {
        n1=a;
        n2=b;
    }
    ReturningObject minNumber()
    {
        ReturningObject min=new ReturningObject(55,35);
        return min;
    }
    public static void main(String arg[])
    {
        ReturningObject R1=new ReturningObject(66,234);
        ReturningObject R2=R1.minNumber();
        int minR1=R1.n1<R1.n2?R1.n1:R1.n2;
        System.out.println("Minimum of (R1) "+R1.n1+" & "+R1.n2+" is "+minR1);
        int minR2=R2    .n1<R2.n2?R2.n1:R2.n2;
        System.out.println("Minimum of (R2) "+R2.n1+" & "+R2.n2+" is "+minR2);
    }
}

Java Tutorial Day 3

Java Tutorial Day 3

Learning Objective: Let’s start with Java Practical List and it’s example with detail explanations. (Continue…)

prog11.java

Write a program in Java in which a subclass constructor invokes the constructor of the super class and instantiate the values.

public class prog11 {
    public static void main(String arg[])
    {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java in which a subclass constructor invokes the constructor of the super class and instantiate the values.");
        System.out.println("---------------------------------");

        SubClass s=new SubClass(5,4);
        
    }
}
class SuperClass
{
    int x;
    SuperClass(int a)
    {
        x=a;
        System.out.println("Super Class : " +x);
    }
}
class SubClass extends SuperClass
{
    int y;
    SubClass(int l,int m)
    {
        super(l);
        y=m;
        System.out.println("Sub class : "+y);
    }
}

prog12.java

Write an application that illustrates method overriding in the same package and different packages. Also demonstrate accessibility rules in inside and outside packages

package p1;

public class prog12_1 {
    private int n=1;
    public int n_pub=2;
}
package p1;

import p1.prog12_1;

public class prog12 {
    public static void main(String arg[])
    {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java in which a subclass constructor invokes the constructor of the super class and instantiate the values.");
        System.out.println("---------------------------------");
        
        prog18_1 p1=new prog18_1();
        System.out.println("n= "+p1.n); // this line generate error without it, output 
                                        //like following
        System.out.println("n_pub= "+p1.n_pub);
    }
}

prog13.java

Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, Circle. Define one method area()in the abstract class and override this area() in these three subclasses to calculate for specific object i.e. area() of Triangle subclass should calculate area of triangle etc. Same for Rectangle and Circle

abstract class Shape
{
    float dim1,dim2,radius;
    abstract float area();
}
class Triangle extends Shape
{
        Triangle(float d1, float d2)
        {
            dim1=d1;
            dim2=d2;
        }
        float area()
        {
            System.out.println("Area of Triangle is ");
            return (dim1*dim2)/2;
        }
}
class Rectangle extends Shape
{
    Rectangle(float d1, float d2)
    {
        dim1=d1;
        dim2=d2;
    }
    float area()
    {
        System.out.println("Area of Rectangle is ");
        return dim1*dim2;
    }
}
class Circle extends Shape
{
    Circle(float d1)
    {
        radius=d1;
    }
    float area()
    {
        System.out.println("Area of Circle is ");
        return 3.14f*radius*radius;
    }
}

public class prog13 {
    public static void main(String arg[])
    {
        System.out.println("---------------------------------");
        System.out.println("      Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, Circle. Define one method area()in the abstract class and override this area() in these three subclasses to calculate for specific object i.e. area() of Triangle subclass should calculate area of triangle etc. Same for Rectangle and Circle");
        System.out.println("---------------------------------");

        Triangle t=new Triangle(4.3f,5.3f);
        Rectangle r=new Rectangle(2.4f,4.2f);
        Circle c=new Circle(10.5f);
        
        System.out.println(t.area());
        System.out.println(r.area());
        System.out.println(c.area());
        
    }
}

prog14.java

Write a program in Java to develop user defined exception for ‘Divide by Zero’ error.



public class prog14 {

    public static void main(String arg[])
    {
        System.out.println("---------------------------------");
        System.out.println("      Write a program in Java to develop user defined exception for 'Divide by Zero' error");
        System.out.println("---------------------------------");
        int a;
        int b;
        a = 10;
        b = 0;

        try{
            System.out.println("Division : "+a/b);
        }
        catch(Exception e)
        {
            System.out.println("Exception: " + e.toString());
        }
    }
}

prog15.java

Write an small application in Java to develop Banking Application in which user deposits the amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs 300.00 and it throws exception “Not Sufficient Fund” when user withdraws Rs. 500 thereafter

import java.util.*;


public class prog15 {
    float fund;
    void deposit(float amount)
    {
        fund=amount;
    }
    void withdraw(float money) throws Exception
    {
        float newFund=fund-money;
        if(newFund<500)
        {
            throw new Exception("Not Sufficient Fund");
        }
        else
        {
            fund=newFund;
            System.out.println("Balance After Withdraw : "+fund);
        }
    }
        public static void main(String arg[])
        {
            System.out.println("---------------------------------");
            System.out.println("      Write an small application in Java to develop Banking Application in which user deposits the amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs 300.00 and it throws exception \"Not Sufficient Fund\" when user withdraws Rs. 500 thereafter.");
            System.out.println("---------------------------------");
            prog21 b=new prog21();
            b.deposit(1000.00f);
            try
            {
                float money;
                Scanner sc=new Scanner(System.in);
                System.out.println("Enter Your Amount for withdraw : ");
                money=sc.nextInt();
                System.out.println("Withdrawing amount : "+money);
                b.withdraw(money);
                /* here test with static data so don't worry  
                money=300;
                System.out.println("Withdrawing amount : "+money);
                b.withdraw(money); */
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
            
        }
}

prog16.java

Write a program that executes two threads. One thread will print the even numbers and the another thread will print odd numbers from 1 to 50.

class NewThreadOE extends Thread
{
    NewThreadOE(String threadname)
    {
        super(threadname);
    }
    public void run()
    {
        if( getName().equals("Odd")==true)  
        {
            for(int i=1;i<=50;i=i+2)
            {
                System.out.print("\nOdd: " + i);
                try
                {
                    Thread.sleep(1000);
                }
                catch(InterruptedException e)
                {
                    System.out.println("Exception Occurred.");
                }
            }
        }
        else
        {
            for(int i=2;i<=50;i=i+2)
            {
                if(i%10==0)
                System.out.println();
                System.out.print("\nEven: " + i);
                try
                {
                    Thread.sleep(1000);
                }
                catch(InterruptedException e)
                {
                    System.out.println("Exception Occurred.");
                }
            }
        }
    }
}

public class prog16 {
    public static void main(String[] args)
    {
        System.out.println("---------------------------------");
        System.out.println("      Write a program that executes two threads. One thread will print the even numbers and the another thread will print odd numbers from 1 to 50.");
        System.out.println("---------------------------------");
        NewThreadOE t1 = new NewThreadOE("Odd");
        NewThreadOE t2 = new NewThreadOE("Even");
        t1.start();
        t2.start();
    }
}

prog17.java

Draw ten red circles in a vertical column in the center of the applet.

import java.applet.*;
import java.awt.*;

public class prog17  extends Applet{
    public void paint(Graphics g)
	{
		g.setColor(Color.red);
		g.fillOval(250,0,50,50);
		g.fillOval(250,50,50,50);
		g.fillOval(250,100,50,50);
		g.fillOval(250,150,50,50);
		g.fillOval(250,200,50,50);
		g.fillOval(250,250,50,50);
		g.fillOval(250,300,50,50);
		g.fillOval(250,350,50,50);
		g.fillOval(250,400,50,50);
		g.fillOval(250,450,50,50);
		g.drawString("Hello",170,550);
	}
}

/* <applet code="vertical_circle" height=600 width=550> </applet> */
<html>

<head> <title> Draw Circles in Vertical Columns </title></head>

<body>

<applet code="prog17.class" width=400 height=400>
</applet>
</body>
</html>

prog18.java

Built an applet that displays a horizontal rectangle in its enter. et the rectangle fill with color from left to right.

import java.applet.*;
import java.awt.*;
/*
<applet code="prog18.class" width=600 height=400>
</applet>
*/
public class prog18 extends Applet{
    public void paint(Graphics g)
    {
            Dimension d=getSize(); 
            int x = d.width/2;
            int y = d.height/2;
            g.setColor(Color.green);
            g.drawRect(x-25,y-25,100,50);
            for(int i=100;i<200;i++)
            {
                try
                {
                    Thread.sleep(30);
                    g.fillRect(i+(x-125),y-25,5,50);
                }
                catch(Exception e){}
            }
    }
}