diff --git a/Chapter6/SDemo2.java b/Chapter6/SDemo2.java new file mode 100644 index 0000000..9f8acbc --- /dev/null +++ b/Chapter6/SDemo2.java @@ -0,0 +1,27 @@ +// Use a static method. +class StaticMeth{ + static int val = 1024; // a static variable + + // a static method + static int valDiv2() { + return val/2; + } + +} + + +public class SDemo2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("val is " + StaticMeth.val); + System.out.println("StaticMeth.valDiv2(): " + StaticMeth.valDiv2()); + + StaticMeth.val = 4; + System.out.println("val is " + StaticMeth.val); + System.out.println("StaticMeth.valDiv2(): " + StaticMeth.valDiv2()); + + } + +} diff --git a/Chapter6/SDemo3.java b/Chapter6/SDemo3.java new file mode 100644 index 0000000..c4b4a35 --- /dev/null +++ b/Chapter6/SDemo3.java @@ -0,0 +1,31 @@ +// Use a static block +class StaticBlock{ + static double rootOf2; + static double rootOf3; + + // This block is executed when the class is loaded. + static { + System.out.println("Inside static block."); + rootOf2 = Math.sqrt(2.0); + rootOf3 = Math.sqrt(3.0); + } + + public StaticBlock(String msg) { + + System.out.println(msg); + + } +} + +public class SDemo3 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + StaticBlock ob = new StaticBlock("Inside Constructor"); + + System.out.println("Square root of 2 is " + StaticBlock.rootOf2); + System.out.println("Square root of 3 is " + StaticBlock.rootOf3); + + } + +} diff --git a/Chapter6/StaticError.java b/Chapter6/StaticError.java new file mode 100644 index 0000000..eea16c3 --- /dev/null +++ b/Chapter6/StaticError.java @@ -0,0 +1,19 @@ + +public class StaticError { + + int denom = 3; // A normal instance variable + static int val = 1024; // A static variable + + /* Error! Can't access a non-static variable from within a static method. */ + static int valDivDenom() { + return val/denom; // won't compile! + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("StaticError.valDivDenom = " + StaticError.valDivDenom()); + + } + +}