Calculate Simple Interest

/*Calculate Simple Interest In Java */
//programming789.blogspot.com
import java.util.Scanner;
public class SimpleInterest {
    public static void main(String args[]) {
        float p, r, si;
        int t;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter principal amount:");
        p = sc.nextFloat();
        System.out.print("Enter rate:");
        r = sc.nextFloat();
        System.out.print("Enter time (in years):");
        t = sc.nextInt();
        si = (p * r * t) / 100;
        System.out.println("Simple Interest is:" + si);

    }
}

● Open notepad and add the code. 
● Save the file as SimpleInterest.java
● When the program is run, the following output is displayed:


>java SimpleInterest

Enter principal amount:123

Enter rate:12
Enter time (in years):1
Simple Interest is:14.76

Swap Two Numbers Using Third Variable.


/*Swap Two Numbers Using Third Variable.*/
import java.util.Scanner;
class SwapTwoNumber
{
   public static void main(String args[])
   {
      int x, y, temp;
      System.out.println("Enter value x and y");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();
      y = in.nextInt();
      System.out.println("Before Swapping\nx := "+x+"\ny := "+y);
      temp = x;
      x = y;
      y=temp;
      System.out.println("After Swapping\nx := "+x+"\ny := "+y);
   }
}

● Save the file as  SwapTwoNumber.java.
When the program is run, the following output is displayed:


Output:

Enter x and y 12

14
Before Swapping
x := 12
y := 14
After Swapping
x := 14
y := 12



Calculate Circle Area.


/*Calculate Circle Area In Java example*/
//programming789.blogspot.com/
import java.util.Scanner;
public class CalculateCircleArea
{
        public static void main(String[] args)
       {
                float radius = 0;
Scanner sc = new Scanner(System.in);
                System.out.println("Please enter radius of a circle:");
                radius = sc.nextFloat();
                double area = Math.PI * radius * radius;
                System.out.println("Area of a circle is :" + area);
       }
}


Math.PI returns the pi value of 3.141592653589793.

● Save the file as SimpleInterest.java 

● When the program is run, the following output is displayed:


Output

Please enter radius of a circle:

12
Area of a circle is :452.3893421169302

Calculate Area Of Triangle


/*Calculate area of Triangle in Java*/
//programming789.blogspot.com/
import java.util.Scanner;
class AreaTriangle {

   public static void main(String args[]) {

      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the width of the Triangle:");
      double base = scanner.nextDouble();

      System.out.println("Enter the height of the Triangle:");
      double height = scanner.nextDouble();

      double area = (base* height)/2;

      System.out.println("Area of Triangle is: " + area);    
   }
}

● Save the file as AreaTriangle.java.
● When the program is run, the following output is displayed:

Output:


Enter the width of the Triangle:
12
Enter the height of the Triangle:
14
Area of Triangle is: 84.0

Convert Fahrenheit to Celsius.


/*convert Fahrenheit to Celsius*/
import java.util.*;
class FahrenheitToCelsius 
{
  public static void main(String[] args) 
  {
    float temperatue;
    Scanner in = new Scanner(System.in);      
    System.out.println("Enter temperatue in Fahrenheit:");
    temperatue = in.nextFloat();
    temperatue = ((temperatue - 32)*5)/9;
    System.out.println("Temperatue in Celsius = " + temperatue);
  }
}


● Save the file as FahrenheitToCelsius.java. 
● When the program is run, the following output is displayed:


>java FahrenheitToCelsius

Enter temperatue in Fahrenheit:

12.5
Temperatue in Celsius = -10.833333

Arrays

Java Array:

● Array is a collection of similar type of elements that have contiguous memory location.
● Java array is an object the contains elements of similar data type.
● It is a data structure where we store similar elements.
● We can store only fixed set of elements in a java array.
● Array in java is index based, first element of the array is stored at 0 index.

Array Declaration:

Syntax:
datatype[] identifer;
or
datatype identifer[];

Types of array in java:

There are two types of array.
● Single Dimensional Array
● Multidimensional Array

Initialization of Array:

Example:
int arr[] = new int [10];
or
int arr[] = {10,20,30,40,50};
new operator is used to initialize an array.

Array Example:

/*java Array Example*/
public class TestArray 
{
   public static void main(String[] args)
   {
     int arr[] = {10,20,30,40,50}; 
     System.out.println("Array[0]="+arr[0]); 
     System.out.println("Array[1]="+arr[1]);
System.out.println("Array[2]="+arr[2]);
System.out.println("Array[3]="+arr[3]);    
System.out.println("Array[4]="+arr[4]);   
    }
}

Output:
Array[0]=10
Array[1]=20
Array[2]=30
Array[3]=40
Array[4]=50


Print Array Elements Using For Loop


/*print array elements using for loop in java*/
public class Test {
   public static void main(String args[]){
      int y,numbers[] = {10, 20, 30, 40, 50};
      for(int x=0 ; x<5;x++ ){
          y=numbers[x];
          System.out.println( y );
      }
   }
}

● Save the file as Test.java.

Output:
>java Test
10
20
30
40
50

Get Input From User In Java

Taking Input with Scanner In Java:
  This program tells you how to get input from user in a java program. We are using Scanner class to get input from user.We are using Scanner class to get input from user. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement.

Scanner Input = new Scanner(System.in);

Here Scanner is the class name, Input is the name of object, new keyword is used to allocate the memory and System.in is the input stream.

Following methods of Scanner class are used in the program below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string

/* Input From User Using Scanner Class */
//programming789.blogspot.com/
import java.util.Scanner; 
class GetInput { 
public static void main(String args[]) 
 String s; 
 int i;
 float f;
 Scanner Input = new Scanner(System.in);
 System.out.println("Enter String Value:"); 
 s = Input.nextLine();
 System.out.println("Your Entered Value Is:"+ s);
 System.out.println("Enter Integer Value:");
 i = Input.nextInt();
 System.out.println("Your Entered Value Is:"+i);
 System.out.println("Entered Float Value:");
 f = Input.nextFloat();
 System.out.println("Your Entered Value Is:"+f); 
 } 
}

● Open notepad and add the code.
● Save the file as GetInput.java.
Open a command prompt window and go to the directory where you saved the java file.and run following command.
    >javac GetInput.java
● Then Run program, When the program is run, the following output is displayed:

● Do not declare variable as same as data types. like float float;
● Do not enter wrong value at the time of entering input. If you enter floating value at integer it will show error.



A First Simple Program In Java

Start compiling and running the sample program.

Print "hello world" program in java.

/*  
simply displays "Hello World" output. */
//programming789.blogspot.com/
class Test 
{
     public static void main(String args[])
      {
       System.out.println("hello world");
      }
}

● Open notepad and add the code.
● Save the file as Test.java.
● Open a command prompt window and go to the directory where you saved the java file. Assume it's C:\Test.
● Type ' javac Test.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line.

● The javac compiler creates a file called Test.class that contains the bytecode.
● To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Test as a command-line argument, as shown here.
>C:\Test>java Test


● When the program is run, the following output is displayed:
hello world

Explaination:

Comment:

● The Java language supports three kinds of comments.

/* text */
The compiler ignores everything from /* to */.

/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation

// text
The compiler ignores everything from // to the end of the line.

Class:

 A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
● A class in java can contain:
    ● data member
    ● method
    ● constructor
    ● block
    ● class and interface

Syntax of class:

class <class name>
{
//code
}

Class rules for Naming

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive.

Public Static Void Main(String args[]) :

● The keyword “static” allows main( ) to be called without having to instantiate a particular instance of the class. Void keyword tell the compiler that main() function does not return a value.


Java Keywords And Data Types


Java Keywords:

● There are 49 reserved keywords currently defined in the Java language.
● These keywords, combined with the syntax of the operators and separators, form the definition of the Java language. 
● These keywords cannot be used as names for a variable,class, or method.

Java Keywords
abstract continue goto package synchronized
assert default if private this
Boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float super while while
const for switch switch

