1. Sample program to calculate tips
-----------------------------
import java.lang.*;
public class Tip {
public long getTip( int amt ) {
double tip = 0.15;
if (amt < 50) tip = 0.1;
return Math.round(amt*tip);
}
public static void main(String []args) {
Tip myTip = new Tip( );
/* You can access instance variable as follows as well */
System.out.println("Tip = " + myTip.getTip(30 ) );
System.out.println("Tip = " + myTip.getTip(60 ) );
}
---------
Same program, without defining a class
public class Tip1 {
public static void main(String []args) {
System.out.println("Tip = " + getTip(30 ) );
System.out.println("Tip = " + getTip(60 ) );
}
public static long getTip( int amt ) {
double tip = 0.15;
if (amt < 50) tip = 0.1;
return Math.round(amt*tip);
}
}
----------------------------------
2. Method Overload
1. Sample programs:
import java.lang.*;
public class Tip {
public long getTip( int amt ) {
double tip = 0.15;
if (amt < 50) tip = 0.1;
return Math.round(amt*tip);
}
public static void main(String []args) {
Tip myTip = new Tip( );
/* You can access instance variable as follows as well */
System.out.println("Tip = " + myTip.getTip(30 ) );
System.out.println("Tip = " + myTip.getTip(60 ) );
}
-----------------------------------
3. Loops
import java.io.*;
public class LoopTest{
public static void main(String args[]) {
int i;
for (i =0;i <= 10;i++) {
if ((i == 2) || (i == 7)) continue;
System.out.println(i);
//System.out.println("\n");
}
System.out.println("while loop \n");
i = 0;
while( i < 20 ) {
System.out.print("value of i : " + i );
i++;
if (i > 10) break;
System.out.print("\n");
}
}
}
---------------------------------------
4. Strings and Arrays
public class Palindrome {
public static void main (String args[]) {
String palindrome = "palindrome";
char a[] = palindrome.toCharArray();
char b[] = new char[20];
System.out.println("String is " + palindrome);
for (int i = palindrome.length() -1; i >= 0; i--) {
b[palindrome.length() - i] = a[i];
}
String reversed = new String(b);
System.out.println ("Reverse is " + reversed);
}
}
-----------------------------------
5. PolyMorphism
class Shape{
// method findArea is overloaded
double findArea (int z,int y){return(0);}
double findArea (int x){return(0);}
}
class Rectangle extends Shape{
double findArea (int a, int b) {
return (a*b);
}
}
class Circle extends Shape{
double findArea (int r) {
return (r * r * 3.14);
}
}
class Triangle extends Shape{
double findArea (int a, int b) {
return (0.5 * a * b);
}
}
class TestPolymorphism{
public static void main(String args[]){
Shape s =new Rectangle();
System.out.println("Area of a rectangle is " + s.findArea(5, 7 ));
s=new Circle();
System.out.println("Area of a Circle is " + s.findArea(6));
s=new Triangle();
System.out.println("Area of a triangle is " + s.findArea(2,3));
}
}
------------------------