507-Shashwat Tripathi Java Exp 3
507-Shashwat Tripathi Java Exp 3
OF
Experiment No. 1
Aim: Write a program to perform addition of two numbers using command line.
Theory: In Java, finding the sum of two or more numbers is very easy. First,
declare and initialize two variables to be added. Another variable to store the sum of
numbers. Apply mathematical operator (+) between the declared variable and store
the result. The following program calculates and prints the sum of two numbers.
Program:
sum = n1 + n2;
}
}
Output:
Experiment No. 2
Theory:
1) Local Variable
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class
is loaded in the memory.
Program:
class Variables {
int var = 20; //local
public Variables()
{
this.geek = "This is instance variable"; //Initialize Instance Variable
}
}}
Output:
Experiment No. 3
Program
import java.util.Scanner;
class Calc {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
switch (operator) {
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
Output: