Friday 13 April 2018

A program to Display Invert Triangle using while loop



Example: Input – 5 Output : 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1
class InvertTriangle
{
public static void main(String args[])

{
int num = Integer.parseInt(args[0]);
while(num > 0)

{
for(int j=1;j<=num;j++)

{
System.out.print(” “+num+” “);
}
System.out.print(“\n”);
num–;
}
}
}

 

Thursday 12 April 2018

A program to convert given no. of days into months and days.(Assume that each month is of 30 days)


Example : Input – 69 Output – 69 days = 2 Month and 9 days */

class DayMonthDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int days = num%30;
int month = num/30;
System.out.println(num+” days = “+month+” Month and “+days+” days”);
}
}

A program to Swap the values



class Swap{
public static void main(String args[]){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println(“\n***Before Swapping***”);
System.out.println(“Number 1 : “+num1);
System.out.println(“Number 2 : “+num2);
//Swap logic
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
System.out.println(“\n***After Swapping***”);
System.out.println(“Number 1 : “+num1);
System.out.println(“Number 2 : “+num2);
}
}

A program to find SUM AND PRODUCT of a given Digit



class Sum_Product_ofDigit{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
//taking value as command line argument.
int temp = num,result=0;
//Logic for sum of digit
while(temp>0){
result = result + temp;
temp–;
}
System.out.println(“Sum of Digit for “+num+” is : “+result);
//Logic for product of digit
temp = num;
result = 1;
while(temp > 0){
result = result * temp;
temp–;
}
System.out.println(“Product of Digit for “+num+” is : “+result);
}
}

A program to display a greet message according to Marks obtained by student



class SwitchDemo{
public static void main(String args[]){
int marks = Integer.parseInt(args[0]); //take marks
as command line argument.
switch(marks/10){
case 10:
case 9:
case 8:
System.out.println(“Excellent”);
break;
case 7:
System.out.println(“Very Good”);
break;
case 6:
System.out.println(“Good”);
break;
case 5:
System.out.println(“Work Hard”);
break;
case 4:
System.out.println(“Poor”);
break;
case 3:
case 2:
case 1:
case 0:
System.out.println(“Very Poor”);
break;
default:
System.out.println(“Invalid value Entered”);
}
}
}

A Program that will read a float type value from the keyboard and print the following output



