1 Calling within Static method /* We can call a non static method from a static method but by only through an object of that class. */ class Test1{ public static void meth1(){ Test1 t1 = new Test1(); t1.meth2(); Test2 t2 = new Test2(); t2.meth3(); } public void meth2(){ System.out.println("this is meth2"); } public static void main(String [] args){ meth1(); } } class Test2{ public void meth3(){ System.out.println("Inside meth3"); }
2 final /* Compute volume for a given mass and generate a table for values of mass = 1.0, 2.0, 3.0, 4.0, 5.0 using a for loop */ class cylinder { public static void main (String args[]) { final double pi = ; double radius, height, volume; radius = 1.0; height = 2.0; volume = pi * radius * radius * height; System.out.println("Volume is: "+volume); radius = 1.0; height = 2.0; // pi = 3.0; volume = pi * radius * radius * height; System.out.println("Volume is: "+volume); }
3 final /* Compute volume for a given mass and generate a table for values of mass = 1.0, 2.0, 3.0, 4.0, 5.0 using a for loop */ class densityTableFor { public static void main (String args[]) { double mass, volume; final double density = 13.6; for(mass = 1.0; mass <=5.0; mass = mass + 1.0){ volume = mass/density; System.out.println("If mass is " + mass + " then the volume is " + volume); } System.out.println(); // density = 13.0; for(mass = 1.0; mass <=2.0; mass = mass + 0.1){ volume = mass/density; System.out.println("If mass is " + mass + " then the volume is " + volume); }
4 StringTokenizer import java.util.StringTokenizer; class tokenizerdemo{ public static void main(String arg[]){ ConsoleReader console = new ConsoleReader(System.in); System.out.println("Pls give string input"); String z = console.readLine(); StringTokenizer st1 = new StringTokenizer(z); while (st1.hasMoreTokens()){ String token = st1.nextToken(); System.out.println(token); } StringTokenizer st2 = new StringTokenizer(z); int tokencount = st2.countTokens(); for (int i=0; i<tokencount; i++){ String token = st2.nextToken(); System.out.println(token); }
5 Roots of an equation /* Solve x*x-3x+1=0 x = 1/3(x*x+1) OR x = 3 - 1/x */ public class equation{ public static void main(String args[]){ double error= ; double x1=0.2; //double x1=1.0; //double x1=2.6; //double x1=3.0; double x2=(x1*x1+1)/3; while(Math.abs(x2-x1)>error){ System.out.println(x2); x1=x2; x2=(x1*x1+1)/3; } System.out.println(x1); System.out.println("FIRST LOOP ENDS");
6 Roots of an equation /* Solve x*x-3x+1=0 x = 1/3(x*x+1) OR x = 3 - 1/x */ x1=0.2; //x1=1.0; //x1=2.6; //x1=3.0; x2=3-1/x1; while(Math.abs(x2-x1)>error){ System.out.println(x2); x1=x2; x2=3-1/x1; } System.out.println(x1); }
FIRST LOOP ENDS
8 With x1= E E E E E E298 Infinity FIRST LOOP ENDS