Data Types:

 ● Java is safe and robustness because of data Types.
 ● in C/C++ you can assign a floating-point value to an integer. In Java we cannot assign a floating-point value to an integer.
 ● Java defines eight types of data: byte, short, int, long, char, float, double, and Boolean. These can be put in four groups as follows.

Integers:- 
 ● This group includes byte, short, int, and long, which are for whole valued signed numbers.

byte:  The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword.
For example:
byte a = 50, b = -50;
a and b default value is 0.

short: short is a signed 16-bit type. It has a range from –32,768 to 32,767.This . A short is 2 times smaller than an int.
Short variables are declared by use of the short keyword.
For example, declares two short variables called a and b:
short a = 105000 ,b = -150000;
a and b default value is 0

Int: The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. Int are commonly used to control loops and to index arrays.
Int variables are declared by use of the int keyword.
For example, declares two int variables called a and b:
int a = 10500 ,b = -150000;
a and b default value is 0

long: long is a signed 64-bit It has a range from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. This type it useful when big numbers are needed.
Long variables are declared by use of the long keyword.
For example, declares two long variables called a and b:
long a = 100000L ,b= 100000L;
a and b default value is 0

Floating-point numbers :-
 ● This group includes float and double, which represent numbers with fractional precision. Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision.
float: The type float specifies a single-precision value that uses 32 bits of storage. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision.
For example, declares two float variables called a and b:
float b = 245.5f, c = 14.5f;
a and b default value is 0.0f.

double: Double precision, as denoted by the double keyword, uses 64 bits to store a value.
All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
For example, declares two double variables called a and b:
double a = 1234.5 , b =  234.5;
a and b default value is 0.0d.

Characters:-
 ● This group includes char, which represents symbols in a character set, like letters and numbers.

char: char data type is a single 16-bit Unicode character. The range of a char is 0 to 65,536. The standard set of characters known as ASCII still ranges from 0 to 127. char minimum value is '\u0000' or 0 and maximum value is '\uffff' or 65,535.
Example: char a = ‘A’;
Booleans:- 
 ● This group includes boolean, which is a special type for representing true/false values.

boolean: is logical values. It represent one bit of information.
Example: boolean a = true;
Default value of a is false.

Environment Setup

   Java SE is freely available download from the here. So you download a version based on your operating system.download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:

Setting up the path for windows:

        ·  Assuming you have installed Java in c:\Program Files\java\jdk directory:
·  Right-click on 'My Computer' and select 'Properties'.
·  Click on the 'Environment variables' button under the 'Advanced' or ‘Advance system setting’ tab.
·  Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the is currently set to 'C:\WINDOWS\SYSTEM32',then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.


java Editors:

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:
  · Notepad or Notepad++:  On Windows machine you can use any simple text editor like Notepad (Recommended).
  · Netbeans: is a Java IDE that is open-source and free which can be downloaded from here.
  · Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from here

Introduction To Java

history of Java:

  Java is a programming language created by James Gosling from Sun Microsystems (Sun) initiated the Java language project in June 1991. The target of Java is to write a program once and then run this program on multiple operating systems. The first publicly available version of Java (Java 1.0) was released in 1995.The current version of Java is Java 1.8 which is also known as java 8.

Features of java:

  Simple: Java was designed to be easy for the professional programmer to learn and use effectively. If you already understand the basic concepts of object-oriented programming,

  ■ Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

  ■ Portable: You can compile a code on one machine and run it on other machines this feature make java portable.

  ■ Object-oriented: Java is OO because they provide capabilities such as encapsulation, inheritance, polymorphism, abstract data types, classes

  ■ RobustJava makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and run time checking.

  ■ Multithreaded: java supports multithreaded programming, which allows you to write programs that do many things simultaneously.

  ■ Interpreted: Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and interpreted to run the program.

  ■ High performance: With the use of Just-In-Time compilers, Java enables high performance.

  ■ Distributed: Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.

  ■ Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Tools you will need run java program:

You will need the following software:
·        Linux 7.1 or Windows xp/7/8 operating system.
·        Java JDK 8.
·        Microsoft Notepad or any other text editor.