/*Small Integer not less than the number. Given Number. Largest Integer not greater than the number. */
class ValueFormat{
public static void main(String args[]){
double i = 34.32; //given number
System.out.println(“Small Integer not greater than the number :”+Math.ceil(i));
System.out.println(“Given Number : “+i);
System.out.println(“Largest Integer not greater than the number :”+Math.floor(i));
}

To Find Minimum of Two Numbers using conditional operator


/* To find minimum of 2 Numbers using ternary operator */
class Minoftwo{
public static void main(String args[]){
//taking value as command line argument. //Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = (i<j)?i:j;
System.out.println(result+” is a minimum value”);
}
}

Find Maximum of Two Numbers



/* To Find Maximum of 2 Numbers using if else */
class Maxoftwo{
public static void main(String args[]){
 
//taking value as command line argument. //Converting String format to Integer value
 

int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
if(i > j)
System.out.println(i+” is greater than “+j);
else
System.out.println(j+” is greater than “+i);
}
}

pyramid of numbers using for loops



/* Generate Pyramid For a Given Number Example This Java example shows how to generate a pyramid of numbers for given number using for loop example. */
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GeneratePyramidExample {
public static void main (String[] args) throws Exception{
BufferedReader keyboard = new BufferedReader (new
InputStreamReader(System.in));
System.out.println(“Enter Number:”);
int as= Integer.parseInt (keyboard.readLine());
System.out.println(“Enter X:”);
int x= Integer.parseInt (keyboard.readLine());
int y = 0;
for(int i=0; i<= as ;i++){
16
for(int j=1; j <= i ; j++){
System.out.print(y + “\t”);
y = y + x;
}
System.out.println(“”);
}
}
}
/* Output of this example would be Enter Number: 5 Enter X: 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ———————————————- Enter Number: 5 Enter X: 2 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 ———————————————- Enter Number: 5 Enter X: 3 0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 */

Factorial of a number using recursion


/*This program shows how to calculate Factorial of a number using recursion function. */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaFactorialUsingRecursion {
public static void main(String args[]) throws NumberFormatException,
IOException{
System.out.println(“Enter the number: “);
//get input from the user
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
//call the recursive function to generate factorial
int result= fact(a);
System.out.println(“Factorial of the number is: ” + result);
}
static int fact(int b)
{
if(b <= 1)
//if the number is 1 then return 1
return 1;
else
//else call the same function with the value – 1
return b * fact(b-1);
}
}
/* Output of this Java example would be Enter the number: 5 Factorial of the number is: 120 */

Calculate Circle Area using radius


This program shows how to calculate
area of circle using it’s radius.
 
Example:-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalculateCircleAreaExample {
public static void main(String[] args) {
int radius = 0;
System.out.println(“Please enter radius of a circle”);
try
{
//get the radius from console
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
radius = Integer.parseInt(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println(“Invalid radius value” + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println(“IO Error :” + ioe);
System.exit(0);
}
/*
* Area of a circle is
* pi * r * r
* where r is a radius of a circle.
*/
//NOTE : use Math.PI constant to get value of pi
double area = Math.PI * radius * radius;
System.out.println(“Area of a circle is ” + area);
}
}

Output:-
Please enter radius of a circle
19
Area of a circle is 1134.1149479459152

Nested Switch


This example shows how to use nested switch statements in a
java program.
Example:-
public class NestedSwitchExample {
public static void main(String[] args) {
/*
* Like any other Java statements, switch statements
* can also be nested in each other as given in
* below example.
*/
int i = 0;
int j = 1;
switch(i)
{
case 0:
switch(j)
{
case 0:
System.out.println(“i is 0, j is 0”);
break;
case 1:
System.out.println(“i is 0, j is 1”);
break;
default:
System.out.println(“nested default
case!!”);
}
break;
default:
System.out.println(“No matching case found!!”);
}
}
}

Output:-
i is 0, j is 1

Reversed pyramid using for loops & decrements operator


Java Pyramid 5 Example
This Java Pyramid example shows how to generate pyramid or triangle
like given below using for loop.
12345
1234
123
12
1

Example:-
public class JavaPyramid5 {
public static void main(String[] args) {
for(int i=5; i>0 ;i–){
for(int j=0; j < i; j++){
System.out.print(j+1);
}
System.out.println(“”);
}
}
}

Output:-
12345
1234
123
12
1

Pyramid of stars using nested for loops


/*
Java Pyramid 1 Example
This Java Pyramid example shows how to generate pyramid or triangle
like given below using for loop.
*
**
***
****
*****
*/

Example:-
public class JavaPyramid1 {
public static void main(String[] args) {
for(int i=1; i<= 5 ;i++){
for(int j=0; j < i; j++){
System.out.print(“*”);
}
//generate a new line
System.out.println(“”);
}
}
}

Output:-
*
**
***
****
*****

Generate prime numbers between 1 & given number


Prime Numbers Java Example
This Prime Numbers Java example shows how to generate prime numbers
between 1 and given number using for loop.

Example:-
public class GeneratePrimeNumbersExample {
public static void main(String[] args) {
//define limit
int limit = 100;
System.out.println(“Prime numbers between 1 and ” + limit);
//loop through the numbers one by one
for(int i=1; i < 100; i++){
boolean isPrime = true;
//check to see if the number is prime
for(int j=2; j < i ; j++){
if(i % j == 0){
isPrime = false;
break;
}
}
// print the number
if(isPrime)
System.out.print(i + ” “);
}
}
}
Output:-
Prime numbers between 1 and 100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 8

Palindrome Number


/*
This program shows how to check for in the given list of numbers
whether each number is palindrome or not
*/
public class JavaPalindromeNumberExample {
public static void main(String[] args) {
//array of numbers to be checked
int numbers[] = new int[]{121,13,34,11,22,54};
//iterate through the numbers
for(int i=0; i < numbers.length; i++){
int number = numbers[i];
int reversedNumber = 0;
int temp=0;
/*
* If the number is equal to it’s reversed number, then
* the given number is a palindrome number.
*
* For ex,121 is a palindrome number while 12 is not.
*/
//reverse the number
while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}
if(numbers[i] == reversedNumber)
System.out.println(numbers[i] + ” is a palindrome”);
else
System.out.println(numbers[i] + ” not a palindrome “);
}
}
}
/*
Output:-
121 is a palindrome number
13 is not a palindrome number
34 is not a palindrome number
11 is a palindrome number
22 is a palindrome number
54 is not a palindrome number
*/

Fibonacci Series


/* Fibonacci Series Java Example
This Fibonacci Series Java Example shows how to create and print
Fibonacci Series using Java.
*/
public class JavaFibonacciSeriesExample {
public static void main(String[] args) {
//number of elements to generate in a series
int limit = 20;
long[] series = new long[limit];
//create first 2 series elements
series[0] = 0;
series[1] = 1;
//create the Fibonacci series and store it in an array
for(int i=2; i < limit; i++){
series[i] = series[i-1] + series[i-2];
}
//print the Fibonacci series numbers
System.out.println(“Fibonacci Series upto ” + limit);
for(int i=0; i< limit; i++){
System.out.print(series[i] + ” “);
}
}
}
/*
Output:-
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
*/

Compare Two Numbers using else-if


/*
Compare Two Numbers Java Example
This Compare Two Numbers Java Example shows how to compare two numbers
using if else if statements.
*/
public class CompareTwoNumbers {
public static void main(String[] args) {
//declare two numbers to compare
int num1 = 324;
int num2 = 234;
if(num1 > num2){
System.out.println(num1 + ” is greater than ” + num2);
}
else if(num1 < num2){
System.out.println(num1 + ” is less than ” + num2);
}
else{
System.out.println(num1 + ” is equal to ” + num2);
}
}
}
/*
Output:-
324 is greater than 234
*/

Factorial of a number


This program shows how to calculate Factorial of a number.
*/
public class NumberFactorial {
public static void main(String[] args) {
int number = 5;
/*
* Factorial of any number is! n.
* For example, factorial of 4 is 4*3*2*1.
*/
int factorial = number;
for(int i =(number – 1); i > 1; i–)
{
factorial = factorial * i;
}
System.out.println(“Factorial of a number is ” + factorial);
}
}
/*
Output of the Factorial program would be
Factorial of a number is 120
*/

Wednesday 11 April 2018

If , else and nested if/else Statement


  • If statement is a compare a statement and equality two number.
  • Here, we are check a if / else condition.
Example:-
<?php
$number1=10;
$number2=20;
if($number1==$number2)
{
echo “Two number are equal <br>”;
}
else if ($number2>$number1)
{
echo “number2 is greater than number1 <br>”;
}
else
{
echo”Two number are not equal <br>”;
}
?>

OUTPUT:-
number2 is greater than number1

Arithmetic operation


  • In arithmetic operation we are use a four operator
             —>ADD (+)
             —>SUBTRACT (-)
             —>PRODUCT(*)
             —>DIVIDE (/)
  • Here we are see a perform all operation.

Example:-
<?php
$number1=1009;
$number2=2003;
echo”ADD<br>”;
echo $number1+$number2 .'<br>’;
echo”SUBTRACT<br>”;
echo $number1-$number2.'<br>’;
echo”PRODUCT<br>”;
echo $number1*$number2.'<br>’;
echo”DIVIDE<br>”;
echo $number1/$number2.'<br>’;
?>

OUTPUT:-
ADD
3012
SUBTRACT
-994
PRODUCT
2021027
DIVIDE
0.50374438342486

Concatenation operator and Escape sequences


Here, we are use a Google link through a “HTML”

Example:-
<?php
$value=25;
$name=”Castor Classes”;
echo “Hello=$name <br>”;    //<br> is use for a next line.
echo ‘Hello=’ . $name . ‘<br>’;
$google=’Google Link’;
echo ‘<a href="http://www.google.com">’.$google.'</a> <br>’;  //This is a HTML code.
echo ‘It’s a nice day’;
?>

OUTPUT:-
Hello=Castor Classes
Hello=Castor Classes
Google Link
It’s a nice day

Variable Declare


  • PHP variable must begin with a “$” sign.
  • Case-sensitive ($Boo!=$b00 !=$BOo)
  • Global and locally-scoped variable
            Global variable can be used anywhere
            Local variable restricted to a function or class
  • certain variable names reserved by PHP
            Form variable ($_POST,$_GET)
            Server variable ($_SERVER)
            Etc.



Example:-
<?php
$value=25;
$name=”Castor Classes”;
$value=($value*8);
echo “$name”;
echo $name,$value;
?>

OutPut:-
Castor ClassesCastor Classes200

Here, $value is use for integer variable and $name is string variable.

List of even numbers


List Even Numbers Java
This List Even Numbers Java Example shows how to find and list even
numbers between 1 and any given number.
 
*/
public class ListEvenNumbers {
public static void main(String[] args) {
//define limit
int limit = 50;
System.out.println(“Printing Even numbers between 1 and ” +
limit);
for(int i=1; i <= limit; i++){
// if the number is divisible by 2 then it is even
if( i % 2 == 0){
System.out.print(i + ” “);
}
}
}
}
/*
Output of List Even Numbers Java Example would be
Printing Even numbers between 1 and 50
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

Recursion


–>Recursion is a process in which a method calls itself continuously. 
A method in java that calls itself is called recursive method.

–>Syntax:-
returntype methodname()
{
//code to be executed
methodname();          //calling same method
}

Example:-
Public Class MyClass
{
// N!=N*(N-1)*(N-2)*………*1.
// 5=5*4*3*2*1
public static int factorial (int N)
{
if(N<=1)
return 1;
else (N*factorial(N-1));     //Call itself method
}
public static void main(string[] args)
System.out println(factorial(5));
}
}

Difference between ArrayList and LinkedList


ArrayList LinkedList
1) ArrayList internally uses dynamic array to store the elements. LinkedList internally uses doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
3) ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
Example:-
 Public Class MyClass{
public static void main(String args[])
{
List<String> MyList=new ArrayList<String>();   //creating arraylist    
MyList.add(“Ravi”);        //Adding object in arraylist    
MyList.add(“Vijay”);
MyList.add(“Ravi”);
MyList.add(“Ajay”);
List<String> MyList2=new LinkedList<String>();       //creating linkedlist    
MyList2.add(“James”);     //adding object in linkedlist   
MyList2.add(“Serena”);
MyList2.add(“Swati”);
MyList2.add(“Junaid”);
System.out.println(“arraylist: “+MyList);
System.out.println(“linkedlist: “+MyList2);                                                                                            }

}

LinkList (Java)

Java Linked List class uses doubly linked list to store the elements.

The important points about Java Linked List are:
  • Java Linked List class can contain duplicate elements.
  • Java Linked List class maintains insertion order.
  • Java Linked List class is non synchronized.
  • In Java Linked List class, manipulation is fast because no shifting needs to be occurred.
  • Java Linked List class can be used as list, stack or queue.                                                            Syntax:-                                                                                                                                                      Link List<string>name=new Linked List<string>();                                                                                  {
………………………..    (Description)                                                                                                                                        }                                                                                                                                                                                Example:-
Public Class MyClass
{
pulic static void main(string[] args)
{
LinkList<string>name=new LinkedList<string>();
name.add(“ABC”);      //Add a name in LinkList
name.add(“PQR”);     //Add a name in LinkList
name.add(“XYZ”);     //Add a name in LinkList
for(string:name)
System.out.println(x);
name.addfirst(“Jack”);     //Add First name in LinkList.
name.addlast(“Zack”);     //Add Last name in LinkList.
name.removelast();            //Remove  First name in LinkList.
name.removefirst();         // Remove Last name in LinkList.
name.clear();                    //Delete all the data in LinkList.
System.out.println(name.size());
name.add(index,”element”);      //This is a syntax for add a variable of particular position in LinkList.
name.add(2,”Index”);
name.remove(2);     // Remove a variable of particular position in LinkList
name.set(1,”a”);  //Change a name as particular index.
}
}

ArrayList


Array List:-ArrayList class uses a dynamic array for storing the elements.

Example:-Public Class MyClass
{
public static void main(string[] args)
{
int single_array=new int[5];   OR {1,2,3,4,5}
ArrayList<Integer>MyList=newArrayList<Integer>(5);
MyList.add(1);
MyList.add(5);
for(Integer x:MyList)
MyList.remove(2);   //To remove index size
MyList.clear();   //to clear index size
System.out.println(x);
System.out.println(MyList.Size());
}
}

Interface


  • An interface in java is a blueprint of a class. It has static constants and abstract methods.
  • The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.
  • Java Interface also represents IS-A relationship.
  • It cannot be instantiated just like abstract class.
  • There are mainly three reasons to use interface. They are given below.
  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.
Class to Class derive–extends
Interface to Class derive–implement
Interface to Interface derive–extends

Abstract Class


  • A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
  • A method that is declared as abstract and does not have implementation is known as abstract method.
Syntax:-
abstract class A
{
}
Example:-
abstract class Bike    //Abstract Class
{
abstract void run();   //Abstract Method
}
class Honda4 extends Bike
{
void run()
{
System.out.println(“running safely..”);
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

Method Overriding


  • If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
Usage:-
  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism
    Rules for Java Method Overriding:-
  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).
    Example:
class Vehicle
{
void run()
{
System.out.println(“Vehicle is running”);
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println(“Bike is running safely”);   //Method Overriding
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}

Polymorphism


Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms.
 
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

Runtime Polymorphism in Java:-

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

Example:-
Public Class BANK
{
int getInsterestRate()
{
return 0;
}
}

Public Class BANK_ABC extends BANK
{
int getInsterestRate()
{
return 0;
}
}

Public Class MyClass
{
public static void main(string[] args)
{
BANK abc=new BANK_ABC();
System.out.println(abc.getInsterestRate());
}
}

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (180) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (753) Python Coding Challenge (228) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses