├── .gitignore ├── Chapter-02 └── src │ ├── BlockTest.java │ ├── Example.java │ ├── Example2.java │ ├── ForTest.java │ └── IfSample.java ├── Chapter-03 └── src │ ├── Area.java │ ├── Array.java │ ├── AutoArray.java │ ├── Average.java │ ├── BoolTest.java │ ├── CharDemo.java │ ├── CharDemo2.java │ ├── Conversion.java │ ├── DynInit.java │ ├── LifeTime.java │ ├── Light.java │ ├── Matrix.java │ ├── Promote.java │ ├── Scope.java │ ├── ScopeErr.java │ ├── ThreeDMatrix.java │ ├── TwoDAgain.java │ ├── TwoDArray.java │ └── VarDemo.java ├── Chapter-04 └── src │ ├── BasicMath.java │ ├── BitLogic.java │ ├── BoolLogic.java │ ├── ByteShift.java │ ├── ByteUShift.java │ ├── HexByte.java │ ├── IncDec.java │ ├── Modulus.java │ ├── MultByTwo.java │ ├── OpBitEquals.java │ ├── OpEquals.java │ └── Ternary.java ├── Chapter-05 └── src │ ├── Break.java │ ├── BreakErr.java │ ├── BreakLoop.java │ ├── BreakLoop2.java │ ├── BreakLoop3.java │ ├── BreakLoop4.java │ ├── Comma.java │ ├── Continue.java │ ├── ContinueLabel.java │ ├── DoWhile.java │ ├── FindPrime.java │ ├── ForEach.java │ ├── ForEach2.java │ ├── ForEach3.java │ ├── ForTick.java │ ├── ForTick2.java │ ├── ForVar.java │ ├── IfElse.java │ ├── Menu.java │ ├── MissingBreak.java │ ├── Nested.java │ ├── NoBody.java │ ├── NoChange.java │ ├── Return.java │ ├── Sample.java │ ├── SampleSwitch.java │ ├── Search.java │ ├── StringSwitch.java │ ├── Switch.java │ ├── TypeInferenceInFor.java │ └── While.java ├── Chapter-06 └── src │ ├── Box.java │ ├── BoxConstructorExamples.java │ ├── BoxDemo.java │ ├── BoxDemo2.java │ ├── BoxDemo3.java │ ├── BoxDemo4.java │ ├── BoxDemo5.java │ ├── BoxDemo6.java │ ├── BoxDemo7.java │ ├── Stack.java │ └── TestStack.java ├── Chapter-07 └── src │ ├── AccessTest.java │ ├── Box.java │ ├── CallByValue.java │ ├── CommandLine.java │ ├── FinalKeyExample.java │ ├── InnerClassDemo.java │ ├── InnerClassDemo2.java │ ├── InnerClassDemo3.java │ ├── Length.java │ ├── OverloadCons.java │ ├── OverloadCons2.java │ ├── OverloadDemo.java │ ├── OverloadDemo2.java │ ├── PassArray.java │ ├── PassOb.java │ ├── PassObjRef.java │ ├── Recursion.java │ ├── Recursion2.java │ ├── RefVarDemo.java │ ├── RetOb.java │ ├── Stack.java │ ├── StaticByName.java │ ├── StringDemo.java │ ├── StringDemo2.java │ ├── StringDemo3.java │ ├── TestStack.java │ ├── TestStack2.java │ ├── UseStatic.java │ ├── VarArgs.java │ ├── VarArgs2.java │ ├── VarArgs3.java │ └── VarArgs4.java ├── Chapter-08 └── src │ ├── AbstractAreas.java │ ├── AbstractDemo.java │ ├── Access.java │ ├── B.java │ ├── BoxWeight.java │ ├── BoxWeightCopyConstructorExample.java │ ├── CallingCons.java │ ├── ColorBox.java │ ├── DemoBoxWeight.java │ ├── DemoShipment.java │ ├── DemoSuper.java │ ├── Dispatch.java │ ├── ExtendingFinalClassExample.java │ ├── FinalMethodOverrideExample.java │ ├── FindAreas.java │ ├── Override.java │ ├── Override2.java │ ├── RefDemo.java │ ├── SimpleInheritance.java │ ├── TypeInferenceAndInheritance.java │ └── UseSuper.java ├── Chapter-09 └── src │ ├── AnotherClient.java │ ├── AskMe.java │ ├── Callback.java │ ├── Client.java │ ├── Client2.java │ ├── DefaultMethodDemo.java │ ├── ExtendingClassWithImport.java │ ├── ExtendingClassWithoutImport.java │ ├── IFExtend.java │ ├── IFTest.java │ ├── IFTest2.java │ ├── IFTest3.java │ ├── Incomplete.java │ ├── IntStack.java │ ├── IntStack2.java │ ├── IntStack3.java │ ├── MyIF.java │ ├── MyIF2.java │ ├── MyIFImp.java │ ├── MyIFImp2.java │ ├── NestedIFDemo.java │ ├── TestBalance.java │ ├── TestIface.java │ ├── TestIface2.java │ ├── mypack │ ├── AccountBalance.java │ ├── Balance.java │ └── Balance2.java │ ├── p1 │ ├── Demo.java │ ├── Derived.java │ ├── Protection.java │ └── SamePackage.java │ └── p2 │ ├── Demo.java │ ├── OtherPackage.java │ └── Protection2.java ├── Chapter-10 └── src │ ├── ChainExcDemo.java │ ├── Exc0.java │ ├── Exc1.java │ ├── Exc2.java │ ├── FinallyDemo.java │ ├── HandleError.java │ ├── MethNestTry.java │ ├── MultiCatch.java │ ├── MultipleCatches.java │ ├── MyException.java │ ├── NestTry.java │ ├── PrintingException.java │ ├── SuperSubCatch.java │ ├── ThrowDemo.java │ ├── ThrowsDemo.java │ └── ThrowsDemo2.java ├── Chapter-11 └── src │ ├── CurrentThreadDemo.java │ ├── Deadlock.java │ ├── DemoJoin.java │ ├── ExtendThread.java │ ├── MultiThreadDemo.java │ ├── PC.java │ ├── PCFixed.java │ ├── SuspendResume.java │ ├── Synch.java │ ├── Synch1.java │ └── ThreadDemo.java ├── Chapter-12 └── src │ ├── Apple.java │ ├── AskMe.java │ ├── AutoBox.java │ ├── AutoBox2.java │ ├── AutoBox3.java │ ├── AutoBox4.java │ ├── AutoBox5.java │ ├── EnumDemo.java │ ├── EnumDemo2.java │ ├── EnumDemo3.java │ ├── EnumDemo4.java │ ├── Marker.java │ ├── Meta.java │ ├── Meta1.java │ ├── Meta2.java │ ├── Meta3.java │ ├── RepeatAnno.java │ ├── Single.java │ ├── TypeAnnoDemo.java │ ├── UnboxingError.java │ └── Wrap.java ├── Chapter-13 └── src │ ├── AssertDemo.java │ ├── AssertDemo2.java │ ├── BRRead.java │ ├── BRReadLines.java │ ├── CopyFile.java │ ├── CopyFile2.java │ ├── Hypot.java │ ├── Hypot2.java │ ├── InstanceOf.java │ ├── MyClass.java │ ├── MyClass2.java │ ├── PrintWriterDemo.java │ ├── ShowFile.java │ ├── ShowFile2.java │ ├── ShowFile3.java │ ├── TinyEdit.java │ └── WriteDemo.java ├── Chapter-14 └── src │ ├── BoundedWildcard.java │ ├── BoundsDemo.java │ ├── BridgeDemo.java │ ├── Gen.java │ ├── Gen2.java │ ├── GenArrays.java │ ├── GenConsDemo.java │ ├── GenDemo.java │ ├── GenIFDemo.java │ ├── GenMethDemo.java │ ├── HierDemo.java │ ├── HierDemo2.java │ ├── HierDemo3.java │ ├── MyGenClass.java │ ├── NonGenDemo.java │ ├── OverrideDemo.java │ ├── RawDemo.java │ ├── SimpGen.java │ ├── Stats.java │ ├── WildcardDemo.java │ └── Wrong.java ├── Chapter-15 └── src │ ├── BlockLambdaDemo.java │ ├── BlockLambdaDemo2.java │ ├── ConstructorRefDemo.java │ ├── ConstructorRefDemo2.java │ ├── ConstructorRefDemo3.java │ ├── GenericFunctionalInterfaceDemo.java │ ├── GenericMethodRefDemo.java │ ├── InstanceMethWithObjectRefDemo.java │ ├── LambdaDemo.java │ ├── LambdaDemo2.java │ ├── LambdaDemo3.java │ ├── LambdaExceptionDemo.java │ ├── LambdasAsArgumentsDemo.java │ ├── MethodRefDemo.java │ ├── MethodRefDemo2.java │ ├── UseFunctionInterfaceDemo.java │ ├── UseMethodRef.java │ └── VarCapture.java ├── Chapter-16 ├── README.md └── src │ ├── mymodapp(initial) │ └── appsrc │ │ ├── appfuncs │ │ ├── appfuncs │ │ │ └── simplefuncs │ │ │ │ └── SimpleMathFuncs.java │ │ └── module-info.java │ │ └── appstart │ │ ├── appstart │ │ └── mymodappdemo │ │ │ └── MyModAppDemo.java │ │ └── module-info.java │ ├── mymodapp(module-based-service) │ └── appsrc │ │ ├── appfuncs │ │ ├── appfuncs │ │ │ └── simplefuncs │ │ │ │ └── SimpleMathFuncs.java │ │ └── module-info.java │ │ ├── appstart │ │ ├── appstart │ │ │ └── mymodappdemo │ │ │ │ └── MyModAppDemo.java │ │ └── module-info.java │ │ ├── userfuncs │ │ ├── module-info.java │ │ └── userfuncs │ │ │ └── binaryfuncs │ │ │ ├── BinFuncProvider.java │ │ │ └── BinaryFunc.java │ │ └── userfuncsimp │ │ ├── module-info.java │ │ └── userfuncsimp │ │ └── binaryfuncsimp │ │ ├── AbsMinus.java │ │ ├── AbsMinusProvider.java │ │ ├── AbsPlus.java │ │ └── AbsPlusProvider.java │ └── mymodapp(transitive module changes) │ └── appsrc │ ├── appfuncs │ ├── appfuncs │ │ └── simplefuncs │ │ │ └── SimpleMathFuncs.java │ └── module-info.java │ ├── appstart │ ├── appstart │ │ └── mymodappdemo │ │ │ └── MyModAppDemo.java │ └── module-info.java │ └── appsupport │ ├── appsupport │ └── supportfuncs │ │ └── SupportFuncs.java │ └── module-info.java ├── Chapter-17 └── src │ ├── BlockArrowCase.java │ ├── EmployeeRecordWithValidation.java │ ├── InstanceOfDemo.java │ ├── RecordDemo.java │ ├── RecordDemo2.java │ ├── RecordDemo3.java │ ├── RecordDemo4.java │ ├── SealedClassDemo.java │ ├── StatementSwitchWithArrows.java │ ├── SwitchExpr.java │ ├── SwitchExpr2.java │ ├── TextBlockDemo.java │ ├── TextBlockDemo2.java │ ├── TraditionalSwitch.java │ ├── UpdatedSwitch.java │ └── Vowels.java ├── Chapter-18 └── src │ ├── ChangeCase.java │ ├── ConCat.java │ ├── EqualsNotEqualTo.java │ ├── MakeString.java │ ├── ReverseDemo.java │ ├── SortString.java │ ├── StringBufferDemo.java │ ├── StringBufferIndexOfDemo.java │ ├── StringJoinDemo.java │ ├── StringReplace.java │ ├── SubStringCons.java │ ├── UseTrim.java │ ├── appendDemo.java │ ├── deleteDemo.java │ ├── equalsDemo.java │ ├── getCharsDemo.java │ ├── indexOfDemo.java │ ├── insertDemo.java │ ├── replaceDemo.java │ ├── setCharAtDemo.java │ └── toStringDemo.java ├── Chapter-19 └── src │ ├── ACDemo.java │ ├── Angles.java │ ├── CloneDemo.java │ ├── CloneDemo2.java │ ├── DoubleDemo.java │ ├── Elapsed.java │ ├── ExecDemo.java │ ├── ExecDemoFini.java │ ├── InfNaN.java │ ├── IsDemo.java │ ├── MyModAppDemo.java │ ├── PBDemo.java │ ├── ParseDemo.java │ ├── PkgTest.java │ ├── RTTI.java │ ├── ShowUserDir.java │ ├── StringConversions.java │ ├── ThreadGroupDemo.java │ └── VerDemo.java ├── Chapter-20 └── src │ ├── AlgorithmsDemo.java │ ├── ArrayDequeDemo.java │ ├── ArrayListDemo.java │ ├── ArrayListToArray.java │ ├── ArraysDemo.java │ ├── CompDemo.java │ ├── CompDemo1.java │ ├── CompDemo2.java │ ├── EnumSetDemo.java │ ├── ForEachDemo.java │ ├── HTDemo.java │ ├── HTDemo2.java │ ├── HashMapDemo.java │ ├── HashSetDemo.java │ ├── IdentityHashMapExample.java │ ├── IteratorDemo.java │ ├── LinkedHashMapDemo.java │ ├── LinkedHashSetDemo.java │ ├── LinkedListDemo.java │ ├── MailList.java │ ├── Phonebook.java │ ├── PriorityQueueDemo.java │ ├── PropDemo.java │ ├── PropDemoDef.java │ ├── SpliteratorDemo.java │ ├── StackDemo.java │ ├── TreeMapDemo.java │ ├── TreeMapDemo2.java │ ├── TreeMapDemo2A.java │ ├── TreeSetDemo.java │ └── VectorDemo.java ├── Chapter-21 └── src │ ├── AvgFile.java │ ├── AvgNums.java │ ├── BitSetDemo.java │ ├── CalendarDemo.java │ ├── CurDemo.java │ ├── DateDemo.java │ ├── FieldWidthDemo.java │ ├── FindInLineDemo.java │ ├── FormatDemo.java │ ├── FormatDemo2.java │ ├── FormatDemo3.java │ ├── FormatDemo4.java │ ├── FormatDemo5.java │ ├── FormatDemo6.java │ ├── FormatterCloseDemo.java │ ├── GregorianCalendarDemo.java │ ├── LRBDemo.java │ ├── LeftJustify.java │ ├── OptionalDemo.java │ ├── PrecisionDemo.java │ ├── RandDemo.java │ ├── STDemo.java │ ├── SampleRB.java │ ├── SampleRB_de.java │ ├── ScanMixed.java │ ├── SetDelimiters.java │ ├── TTest.java │ └── TimeDateFormat.java ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | replay_pid* 25 | 26 | .idea 27 | .vscode/settings.json 28 | -------------------------------------------------------------------------------- /Chapter-02/src/BlockTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate a block of code. 3 | 4 | Call this file "BlockTest.java" 5 | */ 6 | class BlockTest { 7 | public static void main(String[] args) { 8 | int x, y; 9 | 10 | y = 20; 11 | 12 | // the target of this loop is a block 13 | for (x = 0; x < 10; x++) { 14 | System.out.println("This is x: " + x); 15 | System.out.println("This is y: " + y); 16 | y = y - 2; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-02/src/Example.java: -------------------------------------------------------------------------------- 1 | /* 2 | This is a simple Java program. 3 | Call this file "Example.java". 4 | */ 5 | class Example { 6 | // Your program begins with a call to main(). 7 | public static void main(String[] args) { 8 | System.out.println("This is a simple Java program."); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-02/src/Example2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Here is another short example. 3 | Call this file "Example2.java". 4 | */ 5 | class Example2 { 6 | public static void main(String[] args) { 7 | int num; // this declares a variable called num 8 | 9 | num = 100; // this assigns num the value 100 10 | 11 | System.out.println("This is num: " + num); 12 | 13 | num = num * 2; 14 | 15 | System.out.print("The value of num * 2 is "); 16 | System.out.println(num); 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter-02/src/ForTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate the for loop. 3 | 4 | Call this file "ForTest.java". 5 | */ 6 | class ForTest { 7 | public static void main(String[] args) { 8 | int x; 9 | 10 | for (x = 0; x < 10; x = x + 1) 11 | System.out.println("This is x: " + x); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-02/src/IfSample.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate the if. 3 | 4 | Call this file "IfSample.java". 5 | */ 6 | class IfSample { 7 | public static void main(String[] args) { 8 | int x, y; 9 | 10 | x = 10; 11 | y = 20; 12 | 13 | if (x < y) System.out.println("x is less than y"); 14 | 15 | x = x * 2; 16 | if (x == y) System.out.println("x now equal to y"); 17 | 18 | x = x * 2; 19 | if (x > y) System.out.println("x now greater than y"); 20 | 21 | // this won't display anything 22 | if (x == y) System.out.println("you won't see this"); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-03/src/Area.java: -------------------------------------------------------------------------------- 1 | // Compute the area of a circle. 2 | class Area { 3 | public static void main(String[] args) { 4 | double pi, r, a; 5 | 6 | r = 10.8; // radius of circle 7 | pi = 3.1416; // pi, approximately 8 | a = pi * r * r; // compute area 9 | 10 | System.out.println("Area of circle is " + a); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-03/src/Array.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a one-dimensional array. 2 | class Array { 3 | public static void main(String[] args) { 4 | int[] month_days; 5 | month_days = new int[12]; 6 | month_days[0] = 31; 7 | month_days[1] = 28; 8 | month_days[2] = 31; 9 | month_days[3] = 30; 10 | month_days[4] = 31; 11 | month_days[5] = 30; 12 | month_days[6] = 31; 13 | month_days[7] = 31; 14 | month_days[8] = 30; 15 | month_days[9] = 31; 16 | month_days[10] = 30; 17 | month_days[11] = 31; 18 | System.out.println("April has " + month_days[3] + " days."); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-03/src/AutoArray.java: -------------------------------------------------------------------------------- 1 | // An improvied version of the previous program. 2 | class AutoArray { 3 | public static void main(String[] args) { 4 | int[] month_days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 5 | System.out.println("April has " + month_days[3] + " days."); 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter-03/src/Average.java: -------------------------------------------------------------------------------- 1 | // Average an array of values. 2 | class Average { 3 | public static void main(String[] args) { 4 | double[] nums = {10.1, 11.2, 12.3, 13.4, 14.5}; 5 | double result = 0; 6 | int i; 7 | 8 | for (i = 0; i < 5; i++) 9 | result = result + nums[i]; 10 | 11 | System.out.println("Average is " + result / 5); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-03/src/BoolTest.java: -------------------------------------------------------------------------------- 1 | // Demonstrate boolean values. 2 | class BoolTest { 3 | public static void main(String[] args) { 4 | boolean b; 5 | 6 | b = false; 7 | System.out.println("b is " + b); 8 | b = true; 9 | System.out.println("b is " + b); 10 | 11 | // a boolean value can control the if statement 12 | if (b) System.out.println("This is executed."); 13 | 14 | b = false; 15 | if (b) System.out.println("This is not executed."); 16 | 17 | // outcome of a relational operator is a boolean value 18 | System.out.println("10 > 9 is " + (10 > 9)); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-03/src/CharDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate char data type. 2 | class CharDemo { 3 | public static void main(String[] args) { 4 | char ch1, ch2; 5 | 6 | ch1 = 88; // code for X 7 | ch2 = 'Y'; 8 | 9 | System.out.print("ch1 and ch2: "); 10 | System.out.println(ch1 + " " + ch2); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-03/src/CharDemo2.java: -------------------------------------------------------------------------------- 1 | // char variables behave like integers. 2 | class CharDemo2 { 3 | public static void main(String[] args) { 4 | char ch1; 5 | 6 | ch1 = 'X'; 7 | System.out.println("ch1 contains " + ch1); 8 | 9 | ch1++; // increment ch1 10 | System.out.println("ch1 is now " + ch1); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-03/src/Conversion.java: -------------------------------------------------------------------------------- 1 | // Demonstrate casts. 2 | class Conversion { 3 | public static void main(String[] args) { 4 | byte b; 5 | int i = 257; 6 | double d = 323.142; 7 | 8 | System.out.println("\nConversion of int to byte."); 9 | b = (byte) i; 10 | System.out.println("i and b " + i + " " + b); 11 | 12 | System.out.println("\nConversion of double to int."); 13 | i = (int) d; 14 | System.out.println("d and i " + d + " " + i); 15 | 16 | System.out.println("\nConversion of double to byte."); 17 | b = (byte) d; 18 | System.out.println("d and b " + d + " " + b); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-03/src/DynInit.java: -------------------------------------------------------------------------------- 1 | // Demonstrate dynamic initialization. 2 | class DynInit { 3 | public static void main(String[] args) { 4 | double a = 3.0, b = 4.0; 5 | 6 | // c is dynamically initialized 7 | double c = Math.sqrt(a * a + b * b); 8 | 9 | System.out.println("Hypotenuse is " + c); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-03/src/LifeTime.java: -------------------------------------------------------------------------------- 1 | // Demonstrate lifetime of a variable. 2 | class LifeTime { 3 | public static void main(String[] args) { 4 | int x; 5 | 6 | for (x = 0; x < 3; x++) { 7 | int y = -1; // y is initialized each time block is entered 8 | System.out.println("y iz: " + y); // this always prints -1 9 | y = 100; 10 | System.out.println("y is now: " + y); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-03/src/Light.java: -------------------------------------------------------------------------------- 1 | // Compute distance light travels using long variables. 2 | class Light { 3 | public static void main(String[] args) { 4 | int lightspeed; 5 | long days; 6 | long seconds; 7 | long distance; 8 | 9 | // approximate speed of light in miles per second 10 | lightspeed = 186000; 11 | 12 | days = 1000; // specify number of days here 13 | 14 | seconds = days * 24 * 60 * 60; // convert to seconds 15 | 16 | distance = lightspeed * seconds; // compute distance 17 | 18 | System.out.print("In " + days); 19 | System.out.print(" days light will travel about "); 20 | System.out.println(distance + " miles."); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-03/src/Matrix.java: -------------------------------------------------------------------------------- 1 | // Initialize a two-dimensional array. 2 | class Matrix { 3 | public static void main(String[] args) { 4 | double[][] m = { 5 | {0 * 0, 1 * 0, 2 * 0, 3 * 0}, 6 | {0 * 1, 1 * 1, 2 * 1, 3 * 1}, 7 | {0 * 2, 1 * 2, 2 * 2, 3 * 2}, 8 | {0 * 3, 1 * 3, 2 * 3, 3 * 3} 9 | }; 10 | int i, j; 11 | 12 | for (i = 0; i < 4; i++) { 13 | for (j = 0; j < 4; j++) 14 | System.out.print(m[i][j] + " "); 15 | System.out.println(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter-03/src/Promote.java: -------------------------------------------------------------------------------- 1 | class Promote { 2 | public static void main(String[] args) { 3 | byte b = 42; 4 | char c = 'a'; 5 | short s = 1024; 6 | int i = 50000; 7 | float f = 5.67f; 8 | double d = .1234; 9 | double result = (f * b) + (i / c) - (d * s); 10 | System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); 11 | System.out.println("result = " + result); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter-03/src/Scope.java: -------------------------------------------------------------------------------- 1 | // Demonstrate block scope. 2 | class Scope { 3 | public static void main(String[] args) { 4 | int x; // known to all code within main 5 | 6 | x = 10; 7 | if (x == 10) { // start new scope 8 | int y = 20; // known only to this block 9 | 10 | // x and y both known here. 11 | System.out.println("x and y: " + x + " " + y); 12 | x = y * 2; 13 | } 14 | // y = 100; // Error! y not known here 15 | 16 | // x is still known here. 17 | System.out.println("x is " + x); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-03/src/ScopeErr.java: -------------------------------------------------------------------------------- 1 | // This program will not compile 2 | class ScopeErr { 3 | public static void main(String[] args) { 4 | int bar = 1; 5 | { // creates a new scope 6 | int bar = 2; // Compile time error -- bar already defined! 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter-03/src/ThreeDMatrix.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a three-dimensional array. 2 | class ThreeDMatrix { 3 | public static void main(String[] args) { 4 | int[][][] threeD = new int[3][4][5]; 5 | int i, j, k; 6 | 7 | for (i = 0; i < 3; i++) 8 | for (j = 0; j < 4; j++) 9 | for (k = 0; k < 5; k++) 10 | threeD[i][j][k] = i * j * k; 11 | 12 | for (i = 0; i < 3; i++) { 13 | for (j = 0; j < 4; j++) { 14 | for (k = 0; k < 5; k++) 15 | System.out.print(threeD[i][j][k] + " "); 16 | System.out.println(); 17 | } 18 | System.out.println(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-03/src/TwoDAgain.java: -------------------------------------------------------------------------------- 1 | // Manually allocate differing size second dimensions. 2 | class TwoDAgain { 3 | public static void main(String[] args) { 4 | int[][] twoD = new int[4][]; 5 | twoD[0] = new int[1]; 6 | twoD[1] = new int[2]; 7 | twoD[2] = new int[3]; 8 | twoD[3] = new int[4]; 9 | 10 | int i, j, k = 0; 11 | 12 | for (i = 0; i < 4; i++) 13 | for (j = 0; j < i + 1; j++) { 14 | twoD[i][j] = k; 15 | k++; 16 | } 17 | 18 | for (i = 0; i < 4; i++) { 19 | for (j = 0; j < i + 1; j++) 20 | System.out.print(twoD[i][j] + " "); 21 | System.out.println(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-03/src/TwoDArray.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a two-dimensional array. 2 | class TwoDArray { 3 | public static void main(String[] args) { 4 | int[][] twoD = new int[4][5]; 5 | int i, j, k = 0; 6 | 7 | for (i = 0; i < 4; i++) 8 | for (j = 0; j < 5; j++) { 9 | twoD[i][j] = k; 10 | k++; 11 | } 12 | 13 | for (i = 0; i < 4; i++) { 14 | for (j = 0; j < 5; j++) 15 | System.out.print(twoD[i][j] + " "); 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter-03/src/VarDemo.java: -------------------------------------------------------------------------------- 1 | // A simple demonstration of local variable type inference. 2 | class VarDemo { 3 | public static void main(String[] args) { 4 | 5 | // Use type inference to determine the type of the 6 | // variable named avg. In this case, double is inferred. 7 | var avg = 10.0; 8 | System.out.println("Value of avg: " + avg); 9 | 10 | // In the following context, var is not a predefined identifier. 11 | // It is simply a user-defined variable name. 12 | int var = 1; 13 | System.out.println("Value of var: " + var); 14 | 15 | // Interestingly, in the following sequence, var is used 16 | // as both the type of the declaration and as a variable name 17 | // in the initializer. 18 | var k = -var; 19 | System.out.println("Value of k: " + k); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter-04/src/BasicMath.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the basic arithmetic operators. 2 | class BasicMath { 3 | public static void main(String[] args) { 4 | // arithmetic using integers 5 | System.out.println("Integer Arithmetic"); 6 | int a = 1 + 1; 7 | int b = a * 3; 8 | int c = b / 4; 9 | int d = c - a; 10 | int e = -d; 11 | System.out.println("a = " + a); 12 | System.out.println("b = " + b); 13 | System.out.println("c = " + c); 14 | System.out.println("d = " + d); 15 | System.out.println("e = " + e); 16 | 17 | // arithmetic using doubles 18 | System.out.println("\nFloating Point Arithmetic"); 19 | double da = 1 + 1; 20 | double db = da * 3; 21 | double dc = db / 4; 22 | double dd = dc - a; 23 | double de = -dd; 24 | System.out.println("da = " + da); 25 | System.out.println("db = " + db); 26 | System.out.println("dc = " + dc); 27 | System.out.println("dd = " + dd); 28 | System.out.println("de = " + de); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter-04/src/BitLogic.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the bitwise logical operators. 2 | class BitLogic { 3 | public static void main(String[] args) { 4 | String[] binary = { 5 | "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", 6 | "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" 7 | }; 8 | int a = 3; // 0 + 2 + 1 or 0011 in binary 9 | int b = 6; // 4 + 2 + 0 or 0110 in binary 10 | int c = a | b; 11 | int d = a & b; 12 | int e = a ^ b; 13 | int f = (~a & b) | (a & ~b); 14 | int g = ~a & 0x0f; 15 | 16 | System.out.println(" a = " + binary[a]); 17 | System.out.println(" b = " + binary[b]); 18 | System.out.println(" a|b = " + binary[c]); 19 | System.out.println(" a&b = " + binary[d]); 20 | System.out.println(" a^b = " + binary[e]); 21 | System.out.println("~a&b|a&~b = " + binary[f]); 22 | System.out.println(" ~a = " + binary[g]); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-04/src/BoolLogic.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the boolean logical operators. 2 | class BoolLogic { 3 | public static void main(String[] args) { 4 | boolean a = true; 5 | boolean b = false; 6 | boolean c = a | b; 7 | boolean d = a & b; 8 | boolean e = a ^ b; 9 | boolean f = (!a & b) | (a & !b); 10 | boolean g = !a; 11 | 12 | System.out.println(" a = " + a); 13 | System.out.println(" b = " + b); 14 | System.out.println(" a|b = " + c); 15 | System.out.println(" a&b = " + d); 16 | System.out.println(" a^b = " + e); 17 | System.out.println("!a&b|a&!b = " + f); 18 | System.out.println(" !a = " + g); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-04/src/ByteShift.java: -------------------------------------------------------------------------------- 1 | // Left shifting a byte value. 2 | class ByteShift { 3 | public static void main(String[] args) { 4 | byte a = 64, b; 5 | int i; 6 | 7 | i = a << 2; 8 | b = (byte) (a << 2); 9 | 10 | System.out.println("Original value of a: " + a); 11 | System.out.println("i and b: " + i + " " + b); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-04/src/ByteUShift.java: -------------------------------------------------------------------------------- 1 | // Unsigned shifting a byte value. 2 | class ByteUShift { 3 | static public void main(String[] args) { 4 | char[] hex = { 5 | '0', '1', '2', '3', '4', '5', '6', '7', 6 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 7 | }; 8 | byte b = (byte) 0xf1; 9 | byte c = (byte) (b >> 4); 10 | byte d = (byte) (b >>> 4); 11 | byte e = (byte) ((b & 0xff) >> 4); 12 | 13 | System.out.println(" b = 0x" 14 | + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]); 15 | System.out.println(" b >> 4 = 0x" 16 | + hex[(c >> 4) & 0x0f] + hex[c & 0x0f]); 17 | System.out.println(" b >>> 4 = 0x" 18 | + hex[(d >> 4) & 0x0f] + hex[d & 0x0f]); 19 | System.out.println("(b & 0xff) >> 4 = 0x" 20 | + hex[(e >> 4) & 0x0f] + hex[e & 0x0f]); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-04/src/HexByte.java: -------------------------------------------------------------------------------- 1 | // Masking sign extension. 2 | class HexByte { 3 | static public void main(String[] args) { 4 | char[] hex = { 5 | '0', '1', '2', '3', '4', '5', '6', '7', 6 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 7 | }; 8 | byte b = (byte) 0xf1; 9 | 10 | System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-04/src/IncDec.java: -------------------------------------------------------------------------------- 1 | // Demonstrate ++ and --. 2 | class IncDec { 3 | public static void main(String[] args) { 4 | int a = 1; 5 | int b = 2; 6 | int c; 7 | int d; 8 | 9 | c = ++b; 10 | d = a++; 11 | c++; 12 | System.out.println("a = " + a); 13 | System.out.println("b = " + b); 14 | System.out.println("c = " + c); 15 | System.out.println("d = " + d); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-04/src/Modulus.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the % operator. 2 | class Modulus { 3 | public static void main(String[] args) { 4 | int x = 42; 5 | double y = 42.25; 6 | 7 | System.out.println("x mod 10 = " + x % 10); 8 | System.out.println("y mod 10 = " + y % 10); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-04/src/MultByTwo.java: -------------------------------------------------------------------------------- 1 | // Left shifting as a quick way to multiply by 2. 2 | class MultByTwo { 3 | public static void main(String[] args) { 4 | int i; 5 | int num = 0xFFFFFFE; 6 | 7 | for (i = 0; i < 4; i++) { 8 | num = num << 1; 9 | System.out.println(num); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-04/src/OpBitEquals.java: -------------------------------------------------------------------------------- 1 | class OpBitEquals { 2 | public static void main(String[] args) { 3 | int a = 1; 4 | int b = 2; 5 | int c = 3; 6 | 7 | a |= 4; 8 | b >>= 1; 9 | c <<= 1; 10 | a ^= c; 11 | System.out.println("a = " + a); 12 | System.out.println("b = " + b); 13 | System.out.println("c = " + c); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-04/src/OpEquals.java: -------------------------------------------------------------------------------- 1 | // Demonstrate several assignment operators. 2 | class OpEquals { 3 | public static void main(String[] args) { 4 | int a = 1; 5 | int b = 2; 6 | int c = 3; 7 | 8 | a += 5; 9 | b *= 4; 10 | c += a * b; 11 | c %= 6; 12 | System.out.println("a = " + a); 13 | System.out.println("b = " + b); 14 | System.out.println("c = " + c); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-04/src/Ternary.java: -------------------------------------------------------------------------------- 1 | // Demonstrate ?. 2 | class Ternary { 3 | public static void main(String[] args) { 4 | int i, k; 5 | 6 | i = 10; 7 | k = i < 0 ? -i : i; // get absolute value of i 8 | System.out.print("Absolute value of "); 9 | System.out.println(i + " is " + k); 10 | 11 | i = -10; 12 | k = i < 0 ? -i : i; // get absolute value of i 13 | System.out.print("Absolute value of "); 14 | System.out.println(i + " is " + k); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-05/src/Break.java: -------------------------------------------------------------------------------- 1 | // Using break as a civilized form of goto. 2 | class Break { 3 | public static void main(String[] args) { 4 | boolean t = true; 5 | 6 | first: 7 | { 8 | second: 9 | { 10 | third: 11 | { 12 | System.out.println("Before the break."); 13 | if (t) break second; // break out of second block 14 | System.out.println("This won't execute"); 15 | } 16 | System.out.println("This won't execute"); 17 | } 18 | System.out.println("This is after second block."); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-05/src/BreakErr.java: -------------------------------------------------------------------------------- 1 | // This program contains an error. 2 | class BreakErr { 3 | public static void main(String[] args) { 4 | 5 | one: 6 | for (int i = 0; i < 3; i++) { 7 | System.out.print("Pass " + i + ": "); 8 | } 9 | 10 | for (int j = 0; j < 100; j++) { 11 | if (j == 10) break one; // WRONG 12 | System.out.print(j + " "); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-05/src/BreakLoop.java: -------------------------------------------------------------------------------- 1 | // Using break to exit a loop. 2 | class BreakLoop { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < 100; i++) { 5 | if (i == 10) break; // terminate loop if i is 10 6 | System.out.println("i: " + i); 7 | } 8 | System.out.println("Loop complete."); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-05/src/BreakLoop2.java: -------------------------------------------------------------------------------- 1 | // Using break to exit a while loop. 2 | class BreakLoop2 { 3 | public static void main(String[] args) { 4 | int i = 0; 5 | 6 | while (i < 100) { 7 | if (i == 10) break; // terminate loop if i is 10 8 | System.out.println("i: " + i); 9 | i++; 10 | } 11 | System.out.println("Loop complete."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter-05/src/BreakLoop3.java: -------------------------------------------------------------------------------- 1 | // Using break with nested loops. 2 | class BreakLoop3 { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < 3; i++) { 5 | System.out.print("Pass " + i + ": "); 6 | for (int j = 0; j < 100; j++) { 7 | if (j == 10) break; // terminate loop if j is 10 8 | System.out.print(j + " "); 9 | } 10 | System.out.println(); 11 | } 12 | System.out.println("Loops complete."); 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter-05/src/BreakLoop4.java: -------------------------------------------------------------------------------- 1 | // Using break to exit from nested loops 2 | class BreakLoop4 { 3 | public static void main(String[] args) { 4 | outer: 5 | for (int i = 0; i < 3; i++) { 6 | System.out.print("Pass " + i + ": "); 7 | for (int j = 0; j < 100; j++) { 8 | if (j == 10) break outer; // exit both loops 9 | System.out.print(j + " "); 10 | } 11 | System.out.println("This will not print"); 12 | } 13 | System.out.println("Loops complete."); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-05/src/Comma.java: -------------------------------------------------------------------------------- 1 | // Using the comma. 2 | class Comma { 3 | public static void main(String[] args) { 4 | int a, b; 5 | 6 | for (a = 1, b = 4; a < b; a++, b--) { 7 | System.out.println("a = " + a); 8 | System.out.println("b = " + b); 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-05/src/Continue.java: -------------------------------------------------------------------------------- 1 | // Demonstrate continue. 2 | class Continue { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < 10; i++) { 5 | System.out.print(i + " "); 6 | if (i % 2 == 0) continue; 7 | System.out.println(""); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-05/src/ContinueLabel.java: -------------------------------------------------------------------------------- 1 | // Using continue with a label. 2 | class ContinueLabel { 3 | public static void main(String[] args) { 4 | outer: 5 | for (int i = 0; i < 10; i++) { 6 | for (int j = 0; j < 10; j++) { 7 | if (j > i) { 8 | System.out.println(); 9 | continue outer; 10 | } 11 | System.out.print(" " + (i * j)); 12 | } 13 | } 14 | System.out.println(); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-05/src/DoWhile.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the do-while loop. 2 | class DoWhile { 3 | public static void main(String[] args) { 4 | int n = 10; 5 | 6 | do { 7 | System.out.println("tick " + n); 8 | n--; 9 | } while (n > 0); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-05/src/FindPrime.java: -------------------------------------------------------------------------------- 1 | // Test for primes. 2 | class FindPrime { 3 | public static void main(String[] args) { 4 | int num; 5 | boolean isPrime; 6 | 7 | num = 14; 8 | 9 | if (num < 2) isPrime = false; 10 | else isPrime = true; 11 | 12 | for (int i = 2; i <= num / i; i++) { 13 | if ((num % i) == 0) { 14 | isPrime = false; 15 | break; 16 | } 17 | } 18 | 19 | if (isPrime) System.out.println("Prime"); 20 | else System.out.println("Not Prime"); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-05/src/ForEach.java: -------------------------------------------------------------------------------- 1 | // Use a for-each style for loop. 2 | class ForEach { 3 | public static void main(String[] args) { 4 | int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 5 | int sum = 0; 6 | 7 | // use for-each style for to display and sum the values 8 | for (int x : nums) { 9 | System.out.println("Value is: " + x); 10 | sum += x; 11 | } 12 | 13 | System.out.println("Summation: " + sum); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-05/src/ForEach2.java: -------------------------------------------------------------------------------- 1 | // Use break with a for-each style for. 2 | class ForEach2 { 3 | public static void main(String[] args) { 4 | int sum = 0; 5 | int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 6 | 7 | // use for to display and sum the values 8 | for (int x : nums) { 9 | System.out.println("Value is: " + x); 10 | sum += x; 11 | if (x == 5) break; // stop the loop when 5 is obtained 12 | } 13 | System.out.println("Summation of first 5 elements: " + sum); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter-05/src/ForEach3.java: -------------------------------------------------------------------------------- 1 | // Use for-each style for on a two-dimensional array. 2 | class ForEach3 { 3 | public static void main(String[] args) { 4 | int sum = 0; 5 | int[][] nums = new int[3][5]; 6 | 7 | // give nums some values 8 | for (int i = 0; i < 3; i++) 9 | for (int j = 0; j < 5; j++) 10 | nums[i][j] = (i + 1) * (j + 1); 11 | 12 | // use for-each for to display and sum the values 13 | for (int[] x : nums) { 14 | for (int y : x) { 15 | System.out.println("Value is: " + y); 16 | sum += y; 17 | } 18 | } 19 | System.out.println("Summation: " + sum); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-05/src/ForTick.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the for loop. 2 | class ForTick { 3 | public static void main(String[] args) { 4 | int n; 5 | 6 | for (n = 10; n > 0; n--) 7 | System.out.println("tick " + n); 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-05/src/ForTick2.java: -------------------------------------------------------------------------------- 1 | // Declare a loop control variable inside the for. 2 | class ForTick2 { 3 | public static void main(String[] args) { 4 | 5 | // here, n is declared inside of the for loop 6 | for (int n = 10; n > 0; n--) 7 | System.out.println("tick " + n); 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-05/src/ForVar.java: -------------------------------------------------------------------------------- 1 | // Parts of the for loop can be empty. 2 | class ForVar { 3 | public static void main(String[] args) { 4 | int i; 5 | boolean done = false; 6 | 7 | i = 0; 8 | for (; !done; ) { 9 | System.out.println("i is " + i); 10 | if (i == 10) done = true; 11 | i++; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter-05/src/IfElse.java: -------------------------------------------------------------------------------- 1 | // Demonstrate if-else-if statements. 2 | class IfElse { 3 | public static void main(String[] args) { 4 | int month = 4; // April 5 | String season; 6 | 7 | if (month == 12 || month == 1 || month == 2) 8 | season = "Winter"; 9 | else if (month == 3 || month == 4 || month == 5) 10 | season = "Spring"; 11 | else if (month == 6 || month == 7 || month == 8) 12 | season = "Summer"; 13 | else if (month == 9 || month == 10 || month == 11) 14 | season = "Autumn"; 15 | else 16 | season = "Bogus Month"; 17 | 18 | System.out.println("April is in the " + season + "."); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-05/src/MissingBreak.java: -------------------------------------------------------------------------------- 1 | // In a switch, break statements are optional. 2 | class MissingBreak { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < 12; i++) 5 | switch (i) { 6 | case 0: 7 | case 1: 8 | case 2: 9 | case 3: 10 | case 4: 11 | System.out.println("i is less than 5"); 12 | break; 13 | case 5: 14 | case 6: 15 | case 7: 16 | case 8: 17 | case 9: 18 | System.out.println("i is less than 10"); 19 | break; 20 | default: 21 | System.out.println("i is 10 or more."); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-05/src/Nested.java: -------------------------------------------------------------------------------- 1 | // Loops may be nested. 2 | class Nested { 3 | public static void main(String[] args) { 4 | int i, j; 5 | 6 | for (i = 0; i < 10; i++) { 7 | for (j = i; j < 10; j++) 8 | System.out.print("."); 9 | System.out.println(); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter-05/src/NoBody.java: -------------------------------------------------------------------------------- 1 | // The target of a loop can be empty. 2 | class NoBody { 3 | public static void main(String[] args) { 4 | int i, j; 5 | 6 | i = 100; 7 | j = 200; 8 | 9 | // find midpoint between i and j 10 | while (++i < --j) ; // no body in this loop 11 | 12 | System.out.println("Midpoint is " + i); 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter-05/src/NoChange.java: -------------------------------------------------------------------------------- 1 | // The for-each loop is essentially read-only. 2 | class NoChange { 3 | public static void main(String[] args) { 4 | int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 5 | 6 | for (int x : nums) { 7 | System.out.print(x + " "); 8 | x = x * 10; // no effect on nums 9 | } 10 | 11 | System.out.println(); 12 | 13 | for (int x : nums) 14 | System.out.print(x + " "); 15 | 16 | System.out.println(); 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter-05/src/Return.java: -------------------------------------------------------------------------------- 1 | // Demonstrate return. 2 | class Return { 3 | public static void main(String[] args) { 4 | boolean t = true; 5 | 6 | System.out.println("Before the return."); 7 | 8 | if (t) return; // return to caller 9 | 10 | System.out.println("This won't execute."); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-05/src/Sample.java: -------------------------------------------------------------------------------- 1 | class Sample { 2 | public static void main(String[] args) { 3 | int a, b; 4 | 5 | b = 4; 6 | for (a = 1; a < b; a++) { 7 | System.out.println("a = " + a); 8 | System.out.println("b = " + b); 9 | b--; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-05/src/SampleSwitch.java: -------------------------------------------------------------------------------- 1 | // A simple example of the switch. 2 | class SampleSwitch { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < 6; i++) 5 | switch (i) { 6 | case 0: 7 | System.out.println("i is zero."); 8 | break; 9 | case 1: 10 | System.out.println("i is one."); 11 | break; 12 | case 2: 13 | System.out.println("i is two."); 14 | break; 15 | case 3: 16 | System.out.println("i is three."); 17 | break; 18 | default: 19 | System.out.println("i is greater than 3."); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter-05/src/Search.java: -------------------------------------------------------------------------------- 1 | // Search an array using for-each style for. 2 | class Search { 3 | public static void main(String[] args) { 4 | int[] nums = {6, 8, 3, 7, 5, 6, 1, 4}; 5 | int val = 5; 6 | boolean found = false; 7 | 8 | // use for-each style for to search nums for val 9 | for (int x : nums) { 10 | if (x == val) { 11 | found = true; 12 | break; 13 | } 14 | } 15 | 16 | if (found) 17 | System.out.println("Value found!"); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-05/src/StringSwitch.java: -------------------------------------------------------------------------------- 1 | // Use a string to control a switch statement. 2 | 3 | class StringSwitch { 4 | public static void main(String[] args) { 5 | 6 | String str = "two"; 7 | 8 | switch (str) { 9 | case "one": 10 | System.out.println("one"); 11 | break; 12 | case "two": 13 | System.out.println("two"); 14 | break; 15 | case "three": 16 | System.out.println("three"); 17 | break; 18 | default: 19 | System.out.println("no match"); 20 | break; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter-05/src/Switch.java: -------------------------------------------------------------------------------- 1 | // An improved version of the season program. 2 | class Switch { 3 | public static void main(String[] args) { 4 | int month = 4; 5 | String season; 6 | 7 | switch (month) { 8 | case 12: 9 | case 1: 10 | case 2: 11 | season = "Winter"; 12 | break; 13 | case 3: 14 | case 4: 15 | case 5: 16 | season = "Spring"; 17 | break; 18 | case 6: 19 | case 7: 20 | case 8: 21 | season = "Summer"; 22 | break; 23 | case 9: 24 | case 10: 25 | case 11: 26 | season = "Autumn"; 27 | break; 28 | default: 29 | season = "Bogus Month"; 30 | } 31 | System.out.println("April is in the " + season + "."); 32 | } 33 | } -------------------------------------------------------------------------------- /Chapter-05/src/TypeInferenceInFor.java: -------------------------------------------------------------------------------- 1 | // Use type inference in a for loop. 2 | class TypeInferenceInFor { 3 | public static void main(String[] args) { 4 | 5 | // Use type inference with the loop control variable. 6 | System.out.print("Values of x: "); 7 | for (var x = 2.5; x < 100.0; x = x * 2) 8 | System.out.print(x + " "); 9 | 10 | System.out.println(); 11 | 12 | // Use type inference with the iteration variable. 13 | int[] nums = {1, 2, 3, 4, 5, 6}; 14 | System.out.print("Values in nums array: "); 15 | for (var v : nums) 16 | System.out.print(v + " "); 17 | 18 | System.out.println(); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-05/src/While.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the while loop. 2 | class While { 3 | public static void main(String[] args) { 4 | int n = 10; 5 | 6 | while (n > 0) { 7 | System.out.println("tick " + n); 8 | n--; 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-06/src/Box.java: -------------------------------------------------------------------------------- 1 | class Box { 2 | double width; 3 | double height; 4 | double depth; 5 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxConstructorExamples.java: -------------------------------------------------------------------------------- 1 | /* Here, Box uses a parameterized constructor to 2 | initialize the dimensions of a box. 3 | */ 4 | class Box { 5 | double width; 6 | double height; 7 | double depth; 8 | 9 | // A redundant use of this. 10 | Box(double w, double h, double d) { 11 | this.width = w; 12 | this.height = h; 13 | this.depth = d; 14 | } 15 | 16 | // compute and return volume 17 | double volume() { 18 | return width * height * depth; 19 | } 20 | } 21 | 22 | class Box { 23 | double width; 24 | double height; 25 | double depth; 26 | 27 | // Use this to resolve name-space collisions. 28 | Box(double width, double height, double depth) { 29 | this.width = width; 30 | this.height = height; 31 | this.depth = depth; 32 | } 33 | 34 | // compute and return volume 35 | double volume() { 36 | return width * height * depth; 37 | } 38 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo.java: -------------------------------------------------------------------------------- 1 | /* A program that uses the Box class. 2 | 3 | Call this file BoxDemo.java 4 | */ 5 | class Box { 6 | double width; 7 | double height; 8 | double depth; 9 | } 10 | 11 | // This class declares an object of type Box. 12 | class BoxDemo { 13 | 14 | public static void main(String[] args) { 15 | Box mybox = new Box(); 16 | double vol; 17 | 18 | // assign values to mybox's instance variables 19 | mybox.width = 10; 20 | mybox.height = 20; 21 | mybox.depth = 15; 22 | 23 | // compute volume of box 24 | vol = mybox.width * mybox.height * mybox.depth; 25 | 26 | System.out.println("Volume is " + vol); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo2.java: -------------------------------------------------------------------------------- 1 | // This program declares two Box objects. 2 | 3 | class Box { 4 | double width; 5 | double height; 6 | double depth; 7 | } 8 | 9 | class BoxDemo2 { 10 | public static void main(String[] args) { 11 | Box mybox1 = new Box(); 12 | Box mybox2 = new Box(); 13 | double vol; 14 | 15 | // assign values to mybox1's instance variables 16 | mybox1.width = 10; 17 | mybox1.height = 20; 18 | mybox1.depth = 15; 19 | 20 | /* assign different values to mybox2's 21 | instance variables */ 22 | mybox2.width = 3; 23 | mybox2.height = 6; 24 | mybox2.depth = 9; 25 | 26 | // compute volume of first box 27 | vol = mybox1.width * mybox1.height * mybox1.depth; 28 | System.out.println("Volume is " + vol); 29 | 30 | // compute volume of second box 31 | vol = mybox2.width * mybox2.height * mybox2.depth; 32 | System.out.println("Volume is " + vol); 33 | } 34 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo3.java: -------------------------------------------------------------------------------- 1 | // This program includes a method inside the box class. 2 | 3 | class Box { 4 | double width; 5 | double height; 6 | double depth; 7 | 8 | // display volume of a box 9 | void volume() { 10 | System.out.print("Volume is "); 11 | System.out.println(width * height * depth); 12 | } 13 | } 14 | 15 | class BoxDemo3 { 16 | public static void main(String[] args) { 17 | Box mybox1 = new Box(); 18 | Box mybox2 = new Box(); 19 | 20 | // assign values to mybox1's instance variables 21 | mybox1.width = 10; 22 | mybox1.height = 20; 23 | mybox1.depth = 15; 24 | 25 | /* assign different values to mybox2's 26 | instance variables */ 27 | mybox2.width = 3; 28 | mybox2.height = 6; 29 | mybox2.depth = 9; 30 | 31 | // display volume of first box 32 | mybox1.volume(); 33 | 34 | // display volume of second box 35 | mybox2.volume(); 36 | } 37 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo4.java: -------------------------------------------------------------------------------- 1 | // Now, volume() returns the volume of a box. 2 | 3 | class Box { 4 | double width; 5 | double height; 6 | double depth; 7 | 8 | // compute and return volume 9 | double volume() { 10 | return width * height * depth; 11 | } 12 | } 13 | 14 | class BoxDemo4 { 15 | public static void main(String[] args) { 16 | Box mybox1 = new Box(); 17 | Box mybox2 = new Box(); 18 | double vol; 19 | 20 | // assign values to mybox1's instance variables 21 | mybox1.width = 10; 22 | mybox1.height = 20; 23 | mybox1.depth = 15; 24 | 25 | /* assign different values to mybox2's 26 | instance variables */ 27 | mybox2.width = 3; 28 | mybox2.height = 6; 29 | mybox2.depth = 9; 30 | 31 | // get volume of first box 32 | vol = mybox1.volume(); 33 | System.out.println("Volume is " + vol); 34 | 35 | // get volume of second box 36 | vol = mybox2.volume(); 37 | System.out.println("Volume is " + vol); 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo5.java: -------------------------------------------------------------------------------- 1 | // This program uses a parameterized method. 2 | 3 | class Box { 4 | double width; 5 | double height; 6 | double depth; 7 | 8 | // compute and return volume 9 | double volume() { 10 | return width * height * depth; 11 | } 12 | 13 | // sets dimensions of box 14 | void setDim(double w, double h, double d) { 15 | width = w; 16 | height = h; 17 | depth = d; 18 | } 19 | } 20 | 21 | class BoxDemo5 { 22 | public static void main(String[] args) { 23 | Box mybox1 = new Box(); 24 | Box mybox2 = new Box(); 25 | double vol; 26 | 27 | // initialize each box 28 | mybox1.setDim(10, 20, 15); 29 | mybox2.setDim(3, 6, 9); 30 | 31 | // get volume of first box 32 | vol = mybox1.volume(); 33 | System.out.println("Volume is " + vol); 34 | 35 | // get volume of second box 36 | vol = mybox2.volume(); 37 | System.out.println("Volume is " + vol); 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo6.java: -------------------------------------------------------------------------------- 1 | /* Here, Box uses a constructor to initialize the 2 | dimensions of a box. 3 | */ 4 | class Box { 5 | double width; 6 | double height; 7 | double depth; 8 | 9 | // This is the constructor for Box. 10 | Box() { 11 | System.out.println("Constructing Box"); 12 | width = 10; 13 | height = 10; 14 | depth = 10; 15 | } 16 | 17 | // compute and return volume 18 | double volume() { 19 | return width * height * depth; 20 | } 21 | } 22 | 23 | class BoxDemo6 { 24 | public static void main(String[] args) { 25 | // declare, allocate, and initialize Box objects 26 | Box mybox1 = new Box(); 27 | Box mybox2 = new Box(); 28 | 29 | double vol; 30 | 31 | // get volume of first box 32 | vol = mybox1.volume(); 33 | System.out.println("Volume is " + vol); 34 | 35 | // get volume of second box 36 | vol = mybox2.volume(); 37 | System.out.println("Volume is " + vol); 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-06/src/BoxDemo7.java: -------------------------------------------------------------------------------- 1 | /* Here, Box uses a parameterized constructor to 2 | initialize the dimensions of a box. 3 | */ 4 | class Box { 5 | double width; 6 | double height; 7 | double depth; 8 | 9 | // This is the constructor for Box. 10 | Box(double w, double h, double d) { 11 | width = w; 12 | height = h; 13 | depth = d; 14 | } 15 | 16 | // compute and return volume 17 | double volume() { 18 | return width * height * depth; 19 | } 20 | } 21 | 22 | class BoxDemo7 { 23 | public static void main(String[] args) { 24 | // declare, allocate, and initialize Box objects 25 | Box mybox1 = new Box(10, 20, 15); 26 | Box mybox2 = new Box(3, 6, 9); 27 | 28 | double vol; 29 | 30 | // get volume of first box 31 | vol = mybox1.volume(); 32 | System.out.println("Volume is " + vol); 33 | 34 | // get volume of second box 35 | vol = mybox2.volume(); 36 | System.out.println("Volume is " + vol); 37 | } 38 | } -------------------------------------------------------------------------------- /Chapter-06/src/Stack.java: -------------------------------------------------------------------------------- 1 | // This class defines an integer stack that can hold 10 values. 2 | class Stack { 3 | int[] stck = new int[10]; 4 | int tos; 5 | 6 | // Initialize top-of-stack 7 | Stack() { 8 | tos = -1; 9 | } 10 | 11 | // Push an item onto the stack 12 | void push(int item) { 13 | if (tos == 9) 14 | System.out.println("Stack is full."); 15 | else 16 | stck[++tos] = item; 17 | } 18 | 19 | // Pop an item from the stack 20 | int pop() { 21 | if (tos < 0) { 22 | System.out.println("Stack underflow."); 23 | return 0; 24 | } else 25 | return stck[tos--]; 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter-06/src/TestStack.java: -------------------------------------------------------------------------------- 1 | class TestStack { 2 | public static void main(String[] args) { 3 | Stack mystack1 = new Stack(); 4 | Stack mystack2 = new Stack(); 5 | 6 | // push some numbers onto the stack 7 | for (int i = 0; i < 10; i++) mystack1.push(i); 8 | for (int i = 10; i < 20; i++) mystack2.push(i); 9 | 10 | // pop those numbers off the stack 11 | System.out.println("Stack in mystack1:"); 12 | for (int i = 0; i < 10; i++) 13 | System.out.println(mystack1.pop()); 14 | 15 | System.out.println("Stack in mystack2:"); 16 | for (int i = 0; i < 10; i++) 17 | System.out.println(mystack2.pop()); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-07/src/AccessTest.java: -------------------------------------------------------------------------------- 1 | /* This program demonstrates the difference between 2 | public and private. 3 | */ 4 | class Test { 5 | public int b; // public access 6 | int a; // default access 7 | private int c; // private access 8 | 9 | // methods to access c 10 | void setc(int i) { // set c's value 11 | c = i; 12 | } 13 | 14 | int getc() { // get c's value 15 | return c; 16 | } 17 | } 18 | 19 | class AccessTest { 20 | public static void main(String[] args) { 21 | Test ob = new Test(); 22 | 23 | // These are OK, a and b may be accessed directly 24 | ob.a = 10; 25 | ob.b = 20; 26 | 27 | // This is not OK and will cause an error 28 | // ob.c = 100; // Error! 29 | 30 | // You must access c through its methods 31 | ob.setc(100); // OK 32 | 33 | System.out.println("a, b, and c: " + ob.a + " " + 34 | ob.b + " " + ob.getc()); 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-07/src/Box.java: -------------------------------------------------------------------------------- 1 | class Box { 2 | double width; 3 | double height; 4 | double depth; 5 | 6 | // This is the constructor for Box. 7 | Box(double w, double h, double d) { 8 | width = w; 9 | height = h; 10 | depth = d; 11 | } 12 | 13 | // compute and return volume 14 | double volume() { 15 | return width * height * depth; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-07/src/CallByValue.java: -------------------------------------------------------------------------------- 1 | // Simple Types are passed by value. 2 | class Test { 3 | void meth(int i, int j) { 4 | i *= 2; 5 | j /= 2; 6 | } 7 | } 8 | 9 | class CallByValue { 10 | public static void main(String[] args) { 11 | Test ob = new Test(); 12 | int a = 15, b = 20; 13 | 14 | System.out.println("a and b before call: " + 15 | a + " " + b); 16 | 17 | ob.meth(a, b); 18 | 19 | System.out.println("a and b after call: " + 20 | a + " " + b); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-07/src/CommandLine.java: -------------------------------------------------------------------------------- 1 | // Display all command line arguments. 2 | class CommandLine { 3 | public static void main(String[] args) { 4 | for (int i = 0; i < args.length; i++) 5 | System.out.println("args[" + i + "]: " + 6 | args[i]); 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter-07/src/FinalKeyExample.java: -------------------------------------------------------------------------------- 1 | class FinalKeyExample { 2 | final int FILE_NEW = 1; 3 | final int FILE_OPEN = 2; 4 | final int FILE_SAVE = 3; 5 | final int FILE_SAVEAS = 4; 6 | final int FILE_QUIT = 5; 7 | } 8 | -------------------------------------------------------------------------------- /Chapter-07/src/InnerClassDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate an inner class. 2 | class Outer { 3 | int outer_x = 100; 4 | 5 | void test() { 6 | Inner inner = new Inner(); 7 | inner.display(); 8 | } 9 | 10 | // this is an innner class 11 | class Inner { 12 | void display() { 13 | System.out.println("display: outer_x = " + outer_x); 14 | } 15 | } 16 | } 17 | 18 | 19 | class InnerClassDemo { 20 | public static void main(String[] args) { 21 | Outer outer = new Outer(); 22 | outer.test(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter-07/src/InnerClassDemo2.java: -------------------------------------------------------------------------------- 1 | // This program will not compile. 2 | class Outer { 3 | int outer_x = 100; 4 | 5 | void test() { 6 | Inner inner = new Inner(); 7 | inner.display(); 8 | } 9 | 10 | void showy() { 11 | System.out.println(y); // error, y not known here! 12 | } 13 | 14 | // this is an innner class 15 | class Inner { 16 | int y = 10; // y is local to Inner 17 | 18 | void display() { 19 | System.out.println("display: outer_x = " + outer_x); 20 | } 21 | } 22 | } 23 | 24 | class InnerClassDemo { 25 | public static void main(String[] args) { 26 | Outer outer = new Outer(); 27 | outer.test(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter-07/src/InnerClassDemo3.java: -------------------------------------------------------------------------------- 1 | // Define an inner class within a for loop. 2 | class Outer { 3 | int outer_x = 100; 4 | 5 | void test() { 6 | for (int i = 0; i < 10; i++) { 7 | class Inner { 8 | void display() { 9 | System.out.println("display: outer_x = " + outer_x); 10 | } 11 | } 12 | Inner inner = new Inner(); 13 | inner.display(); 14 | } 15 | } 16 | } 17 | 18 | class InnerClassDemo { 19 | public static void main(String[] args) { 20 | Outer outer = new Outer(); 21 | outer.test(); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter-07/src/Length.java: -------------------------------------------------------------------------------- 1 | // This program demonstrates the length array member. 2 | class Length { 3 | public static void main(String[] args) { 4 | int[] a1 = new int[10]; 5 | int[] a2 = {3, 5, 7, 1, 8, 99, 44, -10}; 6 | int[] a3 = {4, 3, 2, 1}; 7 | 8 | System.out.println("length of a1 is " + a1.length); 9 | System.out.println("length of a2 is " + a2.length); 10 | System.out.println("length of a3 is " + a3.length); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-07/src/OverloadDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate method overloading. 2 | class OverloadDemo { 3 | void test() { 4 | System.out.println("No parameters"); 5 | } 6 | 7 | // Overload test for one integer parameter. 8 | void test(int a) { 9 | System.out.println("a: " + a); 10 | } 11 | 12 | // Overload test for two integer parameters. 13 | void test(int a, int b) { 14 | System.out.println("a and b: " + a + " " + b); 15 | } 16 | 17 | // overload test for a double parameter 18 | double test(double a) { 19 | System.out.println("double a: " + a); 20 | return a * a; 21 | } 22 | } 23 | 24 | class Overload { 25 | public static void main(String[] args) { 26 | OverloadDemo ob = new OverloadDemo(); 27 | double result; 28 | 29 | // call all versions of test() 30 | ob.test(); 31 | ob.test(10); 32 | ob.test(10, 20); 33 | result = ob.test(123.25); 34 | System.out.println("Result of ob.test(123.25): " + result); 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-07/src/OverloadDemo2.java: -------------------------------------------------------------------------------- 1 | // Automatic type conversions apply to overloading. 2 | class OverloadDemo { 3 | void test() { 4 | System.out.println("No parameters"); 5 | } 6 | 7 | // Overload test for two integer parameters. 8 | void test(int a, int b) { 9 | System.out.println("a and b: " + a + " " + b); 10 | } 11 | 12 | // overload test for a double parameter and return type 13 | void test(double a) { 14 | System.out.println("Inside test(double) a: " + a); 15 | } 16 | } 17 | 18 | class Overload { 19 | public static void main(String[] args) { 20 | OverloadDemo ob = new OverloadDemo(); 21 | int i = 88; 22 | 23 | ob.test(); 24 | ob.test(10, 20); 25 | 26 | ob.test(i); // this will invoke test(double) 27 | ob.test(123.2); // this will invoke test(double) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter-07/src/PassArray.java: -------------------------------------------------------------------------------- 1 | // Use an array to pass a variable number of 2 | // arguments to a method. 3 | class PassArray { 4 | static void vaTest(int[] v) { 5 | System.out.print("Number of args: " + v.length + 6 | " Contents: "); 7 | 8 | for (int x : v) 9 | System.out.print(x + " "); 10 | 11 | System.out.println(); 12 | } 13 | 14 | public static void main(String[] args) { 15 | // Notice how an array must be created to 16 | // hold the arguments. 17 | int[] n1 = {10}; 18 | int[] n2 = {1, 2, 3}; 19 | int[] n3 = {}; 20 | 21 | vaTest(n1); // 1 arg 22 | vaTest(n2); // 3 args 23 | vaTest(n3); // no args 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter-07/src/PassOb.java: -------------------------------------------------------------------------------- 1 | // Objects may be passed to methods. 2 | class Test { 3 | int a, b; 4 | 5 | Test(int i, int j) { 6 | a = i; 7 | b = j; 8 | } 9 | 10 | // return true if o is equal to the invoking object 11 | boolean equalTo(Test o) { 12 | if (o.a == a && o.b == b) return true; 13 | else return false; 14 | } 15 | } 16 | 17 | class PassOb { 18 | public static void main(String[] args) { 19 | Test ob1 = new Test(100, 22); 20 | Test ob2 = new Test(100, 22); 21 | Test ob3 = new Test(-1, -1); 22 | 23 | System.out.println("ob1 == ob2: " + ob1.equalTo(ob2)); 24 | 25 | System.out.println("ob1 == ob3: " + ob1.equalTo(ob3)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter-07/src/PassObjRef.java: -------------------------------------------------------------------------------- 1 | // Objects are passed through their references. 2 | 3 | class Test { 4 | int a, b; 5 | 6 | Test(int i, int j) { 7 | a = i; 8 | b = j; 9 | } 10 | 11 | // pass an object 12 | void meth(Test o) { 13 | o.a *= 2; 14 | o.b /= 2; 15 | } 16 | } 17 | 18 | class PassObjRef { 19 | public static void main(String[] args) { 20 | Test ob = new Test(15, 20); 21 | 22 | System.out.println("ob.a and ob.b before call: " + 23 | ob.a + " " + ob.b); 24 | 25 | ob.meth(ob); 26 | 27 | System.out.println("ob.a and ob.b after call: " + 28 | ob.a + " " + ob.b); 29 | } 30 | } -------------------------------------------------------------------------------- /Chapter-07/src/Recursion.java: -------------------------------------------------------------------------------- 1 | // A simple example of recursion. 2 | class Factorial { 3 | // this is a recusive function 4 | int fact(int n) { 5 | int result; 6 | 7 | if (n == 1) return 1; 8 | result = fact(n - 1) * n; 9 | return result; 10 | } 11 | } 12 | 13 | class Recursion { 14 | public static void main(String[] args) { 15 | Factorial f = new Factorial(); 16 | 17 | System.out.println("Factorial of 3 is " + f.fact(3)); 18 | System.out.println("Factorial of 4 is " + f.fact(4)); 19 | System.out.println("Factorial of 5 is " + f.fact(5)); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-07/src/Recursion2.java: -------------------------------------------------------------------------------- 1 | // Another example that uses recursion. 2 | 3 | class RecTest { 4 | int[] values; 5 | 6 | RecTest(int i) { 7 | values = new int[i]; 8 | } 9 | 10 | // display arrary -- recursively 11 | void printArray(int i) { 12 | if (i == 0) return; 13 | else printArray(i - 1); 14 | System.out.println("[" + (i - 1) + "] " + values[i - 1]); 15 | } 16 | } 17 | 18 | 19 | class Recursion2 { 20 | public static void main(String[] args) { 21 | RecTest ob = new RecTest(10); 22 | int i; 23 | 24 | for (i = 0; i < 10; i++) ob.values[i] = i; 25 | 26 | ob.printArray(10); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-07/src/RefVarDemo.java: -------------------------------------------------------------------------------- 1 | // Local variable type inference with a user-defined class type. 2 | class MyClass { 3 | private int i; 4 | 5 | MyClass(int k) { 6 | i = k; 7 | } 8 | 9 | int geti() { 10 | return i; 11 | } 12 | 13 | void seti(int k) { 14 | if (k >= 0) i = k; 15 | } 16 | } 17 | 18 | class RefVarDemo { 19 | public static void main(String[] args) { 20 | var mc = new MyClass(10); // Notice the use of var here. 21 | 22 | System.out.println("Value of i in mc is " + mc.geti()); 23 | mc.seti(19); 24 | System.out.println("Value of i in mc is now " + mc.geti()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter-07/src/RetOb.java: -------------------------------------------------------------------------------- 1 | // Returning an object. 2 | class Test { 3 | int a; 4 | 5 | Test(int i) { 6 | a = i; 7 | } 8 | 9 | Test incrByTen() { 10 | Test temp = new Test(a + 10); 11 | return temp; 12 | } 13 | } 14 | 15 | class RetOb { 16 | public static void main(String[] args) { 17 | Test ob1 = new Test(2); 18 | Test ob2; 19 | 20 | ob2 = ob1.incrByTen(); 21 | System.out.println("ob1.a: " + ob1.a); 22 | System.out.println("ob2.a: " + ob2.a); 23 | 24 | ob2 = ob2.incrByTen(); 25 | System.out.println("ob2.a after second increase: " 26 | + ob2.a); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-07/src/Stack.java: -------------------------------------------------------------------------------- 1 | // This class defines an integer stack that can hold 10 values. 2 | class Stack { 3 | /* Now, both stck and tos are private. This means 4 | that they cannot be accidentally or maliciously 5 | altered in a way that would be harmful to the stack. 6 | */ 7 | private int[] stck = new int[10]; 8 | private int tos; 9 | 10 | // Initialize top-of-stack 11 | Stack() { 12 | tos = -1; 13 | } 14 | 15 | // Push an item onto the stack 16 | void push(int item) { 17 | if (tos == 9) 18 | System.out.println("Stack is full."); 19 | else 20 | stck[++tos] = item; 21 | } 22 | 23 | // Pop an item from the stack 24 | int pop() { 25 | if (tos < 0) { 26 | System.out.println("Stack underflow."); 27 | return 0; 28 | } else 29 | return stck[tos--]; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter-07/src/StaticByName.java: -------------------------------------------------------------------------------- 1 | class StaticDemo { 2 | static int a = 42; 3 | static int b = 99; 4 | 5 | static void callme() { 6 | System.out.println("a = " + a); 7 | } 8 | } 9 | 10 | 11 | class StaticByName { 12 | public static void main(String[] args) { 13 | StaticDemo.callme(); 14 | System.out.println("b = " + StaticDemo.b); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-07/src/StringDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrating Strings. 2 | class StringDemo { 3 | public static void main(String[] args) { 4 | String strOb1 = "First String"; 5 | String strOb2 = "Second String"; 6 | String strOb3 = strOb1 + " and " + strOb2; 7 | 8 | System.out.println(strOb1); 9 | System.out.println(strOb2); 10 | System.out.println(strOb3); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter-07/src/StringDemo2.java: -------------------------------------------------------------------------------- 1 | // Demonstrating some String methods. 2 | class StringDemo2 { 3 | public static void main(String[] args) { 4 | String strOb1 = "First String"; 5 | String strOb2 = "Second String"; 6 | String strOb3 = strOb1; 7 | 8 | System.out.println("Length of strOb1: " + 9 | strOb1.length()); 10 | 11 | System.out.println("Char at index 3 in strOb1: " + 12 | strOb1.charAt(3)); 13 | 14 | if (strOb1.equals(strOb2)) 15 | System.out.println("strOb1 == strOb2"); 16 | else 17 | System.out.println("strOb1 != strOb2"); 18 | 19 | if (strOb1.equals(strOb3)) 20 | System.out.println("strOb1 == strOb3"); 21 | else 22 | System.out.println("strOb1 != strOb3"); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-07/src/StringDemo3.java: -------------------------------------------------------------------------------- 1 | // Demonstrate String arrays. 2 | class StringDemo3 { 3 | public static void main(String[] args) { 4 | String[] str = {"one", "two", "three"}; 5 | 6 | for (int i = 0; i < str.length; i++) 7 | System.out.println("str[" + i + "]: " + 8 | str[i]); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-07/src/TestStack.java: -------------------------------------------------------------------------------- 1 | class TestStack { 2 | public static void main(String[] args) { 3 | Stack mystack1 = new Stack(); 4 | Stack mystack2 = new Stack(); 5 | 6 | // push some numbers onto the stack 7 | for (int i = 0; i < 10; i++) mystack1.push(i); 8 | for (int i = 10; i < 20; i++) mystack2.push(i); 9 | 10 | // pop those numbers off the stack 11 | System.out.println("Stack in mystack1:"); 12 | for (int i = 0; i < 10; i++) 13 | System.out.println(mystack1.pop()); 14 | 15 | System.out.println("Stack in mystack2:"); 16 | for (int i = 0; i < 10; i++) 17 | System.out.println(mystack2.pop()); 18 | 19 | // these statements are not legal 20 | // mystack1.tos = -2; 21 | // mystack2.stck[3] = 100; 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter-07/src/UseStatic.java: -------------------------------------------------------------------------------- 1 | // Demonstrate static variables, methods, and blocks. 2 | class UseStatic { 3 | static int a = 3; 4 | static int b; 5 | 6 | static { 7 | System.out.println("Static block initialized."); 8 | b = a * 4; 9 | } 10 | 11 | static void meth(int x) { 12 | System.out.println("x = " + x); 13 | System.out.println("a = " + a); 14 | System.out.println("b = " + b); 15 | } 16 | 17 | public static void main(String[] args) { 18 | meth(42); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter-07/src/VarArgs.java: -------------------------------------------------------------------------------- 1 | // Demonstrate variable-length arguments. 2 | class VarArgs { 3 | 4 | // vaTest() now uses a vararg. 5 | static void vaTest(int... v) { 6 | System.out.print("Number of args: " + v.length + 7 | " Contents: "); 8 | 9 | for (int x : v) 10 | System.out.print(x + " "); 11 | 12 | System.out.println(); 13 | } 14 | 15 | public static void main(String[] args) { 16 | 17 | // Notice how vaTest() can be called with a 18 | // variable number of arguments. 19 | vaTest(10); // 1 arg 20 | vaTest(1, 2, 3); // 3 args 21 | vaTest(); // no args 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter-07/src/VarArgs2.java: -------------------------------------------------------------------------------- 1 | // Use varargs with standard arguments. 2 | class VarArgs2 { 3 | 4 | // Here, msg is a normal parameter and v is a 5 | // varargs parameter. 6 | static void vaTest(String msg, int... v) { 7 | System.out.print(msg + v.length + 8 | " Contents: "); 9 | 10 | for (int x : v) 11 | System.out.print(x + " "); 12 | 13 | System.out.println(); 14 | } 15 | 16 | public static void main(String[] args) { 17 | vaTest("One vararg: ", 10); 18 | vaTest("Three varargs: ", 1, 2, 3); 19 | vaTest("No varargs: "); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-07/src/VarArgs4.java: -------------------------------------------------------------------------------- 1 | // Varargs, overloading, and ambiguity. 2 | // 3 | // This program contains an error and will 4 | // not compile! 5 | class VarArgs4 { 6 | 7 | static void vaTest(int... v) { 8 | System.out.print("vaTest(Integer ...): " + 9 | "Number of args: " + v.length + 10 | " Contents: "); 11 | 12 | for (int x : v) 13 | System.out.print(x + " "); 14 | 15 | System.out.println(); 16 | } 17 | 18 | static void vaTest(boolean... v) { 19 | System.out.print("vaTest(boolean ...) " + 20 | "Number of args: " + v.length + 21 | " Contents: "); 22 | 23 | for (boolean x : v) 24 | System.out.print(x + " "); 25 | 26 | System.out.println(); 27 | } 28 | 29 | 30 | public static void main(String[] args) { 31 | vaTest(1, 2, 3); // OK 32 | vaTest(true, false, false); // OK 33 | 34 | vaTest(); // Error: Ambiguous! 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-08/src/AbstractDemo.java: -------------------------------------------------------------------------------- 1 | // A Simple demonstration of abstract. 2 | abstract class A { 3 | abstract void callme(); 4 | 5 | // concrete methods are still allowed in abstract classes 6 | void callmetoo() { 7 | System.out.println("This is a concrete method."); 8 | } 9 | } 10 | 11 | class B extends A { 12 | void callme() { 13 | System.out.println("B's implementation of callme."); 14 | } 15 | } 16 | 17 | 18 | class AbstractDemo { 19 | public static void main(String[] args) { 20 | B b = new B(); 21 | 22 | b.callme(); 23 | b.callmetoo(); 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter-08/src/Access.java: -------------------------------------------------------------------------------- 1 | /* In a class hierarchy, private members remain 2 | private to their class. 3 | 4 | This program contains an error and will not 5 | compile. 6 | */ 7 | 8 | // Create a superclass. 9 | class A { 10 | int i; // default access 11 | private int j; // private to A 12 | 13 | void setij(int x, int y) { 14 | i = x; 15 | j = y; 16 | } 17 | } 18 | 19 | // A's j is not accessible here. 20 | class B extends A { 21 | int total; 22 | 23 | void sum() { 24 | total = i + j; // ERROR, j is not accessible here 25 | } 26 | } 27 | 28 | class Access { 29 | public static void main(String[] args) { 30 | B subOb = new B(); 31 | 32 | subOb.setij(10, 12); 33 | 34 | subOb.sum(); 35 | System.out.println("Total is " + subOb.total); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter-08/src/B.java: -------------------------------------------------------------------------------- 1 | class B extends A { 2 | int k; 3 | 4 | B(int a, int b, int c) { 5 | super(a, b); 6 | k = c; 7 | } 8 | 9 | void show() { 10 | super.show(); // this calls A's show() 11 | System.out.println("k: " + k); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter-08/src/BoxWeight.java: -------------------------------------------------------------------------------- 1 | // BoxWeight now uses super to initialize its Box attributes. 2 | class BoxWeight extends Box { 3 | double weight; // weight of box 4 | 5 | // initialize width, height, and depth using super() 6 | BoxWeight(double w, double h, double d, double m) { 7 | super(w, h, d); // call superclass constructor 8 | weight = m; 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-08/src/BoxWeightCopyConstructorExample.java: -------------------------------------------------------------------------------- 1 | class BoxWeight extends Box { 2 | double weight; // weight of box 3 | 4 | // construct clone of an object 5 | BoxWeight(BoxWeight ob) { // pass object to constructor 6 | super(ob); 7 | weight = ob.weight; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-08/src/CallingCons.java: -------------------------------------------------------------------------------- 1 | // Demonstrate when constructors are called. 2 | 3 | // Create a super class. 4 | class A { 5 | A() { 6 | System.out.println("Inside A's constructor."); 7 | } 8 | } 9 | 10 | // Create a subclass by extending class A. 11 | class B extends A { 12 | B() { 13 | System.out.println("Inside B's constructor."); 14 | } 15 | } 16 | 17 | // Create another subclass by extending B. 18 | class C extends B { 19 | C() { 20 | System.out.println("Inside C's constructor."); 21 | } 22 | } 23 | 24 | 25 | class CallingCons { 26 | public static void main(String[] args) { 27 | C c = new C(); 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter-08/src/ColorBox.java: -------------------------------------------------------------------------------- 1 | // Here, Box is extended to include color. 2 | class ColorBox extends Box { 3 | int color; // color of box 4 | 5 | ColorBox(double w, double h, double d, int c) { 6 | width = w; 7 | height = h; 8 | depth = d; 9 | color = c; 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-08/src/Dispatch.java: -------------------------------------------------------------------------------- 1 | // Dynamic Method Dispatch 2 | class A { 3 | void callme() { 4 | System.out.println("Inside A's callme method"); 5 | } 6 | } 7 | 8 | class B extends A { 9 | // override callme() 10 | void callme() { 11 | System.out.println("Inside B's callme method"); 12 | } 13 | } 14 | 15 | class C extends A { 16 | // override callme() 17 | void callme() { 18 | System.out.println("Inside C's callme method"); 19 | } 20 | } 21 | 22 | class Dispatch { 23 | public static void main(String[] args) { 24 | A a = new A(); // object of type A 25 | B b = new B(); // object of type B 26 | C c = new C(); // object of type C 27 | A r; // obtain a reference of type A 28 | 29 | r = a; // r refers to an A object 30 | r.callme(); // calls A's version of callme 31 | 32 | r = b; // r refers to a B object 33 | r.callme(); // calls B's version of callme 34 | 35 | r = c; // r refers to a C object 36 | r.callme(); // calls C's version of callme 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter-08/src/ExtendingFinalClassExample.java: -------------------------------------------------------------------------------- 1 | final class A { 2 | // ... 3 | } 4 | 5 | // The following class is illegal. 6 | class B extends A { // ERROR! Can't subclass A 7 | // ... 8 | } -------------------------------------------------------------------------------- /Chapter-08/src/FinalMethodOverrideExample.java: -------------------------------------------------------------------------------- 1 | class A { 2 | final void meth() { 3 | System.out.println("This is a final method."); 4 | } 5 | } 6 | 7 | class B extends A { 8 | void meth() { // ERROR! Can't override. 9 | System.out.println("Illegal!"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter-08/src/Override.java: -------------------------------------------------------------------------------- 1 | // Method overriding. 2 | class A { 3 | int i, j; 4 | 5 | A(int a, int b) { 6 | i = a; 7 | j = b; 8 | } 9 | 10 | // display i and j 11 | void show() { 12 | System.out.println("i and j: " + i + " " + j); 13 | } 14 | } 15 | 16 | class B extends A { 17 | int k; 18 | 19 | B(int a, int b, int c) { 20 | super(a, b); 21 | k = c; 22 | } 23 | 24 | // display k -- this overrides show() in A 25 | void show() { 26 | System.out.println("k: " + k); 27 | } 28 | } 29 | 30 | 31 | class Override { 32 | public static void main(String[] args) { 33 | B subOb = new B(1, 2, 3); 34 | 35 | subOb.show(); // this calls show() in B 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter-08/src/Override2.java: -------------------------------------------------------------------------------- 1 | // Methods with differing type signatures are overloaded -- not overridden. 2 | class A { 3 | int i, j; 4 | 5 | A(int a, int b) { 6 | i = a; 7 | j = b; 8 | } 9 | 10 | // display i and j 11 | void show() { 12 | System.out.println("i and j: " + i + " " + j); 13 | } 14 | } 15 | 16 | // Create a subclass by extending class A. 17 | class B extends A { 18 | int k; 19 | 20 | B(int a, int b, int c) { 21 | super(a, b); 22 | k = c; 23 | } 24 | 25 | // overload show() 26 | void show(String msg) { 27 | System.out.println(msg + k); 28 | } 29 | } 30 | 31 | 32 | class Override2 { 33 | public static void main(String[] args) { 34 | B subOb = new B(1, 2, 3); 35 | 36 | subOb.show("This is k: "); // this calls show() in B 37 | subOb.show(); // this calls show() in A 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-08/src/RefDemo.java: -------------------------------------------------------------------------------- 1 | class RefDemo { 2 | public static void main(String[] args) { 3 | BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); 4 | Box plainbox = new Box(); 5 | double vol; 6 | 7 | vol = weightbox.volume(); 8 | System.out.println("Volume of weightbox is " + vol); 9 | System.out.println("Weight of weightbox is " + weightbox.weight); 10 | System.out.println(); 11 | 12 | // assign BoxWeight reference to Box reference 13 | plainbox = weightbox; 14 | 15 | vol = plainbox.volume(); // OK, volume() defined in Box 16 | System.out.println("Volume of plainbox is " + vol); 17 | 18 | /* The following statement is invalid because plainbox 19 | does not define a weight member. */ 20 | // System.out.println("Weight of plainbox is " + plainbox.weight); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-08/src/UseSuper.java: -------------------------------------------------------------------------------- 1 | // Using super to overcome name hiding. 2 | class A { 3 | int i; 4 | } 5 | 6 | // Create a subclass by extending class A. 7 | class B extends A { 8 | int i; // this i hides the i in A 9 | 10 | B(int a, int b) { 11 | super.i = a; // i in A 12 | i = b; // i in B 13 | } 14 | 15 | void show() { 16 | System.out.println("i in superclass: " + super.i); 17 | System.out.println("i in subclass: " + i); 18 | } 19 | } 20 | 21 | 22 | class UseSuper { 23 | public static void main(String[] args) { 24 | B subOb = new B(1, 2); 25 | 26 | subOb.show(); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-09/src/AnotherClient.java: -------------------------------------------------------------------------------- 1 | // Another implementation of Callback. 2 | class AnotherClient implements Callback { 3 | // Implement Callback's interface 4 | public void callback(int p) { 5 | System.out.println("Another version of callback"); 6 | System.out.println("p squared is " + (p * p)); 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter-09/src/Callback.java: -------------------------------------------------------------------------------- 1 | interface Callback { 2 | void callback(int param); 3 | } -------------------------------------------------------------------------------- /Chapter-09/src/Client.java: -------------------------------------------------------------------------------- 1 | class Client implements Callback { 2 | // Implement Callback's interface 3 | public void callback(int p) { 4 | System.out.println("callback called with " + p); 5 | } 6 | } -------------------------------------------------------------------------------- /Chapter-09/src/Client2.java: -------------------------------------------------------------------------------- 1 | class Client2 implements Callback { 2 | // Implement Callback's interface 3 | public void callback(int p) { 4 | System.out.println("callback called with " + p); 5 | } 6 | 7 | void nonIfaceMeth() { 8 | System.out.println("Classes that implement interfaces " + 9 | "may also define other members, too."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter-09/src/DefaultMethodDemo.java: -------------------------------------------------------------------------------- 1 | // Use the default method. 2 | class DefaultMethodDemo { 3 | public static void main(String[] args) { 4 | 5 | MyIFImp obj = new MyIFImp(); 6 | 7 | // Can call getNumber(), because it is explicitly 8 | // implemented by MyIFImp: 9 | System.out.println(obj.getNumber()); 10 | 11 | // Can also call getString(), because of default 12 | // implementation: 13 | System.out.println(obj.getString()); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-09/src/ExtendingClassWithImport.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | class MyDate extends Date { 4 | } 5 | 6 | -------------------------------------------------------------------------------- /Chapter-09/src/ExtendingClassWithoutImport.java: -------------------------------------------------------------------------------- 1 | class MyDate extends java.util.Date { 2 | } 3 | 4 | -------------------------------------------------------------------------------- /Chapter-09/src/IFExtend.java: -------------------------------------------------------------------------------- 1 | // One interface an extend another. 2 | interface A { 3 | void meth1(); 4 | 5 | void meth2(); 6 | } 7 | 8 | // B now includes meth1() and meth2() -- it adds meth3(). 9 | interface B extends A { 10 | void meth3(); 11 | } 12 | 13 | // This class must implement all of A and B 14 | class MyClass implements B { 15 | public void meth1() { 16 | System.out.println("Implement meth1()."); 17 | } 18 | 19 | public void meth2() { 20 | System.out.println("Implement meth2()."); 21 | } 22 | 23 | public void meth3() { 24 | System.out.println("Implement meth3()."); 25 | } 26 | } 27 | 28 | class IFExtend { 29 | public static void main(String arg[]) { 30 | MyClass ob = new MyClass(); 31 | 32 | ob.meth1(); 33 | ob.meth2(); 34 | ob.meth3(); 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-09/src/IFTest3.java: -------------------------------------------------------------------------------- 1 | /* Create an interface variable and 2 | access stacks through it. 3 | */ 4 | class IFTest3 { 5 | public static void main(String[] args) { 6 | IntStack mystack; // create an interface reference variable 7 | DynStack ds = new DynStack(5); 8 | FixedStack fs = new FixedStack(8); 9 | 10 | mystack = ds; // load dynamic stack 11 | // push some numbers onto the stack 12 | for (int i = 0; i < 12; i++) mystack.push(i); 13 | 14 | mystack = fs; // load fixed stack 15 | for (int i = 0; i < 8; i++) mystack.push(i); 16 | 17 | 18 | mystack = ds; 19 | System.out.println("Values in dynamic stack:"); 20 | for (int i = 0; i < 12; i++) 21 | System.out.println(mystack.pop()); 22 | 23 | mystack = fs; 24 | System.out.println("Values in fixed stack:"); 25 | for (int i = 0; i < 8; i++) 26 | System.out.println(mystack.pop()); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-09/src/Incomplete.java: -------------------------------------------------------------------------------- 1 | abstract class Incomplete implements Callback { 2 | int a, b; 3 | 4 | void show() { 5 | System.out.println(a + " " + b); 6 | } 7 | // ... 8 | } -------------------------------------------------------------------------------- /Chapter-09/src/IntStack.java: -------------------------------------------------------------------------------- 1 | // Define an integer stack interface. 2 | interface IntStack { 3 | void push(int item); // store an item 4 | 5 | int pop(); // retrieve an item 6 | } -------------------------------------------------------------------------------- /Chapter-09/src/IntStack2.java: -------------------------------------------------------------------------------- 1 | interface IntStack2 { 2 | void push(int item); // store an item 3 | 4 | int pop(); // retrieve an item 5 | 6 | // Because clear( ) has a default, it need not be 7 | // implemented by a preexisting class that uses IntStack. 8 | default void clear() { 9 | System.out.println("clear() not implemented."); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-09/src/MyIF.java: -------------------------------------------------------------------------------- 1 | public interface MyIF { 2 | // This is a "normal" interface method declaration. 3 | // It does NOT define a default implementation. 4 | int getNumber(); 5 | 6 | // This is a default method. Notice that it provides 7 | // a default implementation. 8 | default String getString() { 9 | return "Default String"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter-09/src/MyIF2.java: -------------------------------------------------------------------------------- 1 | public interface MyIF2 { 2 | // This is a static interface method. 3 | static int getDefaultNumber() { 4 | return 0; 5 | } 6 | 7 | // This is a "normal" interface method declaration. 8 | // It does NOT define a default implementation. 9 | int getNumber(); 10 | 11 | // This is a default method. Notice that it provides 12 | // a default implementation. 13 | default String getString() { 14 | return "Default String"; 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-09/src/MyIFImp.java: -------------------------------------------------------------------------------- 1 | // Implement MyIF. 2 | class MyIFImp implements MyIF { 3 | // Only getNumber() defined by MyIF needs to be implemented. 4 | // getString() can be allowed to default. 5 | public int getNumber() { 6 | return 100; 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter-09/src/MyIFImp2.java: -------------------------------------------------------------------------------- 1 | class MyIFImp2 implements MyIF { 2 | // Here, implementations for both getNumber( ) and getString( ) are provided. 3 | public int getNumber() { 4 | return 100; 5 | } 6 | 7 | public String getString() { 8 | return "This is a different string."; 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-09/src/NestedIFDemo.java: -------------------------------------------------------------------------------- 1 | // A nested interface example. 2 | 3 | // This class contains a member interface. 4 | class A { 5 | // this is a nested interface 6 | public interface NestedIF { 7 | boolean isNotNegative(int x); 8 | } 9 | } 10 | 11 | // B implements the nested interface. 12 | class B implements A.NestedIF { 13 | public boolean isNotNegative(int x) { 14 | return x < 0 ? false : true; 15 | } 16 | } 17 | 18 | 19 | class NestedIFDemo { 20 | public static void main(String[] args) { 21 | 22 | // use a nested interface reference 23 | A.NestedIF nif = new B(); 24 | 25 | if (nif.isNotNegative(10)) 26 | System.out.println("10 is not negative"); 27 | if (nif.isNotNegative(-12)) 28 | System.out.println("this won't be displayed"); 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Chapter-09/src/TestBalance.java: -------------------------------------------------------------------------------- 1 | import mypack.Balance2; 2 | 3 | class TestBalance { 4 | public static void main(String[] args) { 5 | 6 | /* Because Balance is public, you may use Balance 7 | class and call its constructor. */ 8 | Balance2 test = new Balance2("J. J. Jaspers", 99.88); 9 | 10 | test.show(); // you may also call show() 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-09/src/TestIface.java: -------------------------------------------------------------------------------- 1 | class TestIface { 2 | public static void main(String[] args) { 3 | Callback c = new Client(); 4 | c.callback(42); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Chapter-09/src/TestIface2.java: -------------------------------------------------------------------------------- 1 | class TestIface2 { 2 | public static void main(String[] args) { 3 | Callback c = new Client(); 4 | AnotherClient ob = new AnotherClient(); 5 | 6 | c.callback(42); 7 | 8 | c = ob; // c now refers to AnotherClient object 9 | c.callback(42); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-09/src/mypack/AccountBalance.java: -------------------------------------------------------------------------------- 1 | // A simple package 2 | package mypack; 3 | 4 | 5 | class AccountBalance { 6 | public static void main(String[] args) { 7 | Balance[] current = new Balance[3]; 8 | 9 | current[0] = new Balance("K. J. Fielding", 123.23); 10 | current[1] = new Balance("Will Tell", 157.02); 11 | current[2] = new Balance("Tom Jackson", -12.33); 12 | 13 | for (int i = 0; i < 3; i++) current[i].show(); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-09/src/mypack/Balance.java: -------------------------------------------------------------------------------- 1 | package mypack; 2 | 3 | class Balance { 4 | String name; 5 | double bal; 6 | 7 | Balance(String n, double b) { 8 | name = n; 9 | bal = b; 10 | } 11 | 12 | void show() { 13 | if (bal < 0) 14 | System.out.print("-->> "); 15 | System.out.println(name + ": $" + bal); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-09/src/mypack/Balance2.java: -------------------------------------------------------------------------------- 1 | package mypack; 2 | 3 | /* Now, the Balance class, its constructor, and its 4 | show() method are public. This means that they can 5 | be used by non-subclass code outside their package. 6 | */ 7 | public class Balance2 { 8 | String name; 9 | double bal; 10 | 11 | public Balance2(String n, double b) { 12 | name = n; 13 | bal = b; 14 | } 15 | 16 | public void show() { 17 | if (bal < 0) 18 | System.out.print("-->> "); 19 | System.out.println(name + ": $" + bal); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-09/src/p1/Demo.java: -------------------------------------------------------------------------------- 1 | // Demo package p1. 2 | package p1; 3 | 4 | // Instantiate the various classes in p1. 5 | public class Demo { 6 | public static void main(String[] args) { 7 | Protection ob1 = new Protection(); 8 | Derived ob2 = new Derived(); 9 | SamePackage ob3 = new SamePackage(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter-09/src/p1/Derived.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | 3 | class Derived extends Protection { 4 | Derived() { 5 | System.out.println("derived constructor"); 6 | System.out.println("n = " + n); 7 | 8 | // class only 9 | // System.out.println("n_pri = " + n_pri); 10 | 11 | System.out.println("n_pro = " + n_pro); 12 | System.out.println("n_pub = " + n_pub); 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter-09/src/p1/Protection.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | 3 | public class Protection { 4 | public int n_pub = 4; 5 | protected int n_pro = 3; 6 | int n = 1; 7 | private int n_pri = 2; 8 | 9 | public Protection() { 10 | System.out.println("base constructor"); 11 | System.out.println("n = " + n); 12 | System.out.println("n_pri = " + n_pri); 13 | System.out.println("n_pro = " + n_pro); 14 | System.out.println("n_pub = " + n_pub); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-09/src/p1/SamePackage.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | 3 | 4 | class SamePackage { 5 | SamePackage() { 6 | Protection p = new Protection(); 7 | System.out.println("same package constructor"); 8 | System.out.println("n = " + p.n); 9 | 10 | // class only 11 | // System.out.println("n_pri = " + p.n_pri); 12 | 13 | System.out.println("n_pro = " + p.n_pro); 14 | System.out.println("n_pub = " + p.n_pub); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-09/src/p2/Demo.java: -------------------------------------------------------------------------------- 1 | // Demo package p2. 2 | package p2; 3 | 4 | // Instantiate the various classes in p2. 5 | public class Demo { 6 | public static void main(String[] args) { 7 | Protection2 ob1 = new Protection2(); 8 | OtherPackage ob2 = new OtherPackage(); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-09/src/p2/OtherPackage.java: -------------------------------------------------------------------------------- 1 | package p2; 2 | 3 | class OtherPackage { 4 | OtherPackage() { 5 | p1.Protection p = new p1.Protection(); 6 | System.out.println("other package constructor"); 7 | 8 | // class or package only 9 | // System.out.println("n = " + p.n); 10 | 11 | // class only 12 | // System.out.println("n_pri = " + p.n_pri); 13 | 14 | // class, subclass or package only 15 | // System.out.println("n_pro = " + p.n_pro); 16 | 17 | System.out.println("n_pub = " + p.n_pub); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-09/src/p2/Protection2.java: -------------------------------------------------------------------------------- 1 | package p2; 2 | 3 | class Protection2 extends p1.Protection { 4 | Protection2() { 5 | System.out.println("derived other package constructor"); 6 | 7 | // class or package only 8 | // System.out.println("n = " + n); 9 | 10 | // class only 11 | // System.out.println("n_pri = " + n_pri); 12 | 13 | System.out.println("n_pro = " + n_pro); 14 | System.out.println("n_pub = " + n_pub); 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /Chapter-10/src/ChainExcDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate exception chaining. 2 | class ChainExcDemo { 3 | static void demoproc() { 4 | // create an exception 5 | NullPointerException e = 6 | new NullPointerException("top layer"); 7 | 8 | // add a cause 9 | e.initCause(new ArithmeticException("cause")); 10 | 11 | throw e; 12 | } 13 | 14 | public static void main(String[] args) { 15 | try { 16 | demoproc(); 17 | } catch (NullPointerException e) { 18 | // display top level exception 19 | System.out.println("Caught: " + e); 20 | 21 | // display cause exception 22 | System.out.println("Original cause: " + 23 | e.getCause()); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Chapter-10/src/Exc0.java: -------------------------------------------------------------------------------- 1 | class Exc0 { 2 | public static void main(String[] args) { 3 | int d = 0; 4 | int a = 42 / d; 5 | } 6 | } -------------------------------------------------------------------------------- /Chapter-10/src/Exc1.java: -------------------------------------------------------------------------------- 1 | class Exc1 { 2 | static void subroutine() { 3 | int d = 0; 4 | int a = 10 / d; 5 | } 6 | 7 | public static void main(String[] args) { 8 | Exc1.subroutine(); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-10/src/Exc2.java: -------------------------------------------------------------------------------- 1 | class Exc2 { 2 | public static void main(String[] args) { 3 | int d, a; 4 | 5 | try { // monitor a block of code. 6 | d = 0; 7 | a = 42 / d; 8 | System.out.println("This will not be printed."); 9 | } catch (ArithmeticException e) { // catch divide-by-zero error 10 | System.out.println("Division by zero."); 11 | } 12 | System.out.println("After catch statement."); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter-10/src/FinallyDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate finally. 2 | class FinallyDemo { 3 | // Throw an exception out of the method. 4 | static void procA() { 5 | try { 6 | System.out.println("inside procA"); 7 | throw new RuntimeException("demo"); 8 | } finally { 9 | System.out.println("procA's finally"); 10 | } 11 | } 12 | 13 | // Return from within a try block. 14 | static void procB() { 15 | try { 16 | System.out.println("inside procB"); 17 | return; 18 | } finally { 19 | System.out.println("procB's finally"); 20 | } 21 | } 22 | 23 | // Execute a try block normally. 24 | static void procC() { 25 | try { 26 | System.out.println("inside procC"); 27 | } finally { 28 | System.out.println("procC's finally"); 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | try { 34 | procA(); 35 | } catch (Exception e) { 36 | System.out.println("Exception caught"); 37 | } 38 | procB(); 39 | procC(); 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter-10/src/HandleError.java: -------------------------------------------------------------------------------- 1 | // Handle an exception and move on. 2 | 3 | import java.util.Random; 4 | 5 | class HandleError { 6 | public static void main(String[] args) { 7 | int a = 0, b = 0, c = 0; 8 | Random r = new Random(); 9 | 10 | for (int i = 0; i < 32000; i++) { 11 | try { 12 | b = r.nextInt(); 13 | c = r.nextInt(); 14 | a = 12345 / (b / c); 15 | } catch (ArithmeticException e) { 16 | System.out.println("Division by zero."); 17 | a = 0; // set a to zero and continue 18 | } 19 | System.out.println("a: " + a); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-10/src/MultiCatch.java: -------------------------------------------------------------------------------- 1 | // Demonstrate JDK 7's multi-catch feature. 2 | class MultiCatch { 3 | public static void main(String[] args) { 4 | int a = 10, b = 0; 5 | int[] vals = {1, 2, 3}; 6 | 7 | try { 8 | int result = a / b; // generate an ArithmeticException 9 | 10 | // vals[10] = 19; // generate an ArrayIndexOutOfBoundsException 11 | 12 | // This catch clause catches both exceptions. 13 | } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { 14 | System.out.println("Exception caught: " + e); 15 | } 16 | 17 | System.out.println("After multi-catch."); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-10/src/MultipleCatches.java: -------------------------------------------------------------------------------- 1 | // Demonstrate multiple catch statements. 2 | class MultipleCatches { 3 | public static void main(String[] args) { 4 | try { 5 | int a = args.length; 6 | System.out.println("a = " + a); 7 | int b = 42 / a; 8 | int[] c = {1}; 9 | c[42] = 99; 10 | } catch (ArithmeticException e) { 11 | System.out.println("Divide by 0: " + e); 12 | } catch (ArrayIndexOutOfBoundsException e) { 13 | System.out.println("Array index oob: " + e); 14 | } 15 | System.out.println("After try/catch blocks."); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-10/src/MyException.java: -------------------------------------------------------------------------------- 1 | // This program creates a custom exception type. 2 | class MyException extends Exception { 3 | private int detail; 4 | 5 | MyException(int a) { 6 | detail = a; 7 | } 8 | 9 | public String toString() { 10 | return "MyException[" + detail + "]"; 11 | } 12 | } 13 | 14 | class ExceptionDemo { 15 | static void compute(int a) throws MyException { 16 | System.out.println("Called compute(" + a + ")"); 17 | if (a > 10) 18 | throw new MyException(a); 19 | System.out.println("Normal exit"); 20 | } 21 | 22 | public static void main(String[] args) { 23 | try { 24 | compute(1); 25 | compute(20); 26 | } catch (MyException e) { 27 | System.out.println("Caught " + e); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Chapter-10/src/PrintingException.java: -------------------------------------------------------------------------------- 1 | // Handle an exception and move on. 2 | 3 | import java.util.Random; 4 | 5 | class PrintingException { 6 | public static void main(String[] args) { 7 | int a = 0, b = 0, c = 0; 8 | Random r = new Random(); 9 | 10 | for (int i = 0; i < 32000; i++) { 11 | try { 12 | b = r.nextInt(); 13 | c = r.nextInt(); 14 | a = 12345 / (b / c); 15 | } catch (ArithmeticException e) { 16 | System.out.println("Exception: " + e); 17 | a = 0; // set a to zero and continue 18 | } 19 | System.out.println("a: " + a); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-10/src/SuperSubCatch.java: -------------------------------------------------------------------------------- 1 | /* This program contains an error. 2 | 3 | A subclass must come before its superclass in 4 | a series of catch statements. If not, 5 | unreachable code will be created and a 6 | compile-time error will result. 7 | */ 8 | class SuperSubCatch { 9 | public static void main(String[] args) { 10 | try { 11 | int a = 0; 12 | int b = 42 / a; 13 | } catch (Exception e) { 14 | System.out.println("Generic Exception catch."); 15 | } 16 | /* This catch is never reached because 17 | ArithmeticException is a subclass of Exception. */ catch (ArithmeticException e) { // ERROR - unreachable 18 | System.out.println("This is never reached."); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-10/src/ThrowDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate throw. 2 | class ThrowDemo { 3 | static void demoproc() { 4 | try { 5 | throw new NullPointerException("demo"); 6 | } catch (NullPointerException e) { 7 | System.out.println("Caught inside demoproc."); 8 | throw e; // re-throw the exception 9 | } 10 | } 11 | 12 | public static void main(String[] args) { 13 | try { 14 | demoproc(); 15 | } catch (NullPointerException e) { 16 | System.out.println("Recaught: " + e); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-10/src/ThrowsDemo.java: -------------------------------------------------------------------------------- 1 | // This program contains an error and will not compile. 2 | class ThrowsDemo { 3 | static void throwOne() { 4 | System.out.println("Inside throwOne."); 5 | throw new IllegalAccessException("demo"); 6 | } 7 | 8 | public static void main(String[] args) { 9 | throwOne(); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-10/src/ThrowsDemo2.java: -------------------------------------------------------------------------------- 1 | // This is now correct. 2 | class ThrowsDemo2 { 3 | static void throwOne() throws IllegalAccessException { 4 | System.out.println("Inside throwOne."); 5 | throw new IllegalAccessException("demo"); 6 | } 7 | 8 | public static void main(String[] args) { 9 | try { 10 | throwOne(); 11 | } catch (IllegalAccessException e) { 12 | System.out.println("Caught " + e); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-11/src/CurrentThreadDemo.java: -------------------------------------------------------------------------------- 1 | // Controlling the main Thread. 2 | class CurrentThreadDemo { 3 | public static void main(String[] args) { 4 | Thread t = Thread.currentThread(); 5 | 6 | System.out.println("Current thread: " + t); 7 | 8 | // change the name of the thread 9 | t.setName("My Thread"); 10 | System.out.println("After name change: " + t); 11 | 12 | try { 13 | for (int n = 5; n > 0; n--) { 14 | System.out.println(n); 15 | Thread.sleep(1000); 16 | } 17 | } catch (InterruptedException e) { 18 | System.out.println("Main thread interrupted"); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-12/src/Apple.java: -------------------------------------------------------------------------------- 1 | // Use an enum constructor. 2 | enum Apple { 3 | Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8); 4 | 5 | private int price; // price of each apple 6 | 7 | // Constructor 8 | Apple(int p) { 9 | price = p; 10 | } 11 | 12 | // Overloaded constructor 13 | Apple() { 14 | price = -1; 15 | } 16 | 17 | int getPrice() { 18 | return price; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter-12/src/AutoBox.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a autoboxing/unboxing. 2 | class AutoBox { 3 | public static void main(String[] args) { 4 | 5 | Integer iOb = 100; // autobox an int 6 | 7 | int i = iOb; // auto-unbox 8 | 9 | System.out.println(i + " " + iOb); // displays 100 100 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-12/src/AutoBox2.java: -------------------------------------------------------------------------------- 1 | // Autoboxing/unboxing takes place with 2 | // method parameters and return values. 3 | 4 | class AutoBox2 { 5 | // Take an Integer parameter and return 6 | // an int value; 7 | static int m(Integer v) { 8 | return v; // auto-unbox to int 9 | } 10 | 11 | public static void main(String[] args) { 12 | // Pass an int to m() and assign the return value 13 | // to an Integer. Here, the argument 100 is autoboxed 14 | // into an Integer. The return value is also autoboxed 15 | // into an Integer. 16 | Integer iOb = m(100); 17 | 18 | System.out.println(iOb); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-12/src/AutoBox3.java: -------------------------------------------------------------------------------- 1 | // Autoboxing/unboxing occurs inside expressions. 2 | 3 | class AutoBox3 { 4 | public static void main(String[] args) { 5 | 6 | Integer iOb, iOb2; 7 | int i; 8 | 9 | iOb = 100; 10 | System.out.println("Original value of iOb: " + iOb); 11 | 12 | // The following automatically unboxes iOb, 13 | // performs the increment, and then reboxes 14 | // the result back into iOb. 15 | ++iOb; 16 | System.out.println("After ++iOb: " + iOb); 17 | 18 | // Here, iOb is unboxed, the expression is 19 | // evaluated, and the result is reboxed and 20 | // assigned to iOb2. 21 | iOb2 = iOb + (iOb / 3); 22 | System.out.println("iOb2 after expression: " + iOb2); 23 | 24 | // The same expression is evaluated, but the 25 | // result is not reboxed. 26 | i = iOb + (iOb / 3); 27 | System.out.println("i after expression: " + i); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter-12/src/AutoBox4.java: -------------------------------------------------------------------------------- 1 | class AutoBox4 { 2 | public static void main(String[] args) { 3 | 4 | Integer iOb = 100; 5 | ; 6 | Double dOb = 98.6; 7 | 8 | 9 | dOb = dOb + iOb; 10 | System.out.println("dOb after expression: " + dOb); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter-12/src/AutoBox5.java: -------------------------------------------------------------------------------- 1 | // Autoboxing/unboxing a Boolean and Character. 2 | 3 | class AutoBox5 { 4 | public static void main(String[] args) { 5 | 6 | // Autobox/unbox a boolean. 7 | Boolean b = true; 8 | 9 | // Below, b is auto-unboxed when used in 10 | // a conditional expression, such as an if. 11 | if (b) System.out.println("b is true"); 12 | 13 | // Autobox/unbox a char. 14 | Character ch = 'x'; // box a char 15 | char ch2 = ch; // unbox a char 16 | 17 | System.out.println("ch2 is " + ch2); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter-12/src/EnumDemo2.java: -------------------------------------------------------------------------------- 1 | // Use the built-in enumeration methods. 2 | 3 | // An enumeration of apple varieties. 4 | enum Apple { 5 | Jonathan, GoldenDel, RedDel, Winesap, Cortland 6 | } 7 | 8 | 9 | class EnumDemo2 { 10 | public static void main(String[] args) { 11 | Apple ap; 12 | 13 | System.out.println("Here are all Apple constants"); 14 | 15 | // use values() 16 | Apple[] allapples = Apple.values(); 17 | for (Apple a : allapples) 18 | System.out.println(a); 19 | 20 | System.out.println(); 21 | 22 | // use valueOf() 23 | ap = Apple.valueOf("Winesap"); 24 | System.out.println("ap contains " + ap); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter-12/src/EnumDemo3.java: -------------------------------------------------------------------------------- 1 | // Use an enum constructor, instance variable, and method. 2 | enum Apple { 3 | Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8); 4 | 5 | private int price; // price of each apple 6 | 7 | // Constructor 8 | Apple(int p) { 9 | price = p; 10 | } 11 | 12 | int getPrice() { 13 | return price; 14 | } 15 | } 16 | 17 | 18 | class EnumDemo3 { 19 | public static void main(String[] args) { 20 | Apple ap; 21 | 22 | // Display price of Winesap. 23 | System.out.println("Winesap costs " + 24 | Apple.Winesap.getPrice() + 25 | " cents.\n"); 26 | 27 | // Display all apples and prices. 28 | System.out.println("All apple prices:"); 29 | for (Apple a : Apple.values()) 30 | System.out.println(a + " costs " + a.getPrice() + 31 | " cents."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter-12/src/Marker.java: -------------------------------------------------------------------------------- 1 | import java.lang.annotation.Retention; 2 | import java.lang.annotation.RetentionPolicy; 3 | import java.lang.reflect.Method; 4 | 5 | // A marker annotation. 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @interface MyMarker { 8 | } 9 | 10 | 11 | class Marker { 12 | 13 | // Annotate a method using a marker. 14 | // Notice that no ( ) is needed. 15 | @MyMarker 16 | public static void myMeth() { 17 | Marker ob = new Marker(); 18 | 19 | try { 20 | Method m = ob.getClass().getMethod("myMeth"); 21 | 22 | // Determine if the annotation is present. 23 | if (m.isAnnotationPresent(MyMarker.class)) 24 | System.out.println("MyMarker is present."); 25 | 26 | } catch (NoSuchMethodException exc) { 27 | System.out.println("Method Not Found."); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | myMeth(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter-12/src/Meta1.java: -------------------------------------------------------------------------------- 1 | import java.lang.annotation.Retention; 2 | import java.lang.annotation.RetentionPolicy; 3 | import java.lang.reflect.Method; 4 | 5 | @Retention(RetentionPolicy.RUNTIME) 6 | @interface MyAnno { 7 | String str(); 8 | 9 | int val(); 10 | } 11 | 12 | class Meta { 13 | 14 | // myMeth now has two arguments. 15 | @MyAnno(str = "Two Parameters", val = 19) 16 | public static void myMeth(String str, int i) { 17 | Meta ob = new Meta(); 18 | 19 | try { 20 | Class c = ob.getClass(); 21 | 22 | // Here, the parameter types are specified. 23 | Method m = c.getMethod("myMeth", String.class, int.class); 24 | 25 | MyAnno anno = m.getAnnotation(MyAnno.class); 26 | 27 | System.out.println(anno.str() + " " + anno.val()); 28 | } catch (NoSuchMethodException exc) { 29 | System.out.println("Method Not Found."); 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | myMeth("test", 10); 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-12/src/Meta3.java: -------------------------------------------------------------------------------- 1 | import java.lang.annotation.Retention; 2 | import java.lang.annotation.RetentionPolicy; 3 | import java.lang.reflect.Method; 4 | 5 | // An annotation type declaration that includes defaults. 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @interface MyAnno { 8 | String str() default "Testing"; 9 | 10 | int val() default 9000; 11 | } 12 | 13 | 14 | class Meta3 { 15 | 16 | // Annotate a method using the default values. 17 | @MyAnno() 18 | public static void myMeth() { 19 | Meta3 ob = new Meta3(); 20 | 21 | // Obtain the annotation for this method 22 | // and display the values of the members. 23 | try { 24 | Class c = ob.getClass(); 25 | 26 | Method m = c.getMethod("myMeth"); 27 | 28 | MyAnno anno = m.getAnnotation(MyAnno.class); 29 | 30 | System.out.println(anno.str() + " " + anno.val()); 31 | } catch (NoSuchMethodException exc) { 32 | System.out.println("Method Not Found."); 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | myMeth(); 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-12/src/Single.java: -------------------------------------------------------------------------------- 1 | import java.lang.annotation.Retention; 2 | import java.lang.annotation.RetentionPolicy; 3 | import java.lang.reflect.Method; 4 | 5 | // A single-member annotation. 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @interface MySingle { 8 | int value(); // this variable name must be value 9 | } 10 | 11 | 12 | class Single { 13 | 14 | // Annotate a method using a marker. 15 | @MySingle(100) 16 | public static void myMeth() { 17 | Single ob = new Single(); 18 | 19 | try { 20 | Method m = ob.getClass().getMethod("myMeth"); 21 | 22 | MySingle anno = m.getAnnotation(MySingle.class); 23 | 24 | System.out.println(anno.value()); // displays 100 25 | 26 | } catch (NoSuchMethodException exc) { 27 | System.out.println("Method Not Found."); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | myMeth(); 33 | } 34 | } -------------------------------------------------------------------------------- /Chapter-12/src/UnboxingError.java: -------------------------------------------------------------------------------- 1 | // An error produced by manual unboxing. 2 | class UnboxingError { 3 | public static void main(String[] args) { 4 | 5 | Integer iOb = 1000; // autobox the value 1000 6 | 7 | int i = iOb.byteValue(); // manually unbox as byte !!! 8 | 9 | System.out.println(i); // does not display 1000 ! 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-12/src/Wrap.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a type wrapper. 2 | class Wrap { 3 | public static void main(String[] args) { 4 | 5 | Integer iOb = Integer.valueOf(100); 6 | 7 | int i = iOb.intValue(); 8 | 9 | System.out.println(i + " " + iOb); // displays 100 100 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-13/src/AssertDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate assert. 2 | class AssertDemo { 3 | static int val = 3; 4 | 5 | // Return an integer. 6 | static int getnum() { 7 | return val--; 8 | } 9 | 10 | public static void main(String[] args) { 11 | int n; 12 | 13 | for (int i = 0; i < 10; i++) { 14 | n = getnum(); 15 | 16 | assert n > 0; // will fail when n is 0 17 | 18 | System.out.println("n is " + n); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-13/src/AssertDemo2.java: -------------------------------------------------------------------------------- 1 | // A poor way to use assert!!! 2 | class AssertDemo2 { 3 | // get a random number generator 4 | static int val = 3; 5 | 6 | // Return an integer. 7 | static int getnum() { 8 | return val--; 9 | } 10 | 11 | public static void main(String[] args) { 12 | int n = 0; 13 | 14 | for (int i = 0; i < 10; i++) { 15 | 16 | assert (n = getnum()) > 0; // This is not a good idea! 17 | 18 | System.out.println("n is " + n); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter-13/src/BRRead.java: -------------------------------------------------------------------------------- 1 | // Use a BufferedReader to read characters from the console. 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | class BRRead { 8 | public static void main(String[] args) throws IOException { 9 | char c; 10 | BufferedReader br = new BufferedReader(new 11 | InputStreamReader(System.in, System.console().charset())); 12 | 13 | System.out.println("Enter characters, 'q' to quit."); 14 | // read characters 15 | do { 16 | c = (char) br.read(); 17 | System.out.println(c); 18 | } while (c != 'q'); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter-13/src/BRReadLines.java: -------------------------------------------------------------------------------- 1 | // Read a string from console using a BufferedReader. 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | class BRReadLines { 8 | public static void main(String[] args) throws IOException { 9 | // create a BufferedReader using System.in 10 | BufferedReader br = new BufferedReader(new 11 | InputStreamReader(System.in, System.console().charset())); 12 | 13 | String str; 14 | System.out.println("Enter lines of text."); 15 | System.out.println("Enter 'stop' to quit."); 16 | do { 17 | str = br.readLine(); 18 | System.out.println(str); 19 | } while (!str.equals("stop")); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-13/src/CopyFile2.java: -------------------------------------------------------------------------------- 1 | /* A version of CopyFile that uses try-with-resources. 2 | It demonstrates two resources (in this case files) being 3 | managed by a single try statement. 4 | */ 5 | 6 | import java.io.FileInputStream; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | 10 | class CopyFile2 { 11 | public static void main(String[] args) throws IOException { 12 | int i; 13 | 14 | // First, confirm that both files has been specified. 15 | if (args.length != 2) { 16 | System.out.println("Usage: CopyFile from to"); 17 | return; 18 | } 19 | 20 | // Open and manage two files via the try statement. 21 | try (FileInputStream fin = new FileInputStream(args[0]); 22 | FileOutputStream fout = new FileOutputStream(args[1])) { 23 | 24 | do { 25 | i = fin.read(); 26 | if (i != -1) fout.write(i); 27 | } while (i != -1); 28 | 29 | } catch (IOException e) { 30 | System.out.println("I/O Error: " + e); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Chapter-13/src/Hypot.java: -------------------------------------------------------------------------------- 1 | // Compute the hypotenuse of a right triangle. 2 | class Hypot { 3 | public static void main(String[] args) { 4 | double side1, side2; 5 | double hypot; 6 | side1 = 3.0; 7 | side2 = 4.0; 8 | 9 | // Notice how sqrt() and pow() must be qualified by 10 | // their class name, which is Math. 11 | hypot = Math.sqrt(Math.pow(side1, 2) + 12 | Math.pow(side2, 2)); 13 | 14 | System.out.println("Given sides of lengths " + 15 | side1 + " and " + side2 + 16 | " the hypotenuse is " + 17 | hypot); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-13/src/Hypot2.java: -------------------------------------------------------------------------------- 1 | // Use static import to bring sqrt() and pow() into view. 2 | 3 | import static java.lang.Math.pow; 4 | import static java.lang.Math.sqrt; 5 | 6 | // Compute the hypotenuse of a right triangle. 7 | class Hypot2 { 8 | public static void main(String[] args) { 9 | double side1, side2; 10 | double hypot; 11 | 12 | side1 = 3.0; 13 | side2 = 4.0; 14 | 15 | // Here, sqrt() and pow() can be called by themselves, 16 | // without their class name. 17 | hypot = sqrt(pow(side1, 2) + pow(side2, 2)); 18 | 19 | System.out.println("Given sides of lengths " + 20 | side1 + " and " + side2 + 21 | " the hypotenuse is " + 22 | hypot); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-13/src/MyClass.java: -------------------------------------------------------------------------------- 1 | class MyClass { 2 | int a; 3 | int b; 4 | 5 | // initialize a and b individually 6 | MyClass(int i, int j) { 7 | a = i; 8 | b = j; 9 | } 10 | 11 | // initialize a and b to the same value 12 | MyClass(int i) { 13 | a = i; 14 | b = i; 15 | } 16 | 17 | // give a and b default values of 0 18 | MyClass() { 19 | a = 0; 20 | b = 0; 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-13/src/MyClass2.java: -------------------------------------------------------------------------------- 1 | class MyClass { 2 | int a; 3 | int b; 4 | 5 | // initialize a and b individually 6 | MyClass(int i, int j) { 7 | a = i; 8 | b = j; 9 | } 10 | 11 | // initialize a and b to the same value 12 | MyClass(int i) { 13 | this(i, i); // invokes MyClass(i, i) 14 | } 15 | 16 | // give a and b default values of 0 17 | MyClass() { 18 | this(0); // invokes MyClass(0) 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-13/src/PrintWriterDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate PrintWriter 2 | 3 | import java.io.PrintWriter; 4 | 5 | public class PrintWriterDemo { 6 | public static void main(String[] args) { 7 | PrintWriter pw = new PrintWriter(System.out, true); 8 | 9 | pw.println("This is a string"); 10 | int i = -7; 11 | pw.println(i); 12 | double d = 4.5e-7; 13 | pw.println(d); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-13/src/TinyEdit.java: -------------------------------------------------------------------------------- 1 | // A tiny editor. 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | class TinyEdit { 8 | public static void main(String[] args) throws IOException { 9 | // create a BufferedReader using System.in 10 | BufferedReader br = new BufferedReader(new 11 | InputStreamReader(System.in, System.console().charset())); 12 | 13 | String[] str = new String[100]; 14 | System.out.println("Enter lines of text."); 15 | System.out.println("Enter 'stop' to quit."); 16 | for (int i = 0; i < 100; i++) { 17 | str[i] = br.readLine(); 18 | if (str[i].equals("stop")) break; 19 | } 20 | System.out.println("\nHere is your file:"); 21 | // display the lines 22 | for (int i = 0; i < 100; i++) { 23 | if (str[i].equals("stop")) break; 24 | System.out.println(str[i]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter-13/src/WriteDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate System.out.write(). 2 | class WriteDemo { 3 | public static void main(String[] args) { 4 | int b; 5 | 6 | b = 'A'; 7 | System.out.write(b); 8 | System.out.write('\n'); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter-14/src/BridgeDemo.java: -------------------------------------------------------------------------------- 1 | // A situation that creates a bridge method. 2 | class Gen { 3 | T ob; // declare an object of type T 4 | 5 | // Pass the constructor a reference to 6 | // an object of type T. 7 | Gen(T o) { 8 | ob = o; 9 | } 10 | 11 | // Return ob. 12 | T getOb() { 13 | return ob; 14 | } 15 | } 16 | 17 | // A subclass of Gen. 18 | class Gen2 extends Gen { 19 | 20 | Gen2(String o) { 21 | super(o); 22 | } 23 | 24 | // A String-specific override of getOb(). 25 | String getOb() { 26 | System.out.print("You called String getOb(): "); 27 | return ob; 28 | } 29 | } 30 | 31 | // Demonstrate a situation that requires a bridge method. 32 | class BridgeDemo { 33 | public static void main(String[] args) { 34 | 35 | // Create a Gen2 object for Strings. 36 | Gen2 strOb2 = new Gen2("Generics Test"); 37 | 38 | System.out.println(strOb2.getOb()); 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter-14/src/Gen.java: -------------------------------------------------------------------------------- 1 | // A simple generic class hierarchy. 2 | class Gen { 3 | T ob; 4 | 5 | Gen(T o) { 6 | ob = o; 7 | } 8 | 9 | // Return ob. 10 | T getOb() { 11 | return ob; 12 | } 13 | } 14 | 15 | // A subclass of Gen. 16 | class Gen2 extends Gen { 17 | Gen2(T o) { 18 | super(o); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-14/src/Gen2.java: -------------------------------------------------------------------------------- 1 | // Can't create an instance of T. 2 | class Gen { 3 | T ob; 4 | 5 | Gen() { 6 | ob = new T(); // Illegal!!! 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Chapter-14/src/GenArrays.java: -------------------------------------------------------------------------------- 1 | // Generics and arrays. 2 | class Gen { 3 | T ob; 4 | 5 | T[] vals; // OK 6 | 7 | Gen(T o, T[] nums) { 8 | ob = o; 9 | 10 | // This statement is illegal. 11 | // vals = new T[10]; // can't create an array of T 12 | 13 | // But, this statement is OK. 14 | vals = nums; // OK to assign reference to existent array 15 | } 16 | } 17 | 18 | 19 | class GenArrays { 20 | public static void main(String[] args) { 21 | Integer[] n = {1, 2, 3, 4, 5}; 22 | 23 | Gen iOb = new Gen(50, n); 24 | 25 | // Can't create an array of type-specific generic references. 26 | // Gen[] gens = new Gen[10]; // Wrong! 27 | 28 | // This is OK. 29 | Gen[] gens = new Gen[10]; // OK 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter-14/src/GenConsDemo.java: -------------------------------------------------------------------------------- 1 | // Use a generic constructor. 2 | class GenCons { 3 | private double val; 4 | 5 | GenCons(T arg) { 6 | val = arg.doubleValue(); 7 | } 8 | 9 | void showVal() { 10 | System.out.println("val: " + val); 11 | } 12 | } 13 | 14 | 15 | class GenConsDemo { 16 | public static void main(String[] args) { 17 | 18 | GenCons test = new GenCons(100); 19 | GenCons test2 = new GenCons(123.5F); 20 | 21 | test.showVal(); 22 | test2.showVal(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter-14/src/HierDemo.java: -------------------------------------------------------------------------------- 1 | // A subclass can add its own type parameters. 2 | class Gen { 3 | T ob; // declare an object of type T 4 | 5 | // Pass the constructor a reference to 6 | // an object of type T. 7 | Gen(T o) { 8 | ob = o; 9 | } 10 | 11 | // Return ob. 12 | T getOb() { 13 | return ob; 14 | } 15 | } 16 | 17 | // A subclass of Gen that defines a second 18 | // type parameter, called V. 19 | class Gen2 extends Gen { 20 | V ob2; 21 | 22 | Gen2(T o, V o2) { 23 | super(o); 24 | ob2 = o2; 25 | } 26 | 27 | V getOb2() { 28 | return ob2; 29 | } 30 | } 31 | 32 | // Create an object of type Gen2. 33 | class HierDemo { 34 | public static void main(String[] args) { 35 | 36 | // Create a Gen2 object for String and Integer. 37 | Gen2 x = 38 | new Gen2("Value is: ", 99); 39 | 40 | System.out.print(x.getOb()); 41 | System.out.println(x.getOb2()); 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter-14/src/HierDemo2.java: -------------------------------------------------------------------------------- 1 | // A nongeneric class can be the superclass 2 | // of a generic subclass. 3 | 4 | // A nongeneric class. 5 | class NonGen { 6 | int num; 7 | 8 | NonGen(int i) { 9 | num = i; 10 | } 11 | 12 | int getnum() { 13 | return num; 14 | } 15 | } 16 | 17 | // A generic subclass. 18 | class Gen extends NonGen { 19 | T ob; // declare an object of type T 20 | 21 | // Pass the constructor a reference to 22 | // an object of type T. 23 | Gen(T o, int i) { 24 | super(i); 25 | ob = o; 26 | } 27 | 28 | // Return ob. 29 | T getOb() { 30 | return ob; 31 | } 32 | } 33 | 34 | // Create a Gen object. 35 | class HierDemo2 { 36 | public static void main(String[] args) { 37 | 38 | // Create a Gen object for String. 39 | Gen w = new Gen("Hello", 47); 40 | 41 | System.out.print(w.getOb() + " "); 42 | System.out.println(w.getnum()); 43 | } 44 | } -------------------------------------------------------------------------------- /Chapter-14/src/MyGenClass.java: -------------------------------------------------------------------------------- 1 | // Ambiguity caused by erasure on 2 | // overloaded methods. 3 | class MyGenClass { 4 | T ob1; 5 | V ob2; 6 | 7 | // ... 8 | 9 | // These two overloaded methods are ambiguous 10 | // and will not compile. 11 | void set(T o) { 12 | ob1 = o; 13 | } 14 | 15 | void set(V o) { 16 | ob2 = o; 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter-14/src/Stats.java: -------------------------------------------------------------------------------- 1 | // Stats attempts (unsuccessfully) to 2 | // create a generic class that can compute 3 | // the average of an array of numbers of 4 | // any given type. 5 | // 6 | // The class contains an error! 7 | class Stats { 8 | T[] nums; // nums is an array of type T 9 | 10 | // Pass the constructor a reference to 11 | // an array of type T. 12 | Stats(T[] o) { 13 | nums = o; 14 | } 15 | 16 | // Return type double in all cases. 17 | double average() { 18 | double sum = 0.0; 19 | 20 | for (int i = 0; i < nums.length; i++) 21 | sum += nums[i].doubleValue(); // Error!!! 22 | 23 | return sum / nums.length; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter-14/src/Wrong.java: -------------------------------------------------------------------------------- 1 | class Wrong { 2 | // Wrong, no static variables of type T. 3 | static T ob; 4 | 5 | // Wrong, no static method can use T. 6 | static T getOb() { 7 | return ob; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter-15/src/BlockLambdaDemo.java: -------------------------------------------------------------------------------- 1 | // A block lambda that computes the factorial of an int value. 2 | 3 | interface NumericFunc { 4 | int func(int n); 5 | } 6 | 7 | class BlockLambdaDemo { 8 | public static void main(String[] args) { 9 | 10 | // This block lambda computes the factorial of an int value. 11 | NumericFunc factorial = (n) -> { 12 | int result = 1; 13 | 14 | for (int i = 1; i <= n; i++) 15 | result = i * result; 16 | 17 | return result; 18 | }; 19 | 20 | System.out.println("The factoral of 3 is " + factorial.func(3)); 21 | System.out.println("The factoral of 5 is " + factorial.func(5)); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter-15/src/BlockLambdaDemo2.java: -------------------------------------------------------------------------------- 1 | // A block lambda that reverses the characters in a string. 2 | 3 | interface StringFunc { 4 | String func(String n); 5 | } 6 | 7 | class BlockLambdaDemo2 { 8 | public static void main(String[] args) { 9 | 10 | // This block lambda that reverses the characters in a string. 11 | StringFunc reverse = (str) -> { 12 | String result = ""; 13 | int i; 14 | 15 | for (i = str.length() - 1; i >= 0; i--) 16 | result += str.charAt(i); 17 | 18 | return result; 19 | }; 20 | 21 | System.out.println("Lambda reversed is " + 22 | reverse.func("Lambda")); 23 | System.out.println("Expression reversed is " + 24 | reverse.func("Expression")); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter-15/src/ConstructorRefDemo2.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a constructor reference with a generic class. 2 | 3 | // MyFunc is now a generic functional interface. 4 | interface MyFunc { 5 | MyClass func(T n); 6 | } 7 | 8 | class MyClass { 9 | private T val; 10 | 11 | // A constructor that takes an argument. 12 | MyClass(T v) { 13 | val = v; 14 | } 15 | 16 | // This is the default constructor. 17 | MyClass() { 18 | val = null; 19 | } 20 | 21 | // ... 22 | 23 | T getVal() { 24 | return val; 25 | } 26 | 27 | ; 28 | } 29 | 30 | class ConstructorRefDemo2 { 31 | 32 | public static void main(String[] args) { 33 | // Create a reference to the MyClass constructor. 34 | MyFunc myClassCons = MyClass::new; 35 | 36 | // Create an instance of MyClass via that constructor reference. 37 | MyClass mc = myClassCons.func(100); 38 | 39 | // Use the instance of MyClass just created. 40 | System.out.println("val in mc is " + mc.getVal()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter-15/src/LambdaDemo2.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a lambda expression that takes a parameter. 2 | 3 | // Another functional interface. 4 | interface NumericTest { 5 | boolean test(int n); 6 | } 7 | 8 | class LambdaDemo2 { 9 | public static void main(String[] args) { 10 | // A lambda expression that tests if a number is even. 11 | NumericTest isEven = (n) -> (n % 2) == 0; 12 | 13 | if (isEven.test(10)) System.out.println("10 is even"); 14 | if (!isEven.test(9)) System.out.println("9 is not even"); 15 | 16 | // Now, use a lambda expression that tests if a number 17 | // is non-negative. 18 | NumericTest isNonNeg = (n) -> n >= 0; 19 | 20 | if (isNonNeg.test(1)) System.out.println("1 is non-negative"); 21 | if (!isNonNeg.test(-1)) System.out.println("-1 is negative"); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter-15/src/LambdaDemo3.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a lambda expression that takes two parameters. 2 | 3 | interface NumericTest { 4 | boolean test(int n, int d); 5 | } 6 | 7 | class LambdaDemo3 { 8 | public static void main(String[] args) { 9 | // This lambda expression determines if one number is 10 | // a factor of another. 11 | NumericTest isFactor = (n, d) -> (n % d) == 0; 12 | 13 | if (isFactor.test(10, 2)) 14 | System.out.println("2 is a factor of 10"); 15 | 16 | if (!isFactor.test(10, 3)) 17 | System.out.println("3 is not a factor of 10"); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-15/src/LambdaExceptionDemo.java: -------------------------------------------------------------------------------- 1 | // Throw an exception from a lambda expression. 2 | 3 | interface DoubleNumericArrayFunc { 4 | double func(double[] n) throws EmptyArrayException; 5 | } 6 | 7 | class EmptyArrayException extends Exception { 8 | EmptyArrayException() { 9 | super("Array Empty"); 10 | } 11 | } 12 | 13 | class LambdaExceptionDemo { 14 | 15 | public static void main(String[] args) throws EmptyArrayException { 16 | double[] values = {1.0, 2.0, 3.0, 4.0}; 17 | 18 | // This block lambda computes the average of an array of doubles. 19 | DoubleNumericArrayFunc average = (n) -> { 20 | double sum = 0; 21 | 22 | if (n.length == 0) 23 | throw new EmptyArrayException(); 24 | 25 | for (int i = 0; i < n.length; i++) 26 | sum += n[i]; 27 | 28 | return sum / n.length; 29 | }; 30 | 31 | System.out.println("The average is " + average.func(values)); 32 | 33 | // This causes an exception to be thrown. 34 | System.out.println("The average is " + average.func(new double[0])); 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter-15/src/UseFunctionInterfaceDemo.java: -------------------------------------------------------------------------------- 1 | // Use the Function built-in functional interface. 2 | 3 | // Import the Function interface. 4 | 5 | import java.util.function.Function; 6 | 7 | class UseFunctionInterfaceDemo { 8 | public static void main(String[] args) { 9 | 10 | // This block lambda computes the factorial of an int value. 11 | // This time, Function is the functional interface. 12 | Function factorial = (n) -> { 13 | int result = 1; 14 | for (int i = 1; i <= n; i++) 15 | result = i * result; 16 | return result; 17 | }; 18 | 19 | System.out.println("The factoral of 3 is " + factorial.apply(3)); 20 | System.out.println("The factoral of 5 is " + factorial.apply(5)); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-15/src/UseMethodRef.java: -------------------------------------------------------------------------------- 1 | // Use a method reference to help find the maximum value in a collection. 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | class MyClass { 7 | private int val; 8 | 9 | MyClass(int v) { 10 | val = v; 11 | } 12 | 13 | int getVal() { 14 | return val; 15 | } 16 | } 17 | 18 | class UseMethodRef { 19 | // A compare() method compatible with the one defined by Comparator. 20 | static int compareMC(MyClass a, MyClass b) { 21 | return a.getVal() - b.getVal(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | ArrayList al = new ArrayList(); 26 | 27 | al.add(new MyClass(1)); 28 | al.add(new MyClass(4)); 29 | al.add(new MyClass(2)); 30 | al.add(new MyClass(9)); 31 | al.add(new MyClass(3)); 32 | al.add(new MyClass(7)); 33 | 34 | // Find the maximum value in al using the compareMC() method. 35 | MyClass maxValObj = Collections.max(al, UseMethodRef::compareMC); 36 | 37 | System.out.println("Maximum value is: " + maxValObj.getVal()); 38 | } 39 | } -------------------------------------------------------------------------------- /Chapter-15/src/VarCapture.java: -------------------------------------------------------------------------------- 1 | // An example of capturing a local variable from the enclosing scope. 2 | 3 | interface MyFunc { 4 | int func(int n); 5 | } 6 | 7 | class VarCapture { 8 | public static void main(String[] args) { 9 | // A local variable that can be captured. 10 | int num = 10; 11 | 12 | MyFunc myLambda = (n) -> { 13 | // This use of num is OK. It does not modify num. 14 | int v = num + n; 15 | 16 | // However, the following is illegal because it attempts 17 | // to modify the value of num. 18 | // num++; 19 | 20 | return v; 21 | }; 22 | 23 | // The following line would also cause an error, because 24 | // it would remove the effectively final status from num. 25 | // num = 9; 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter-16/README.md: -------------------------------------------------------------------------------- 1 | # Commands 2 | 3 | **Compilation of all modules** 4 | ```bash 5 | javac -d appmodules --module-source-path appsrc appsrc/appstart/appstart/mymodappdemo/MyModAppDemo.java 6 | ``` 7 | 8 | **Running the module** 9 | ```bash 10 | java --module-path appmodules -m appstart/appstart.mymodappdemo.MyModAppDemo 11 | ``` 12 | 13 | **Compilation of individual module** 14 | ```bash 15 | javac --module-path appmodules -d appmodules/appstart appsrc/appstart/module-info.java appsrc /appstart/appstart/mymodappdemo/MyModAppDemo.java 16 | ``` 17 | 18 | **Compilation of module based service** 19 | ```bash 20 | javac -d appmodules --module-source-path appsrc appsrc/userfuncsimp/module-info.java appsrc/appstart/appstart/mymodappdemo/MyModAppDemo.java 21 | ``` -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(initial)/appsrc/appfuncs/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for the functions module. 2 | module appfuncs { 3 | 4 | // Exports the package appfuncs.simplefuncs. 5 | exports appfuncs.simplefuncs; 6 | } 7 | -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(initial)/appsrc/appstart/appstart/mymodappdemo/MyModAppDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a simple module-based application. 2 | package appstart.mymodappdemo; 3 | 4 | import appfuncs.simplefuncs.SimpleMathFuncs; 5 | 6 | public class MyModAppDemo { 7 | public static void main(String[] args) { 8 | 9 | if (SimpleMathFuncs.isFactor(2, 10)) 10 | System.out.println("2 is a factor of 10"); 11 | 12 | System.out.println("Smallest factor common to both 35 and 105 is " + 13 | SimpleMathFuncs.lcf(35, 105)); 14 | 15 | System.out.println("Largest factor common to both 35 and 105 is " + 16 | SimpleMathFuncs.gcf(35, 105)); 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(initial)/appsrc/appstart/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for the main application module. 2 | module appstart { 3 | // Requires the module appfuncs. 4 | requires appfuncs; 5 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/appfuncs/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for the functions module. 2 | module appfuncs { 3 | 4 | // Exports the package appfuncs.simplefuncs. 5 | exports appfuncs.simplefuncs; 6 | } 7 | -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/appstart/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for the main application module. 2 | // It now uses BinFuncProvider. 3 | module appstart { 4 | // Requires the modules appfuncs and userfuncs. 5 | requires appfuncs; 6 | requires userfuncs; 7 | 8 | // appstart now uses BinFuncProvider. 9 | uses userfuncs.binaryfuncs.BinFuncProvider; 10 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncs/module-info.java: -------------------------------------------------------------------------------- 1 | module userfuncs { 2 | exports userfuncs.binaryfuncs; 3 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncs/userfuncs/binaryfuncs/BinFuncProvider.java: -------------------------------------------------------------------------------- 1 | // This interface defines the form of a service provider that 2 | // obtains BinaryFunc instances. 3 | package userfuncs.binaryfuncs; 4 | 5 | import userfuncs.binaryfuncs.BinaryFunc; 6 | 7 | public interface BinFuncProvider { 8 | 9 | // Obtain a BinaryFunc. 10 | public BinaryFunc get(); 11 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncs/userfuncs/binaryfuncs/BinaryFunc.java: -------------------------------------------------------------------------------- 1 | // This interface defines a function that takes two int 2 | // arguments and returns an int result. Thus, it can 3 | // describe any binary operation on two ints that 4 | // returns an int. 5 | 6 | package userfuncs.binaryfuncs; 7 | 8 | public interface BinaryFunc { 9 | // Obtain the name of the function. 10 | public String getName(); 11 | 12 | // This is the function to perform. It will be 13 | // provided by specific implementations. 14 | public int func(int a, int b); 15 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncsimp/module-info.java: -------------------------------------------------------------------------------- 1 | module userfuncsimp { 2 | requires userfuncs; 3 | 4 | provides userfuncs.binaryfuncs.BinFuncProvider with 5 | userfuncsimp.binaryfuncsimp.AbsPlusProvider, 6 | userfuncsimp.binaryfuncsimp.AbsMinusProvider; 7 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncsimp/userfuncsimp/binaryfuncsimp/AbsMinus.java: -------------------------------------------------------------------------------- 1 | // AbsMinus provides a concrete implementation of 2 | // BinaryFunc. It returns the result of abs(a) - abs(b). 3 | 4 | package userfuncsimp.binaryfuncsimp; 5 | 6 | import userfuncs.binaryfuncs.BinaryFunc; 7 | 8 | public class AbsMinus implements BinaryFunc { 9 | 10 | // Return name of this function. 11 | public String getName() { 12 | return "absMinus"; 13 | } 14 | 15 | // Implement the AbsMinus function. 16 | public int func(int a, int b) { 17 | return Math.abs(a) - Math.abs(b); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncsimp/userfuncsimp/binaryfuncsimp/AbsMinusProvider.java: -------------------------------------------------------------------------------- 1 | // This is a provider for the AbsMinus function. 2 | 3 | package userfuncsimp.binaryfuncsimp; 4 | 5 | import userfuncs.binaryfuncs.*; 6 | 7 | public class AbsMinusProvider implements BinFuncProvider { 8 | 9 | // Provide an AbsMinus object. 10 | public BinaryFunc get() { 11 | return new AbsMinus(); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncsimp/userfuncsimp/binaryfuncsimp/AbsPlus.java: -------------------------------------------------------------------------------- 1 | // AbsPlus provides a concrete implementation of 2 | // BinaryFunc. It returns the result of abs(a) + abs(b). 3 | package userfuncsimp.binaryfuncsimp; 4 | 5 | import userfuncs.binaryfuncs.BinaryFunc; 6 | 7 | public class AbsPlus implements BinaryFunc { 8 | 9 | // Return name of this function. 10 | public String getName() { 11 | return "absPlus"; 12 | } 13 | 14 | // Implement the AbsPlus function. 15 | public int func(int a, int b) { 16 | return Math.abs(a) + Math.abs(b); 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(module-based-service)/appsrc/userfuncsimp/userfuncsimp/binaryfuncsimp/AbsPlusProvider.java: -------------------------------------------------------------------------------- 1 | // This is a provider for the AbsPlus function. 2 | 3 | package userfuncsimp.binaryfuncsimp; 4 | 5 | import userfuncs.binaryfuncs.*; 6 | 7 | public class AbsPlusProvider implements BinFuncProvider { 8 | 9 | // Provide an AbsPlus object. 10 | public BinaryFunc get() { 11 | return new AbsPlus(); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(transitive module changes)/appsrc/appfuncs/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for appfuncs. 2 | module appfuncs { 3 | // Exports the package appfuncs.simplefuncs. 4 | exports appfuncs.simplefuncs; 5 | 6 | // Requires appsupport and makes it public 7 | requires transitive appsupport; 8 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(transitive module changes)/appsrc/appstart/appstart/mymodappdemo/MyModAppDemo.java: -------------------------------------------------------------------------------- 1 | // Updated to use SupportFuncs. 2 | package appstart.mymodappdemo; 3 | 4 | import appfuncs.simplefuncs.SimpleMathFuncs; 5 | import appsupport.supportfuncs.SupportFuncs; 6 | 7 | public class MyModAppDemo { 8 | public static void main(String[] args) { 9 | 10 | // Now, isFactor() is referred to via SupportFuncs, 11 | // not SimpleMathFuncs. 12 | if (SupportFuncs.isFactor(2, 10)) 13 | System.out.println("2 is a factor of 10"); 14 | 15 | System.out.println("Smallest factor common to both 35 and 105 is " + 16 | SimpleMathFuncs.lcf(35, 105)); 17 | 18 | System.out.println("Largest factor common to both 35 and 105 is " + 19 | SimpleMathFuncs.gcf(35, 105)); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(transitive module changes)/appsrc/appstart/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for the main application module. 2 | module appstart { 3 | // Requires the module appfuncs. 4 | requires appfuncs; 5 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(transitive module changes)/appsrc/appsupport/appsupport/supportfuncs/SupportFuncs.java: -------------------------------------------------------------------------------- 1 | // Support functions. 2 | 3 | package appsupport.supportfuncs; 4 | 5 | public class SupportFuncs { 6 | 7 | // Determine if a is a factor of b. 8 | public static boolean isFactor(int a, int b) { 9 | if ((b % a) == 0) return true; 10 | return false; 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-16/src/mymodapp(transitive module changes)/appsrc/appsupport/module-info.java: -------------------------------------------------------------------------------- 1 | // Module definition for appsupport. 2 | module appsupport { 3 | exports appsupport.supportfuncs; 4 | } -------------------------------------------------------------------------------- /Chapter-17/src/InstanceOfDemo.java: -------------------------------------------------------------------------------- 1 | public class InstanceOfDemo { 2 | 3 | public static void main(String[] args) { 4 | Number num = Integer.valueOf(100); 5 | 6 | if (num instanceof Integer numInt) { 7 | System.out.println("numInt is of type: " + numInt.getClass()); 8 | } 9 | 10 | if (num instanceof Integer numInt && numInt < 1000) { 11 | System.out.println("Number less than 1000"); 12 | } 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter-17/src/SealedClassDemo.java: -------------------------------------------------------------------------------- 1 | sealed interface A permits B, C, D { 2 | 3 | } 4 | 5 | non-sealed interface D extends A { 6 | 7 | } 8 | 9 | public class SealedClassDemo { 10 | } 11 | 12 | sealed class MySealedClass permits Alpha, Beta, Gamma { 13 | 14 | } 15 | 16 | final class Alpha extends MySealedClass { 17 | 18 | } 19 | 20 | non-sealed class Beta extends MySealedClass { 21 | 22 | } 23 | // This is invalid 24 | /* 25 | final class Temp extends MySealedClass{ 26 | 27 | }*/ 28 | 29 | sealed class Gamma extends MySealedClass permits GammaImpl { 30 | 31 | } 32 | 33 | final class GammaImpl extends Gamma { 34 | 35 | } 36 | 37 | non-sealed class B implements A { 38 | 39 | } 40 | 41 | final class C implements A { 42 | 43 | } -------------------------------------------------------------------------------- /Chapter-17/src/StatementSwitchWithArrows.java: -------------------------------------------------------------------------------- 1 | // Use case arrows with a switch statement 2 | class StatementSwitchWithArrows { 3 | 4 | public static void main(String[] args) { 5 | int up = 0; 6 | int down = 0; 7 | int left = 0; 8 | int right = 0; 9 | 10 | char direction = 'R'; 11 | 12 | // Use arrows with a switch statement. Notice that 13 | // no value is produced. 14 | switch (direction) { 15 | case 'L' -> { 16 | System.out.println("Turning Left"); 17 | left++; 18 | } 19 | case 'R' -> { 20 | System.out.println("Turning Right"); 21 | right++; 22 | } 23 | case 'U' -> { 24 | System.out.println("Moving Up"); 25 | up++; 26 | } 27 | case 'D' -> { 28 | System.out.println("Moving Down"); 29 | down++; 30 | } 31 | } 32 | 33 | System.out.println(right); 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter-17/src/SwitchExpr.java: -------------------------------------------------------------------------------- 1 | // Convert a switch statement into a switch expression. 2 | class SwitchExpr { 3 | public static void main(String[] args) { 4 | int eventCode = 6010; 5 | 6 | // This is a switch expression. Notice how its value is assigned 7 | // to the priorityLevel variable. Also notice how the value of the 8 | // switch is supplied by the yield statement. 9 | int priorityLevel = switch (eventCode) { 10 | case 1000, 1205, 8900: 11 | yield 1; 12 | case 2000, 6010, 9128: 13 | yield 2; 14 | case 1002, 7023, 9300: 15 | yield 3; 16 | default: // normal priority 17 | yield 0; 18 | }; 19 | 20 | System.out.println("Priority level for event code " + eventCode + 21 | " is " + priorityLevel); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter-17/src/SwitchExpr2.java: -------------------------------------------------------------------------------- 1 | // Use the arrow "shorthand" to supply the priority level. 2 | class SwitchExpr2 { 3 | public static void main(String[] args) { 4 | int eventCode = 6010; 5 | 6 | // In this switch expression, notice how the value is supplied 7 | // by use of an arrow case. Notice that no break statement is 8 | // required (or allowed) to prevent fall through. 9 | int priorityLevel = switch (eventCode) { 10 | case 1000, 1205, 8900 -> 1; 11 | case 2000, 6010, 9128 -> 2; 12 | case 1002, 7023, 9300 -> 3; 13 | default -> 0; // normal priority 14 | }; 15 | 16 | System.out.println("Priority level for event code " + eventCode + 17 | " is " + priorityLevel); 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter-17/src/TextBlockDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate indentation in a text block. 2 | 3 | class TextBlockDemo { 4 | 5 | public static void main(String[] args) { 6 | String str = """ 7 | Text blocks support strings that 8 | span two or more lines and preserve 9 | indentation. They reduce the 10 | tedium associated with the 11 | entry of long or complicated 12 | strings into a program. 13 | """; 14 | 15 | System.out.println(str); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-17/src/TextBlockDemo2.java: -------------------------------------------------------------------------------- 1 | // Use double quotes in a text block. 2 | 3 | class TextBlockDemo2 { 4 | 5 | public static void main(String[] args) { 6 | 7 | String str = """ 8 | A text block can use double quotes without 9 | the need for escape sequences. For example: 10 | 11 | He said, "The cat is on the roof." 12 | She asked, "How did it get up there?" 13 | """; 14 | 15 | System.out.println(str); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-17/src/TraditionalSwitch.java: -------------------------------------------------------------------------------- 1 | // Use a traditional switch to set a priority level based on which 2 | // event code is matched. 3 | class TraditionalSwitch { 4 | 5 | public static void main(String[] args) { 6 | int priorityLevel; 7 | 8 | int eventCode = 6010; 9 | 10 | // A traditional switch that supplies a value associated 11 | // with a case. 12 | switch (eventCode) { 13 | case 1000: // In this traditional switch, case stacking is used. 14 | case 1205: 15 | case 8900: 16 | priorityLevel = 1; 17 | break; 18 | case 2000: 19 | case 6010: 20 | case 9128: 21 | priorityLevel = 2; 22 | break; 23 | case 1002: 24 | case 7023: 25 | case 9300: 26 | priorityLevel = 3; 27 | break; 28 | default: // normal priority 29 | priorityLevel = 0; 30 | } 31 | 32 | System.out.println("Priority level for event code " + eventCode + 33 | " is " + priorityLevel); 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter-17/src/UpdatedSwitch.java: -------------------------------------------------------------------------------- 1 | // Use a traditional switch to set a priority level based on which 2 | // event code is matched. 3 | class UpdatedSwitch { 4 | 5 | public static void main(String[] args) { 6 | int priorityLevel; 7 | 8 | int eventCode = 6010; 9 | 10 | // This switch uses a list of constants with each case. 11 | switch (eventCode) { 12 | case 1000, 1205, 8900: 13 | priorityLevel = 1; 14 | break; 15 | case 2000, 6010, 9128: 16 | priorityLevel = 2; 17 | break; 18 | case 1002, 7023, 9300: 19 | priorityLevel = 3; 20 | break; 21 | default: // normal priority 22 | priorityLevel = 0; 23 | } 24 | 25 | System.out.println("Priority level for event code " + eventCode + 26 | " is " + priorityLevel); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-17/src/Vowels.java: -------------------------------------------------------------------------------- 1 | // Use a switch expression to determine if a character is an English vowel. 2 | // Notice the use of a block as the target of an arrow case for Y. 3 | 4 | class Vowels { 5 | 6 | public static void main(String[] args) { 7 | 8 | // If Y is to be counted as a vowel, set this 9 | // variable to true. 10 | boolean yIsVowel = true; 11 | 12 | char ch = 'Y'; 13 | 14 | boolean isVowel = switch (ch) { 15 | case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' -> true; 16 | case 'y', 'Y' -> { 17 | if (yIsVowel) yield true; 18 | else yield false; 19 | } 20 | default -> false; 21 | }; 22 | 23 | if (isVowel) System.out.println(ch + " is a vowel."); 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter-18/src/ChangeCase.java: -------------------------------------------------------------------------------- 1 | // Demonstrate toUpperCase() and toLowerCase(). 2 | 3 | class ChangeCase { 4 | public static void main(String[] args) { 5 | String s = "This is a test."; 6 | 7 | System.out.println("Original: " + s); 8 | 9 | String upper = s.toUpperCase(); 10 | String lower = s.toLowerCase(); 11 | 12 | System.out.println("Uppercase: " + upper); 13 | System.out.println("Lowercase: " + lower); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-18/src/ConCat.java: -------------------------------------------------------------------------------- 1 | // Using concatenation to prevent long lines. 2 | class ConCat { 3 | public static void main(String[] args) { 4 | String longStr = "This could have been " + 5 | "a very long line that would have " + 6 | "wrapped around. But string concatenation " + 7 | "prevents this."; 8 | 9 | System.out.println(longStr); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-18/src/EqualsNotEqualTo.java: -------------------------------------------------------------------------------- 1 | // equals() vs == 2 | class EqualsNotEqualTo { 3 | public static void main(String[] args) { 4 | String s1 = "Hello"; 5 | String s2 = new String(s1); 6 | 7 | System.out.println(s1 + " equals " + s2 + " -> " + 8 | s1.equals(s2)); 9 | System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-18/src/MakeString.java: -------------------------------------------------------------------------------- 1 | // Construct one String from another. 2 | class MakeString { 3 | public static void main(String[] args) { 4 | char[] c = {'J', 'a', 'v', 'a'}; 5 | String s1 = new String(c); 6 | String s2 = new String(s1); 7 | 8 | System.out.println(s1); 9 | System.out.println(s2); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-18/src/ReverseDemo.java: -------------------------------------------------------------------------------- 1 | // Using reverse() to reverse a StringBuffer. 2 | class ReverseDemo { 3 | public static void main(String[] args) { 4 | StringBuffer s = new StringBuffer("abcdef"); 5 | 6 | System.out.println(s); 7 | s.reverse(); 8 | System.out.println(s); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-18/src/SortString.java: -------------------------------------------------------------------------------- 1 | // A bubble sort for Strings. 2 | class SortString { 3 | static String[] arr = { 4 | "Now", "is", "the", "time", "for", "all", "good", "men", 5 | "to", "come", "to", "the", "aid", "of", "their", "country" 6 | }; 7 | 8 | public static void main(String[] args) { 9 | for (int j = 0; j < arr.length; j++) { 10 | for (int i = j + 1; i < arr.length; i++) { 11 | if (arr[i].compareTo(arr[j]) < 0) { 12 | String t = arr[j]; 13 | arr[j] = arr[i]; 14 | arr[i] = t; 15 | } 16 | } 17 | System.out.println(arr[j]); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter-18/src/StringBufferDemo.java: -------------------------------------------------------------------------------- 1 | // StringBuffer length vs. capacity. 2 | class StringBufferDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("Hello"); 5 | 6 | System.out.println("buffer = " + sb); 7 | System.out.println("length = " + sb.length()); 8 | System.out.println("capacity = " + sb.capacity()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter-18/src/StringBufferIndexOfDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate indexOf() and lasrIndexOf() 2 | class StringBufferIndexOfDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("one two one"); 5 | int i; 6 | 7 | i = sb.indexOf("one"); 8 | System.out.println("First index: " + i); 9 | 10 | i = sb.lastIndexOf("one"); 11 | System.out.println("Last index: " + i); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-18/src/StringJoinDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the join() method defined by String. 2 | class StringJoinDemo { 3 | public static void main(String[] args) { 4 | 5 | String result = String.join(" ", "Alpha", "Beta", "Gamma"); 6 | System.out.println(result); 7 | 8 | result = String.join(", ", "John", "ID#: 569", 9 | "E-mail: John@HerbSchildt.com"); 10 | System.out.println(result); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-18/src/StringReplace.java: -------------------------------------------------------------------------------- 1 | // Substring replacement. 2 | class StringReplace { 3 | public static void main(String[] args) { 4 | String org = "This is a test. This is, too."; 5 | String search = "is"; 6 | String sub = "was"; 7 | String result = ""; 8 | int i; 9 | 10 | do { // replace all matching substrings 11 | System.out.println(org); 12 | i = org.indexOf(search); 13 | if (i != -1) { 14 | result = org.substring(0, i); 15 | result = result + sub; 16 | result = result + org.substring(i + search.length()); 17 | org = result; 18 | } 19 | } while (i != -1); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-18/src/SubStringCons.java: -------------------------------------------------------------------------------- 1 | // Construct string from subset of char array. 2 | class SubStringCons { 3 | public static void main(String[] args) { 4 | byte[] ascii = {65, 66, 67, 68, 69, 70}; 5 | 6 | String s1 = new String(ascii); 7 | System.out.println(s1); 8 | 9 | String s2 = new String(ascii, 2, 3); 10 | System.out.println(s2); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-18/src/appendDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate append(). 2 | class appendDemo { 3 | public static void main(String[] args) { 4 | String s; 5 | int a = 42; 6 | StringBuffer sb = new StringBuffer(40); 7 | 8 | s = sb.append("a = ").append(a).append("!").toString(); 9 | System.out.println(s); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-18/src/deleteDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate delete() and deleteCharAt() 2 | class deleteDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("This is a test."); 5 | 6 | sb.delete(4, 7); 7 | System.out.println("After delete: " + sb); 8 | 9 | sb.deleteCharAt(0); 10 | System.out.println("After deleteCharAt: " + sb); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-18/src/equalsDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate equals() and equalsIgnoreCase(). 2 | class equalsDemo { 3 | public static void main(String[] args) { 4 | String s1 = "Hello"; 5 | String s2 = "Hello"; 6 | String s3 = "Good-bye"; 7 | String s4 = "HELLO"; 8 | System.out.println(s1 + " equals " + s2 + " -> " + 9 | s1.equals(s2)); 10 | System.out.println(s1 + " equals " + s3 + " -> " + 11 | s1.equals(s3)); 12 | System.out.println(s1 + " equals " + s4 + " -> " + 13 | s1.equals(s4)); 14 | System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + 15 | s1.equalsIgnoreCase(s4)); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-18/src/getCharsDemo.java: -------------------------------------------------------------------------------- 1 | class getCharsDemo { 2 | public static void main(String[] args) { 3 | String s = "This is a demo of the getChars method."; 4 | int start = 10; 5 | int end = 14; 6 | char[] buf = new char[end - start]; 7 | 8 | s.getChars(start, end, buf, 0); 9 | System.out.println(buf); 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter-18/src/indexOfDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate indexOf() and lastIndexOf(). 2 | class indexOfDemo { 3 | public static void main(String[] args) { 4 | String s = "Now is the time for all good men " + 5 | "to come to the aid of their country."; 6 | 7 | System.out.println(s); 8 | System.out.println("indexOf(t) = " + 9 | s.indexOf('t')); 10 | System.out.println("lastIndexOf(t) = " + 11 | s.lastIndexOf('t')); 12 | System.out.println("indexOf(the) = " + 13 | s.indexOf("the")); 14 | System.out.println("lastIndexOf(the) = " + 15 | s.lastIndexOf("the")); 16 | System.out.println("indexOf(t, 10) = " + 17 | s.indexOf('t', 10)); 18 | System.out.println("lastIndexOf(t, 60) = " + 19 | s.lastIndexOf('t', 60)); 20 | System.out.println("indexOf(the, 10) = " + 21 | s.indexOf("the", 10)); 22 | System.out.println("lastIndexOf(the, 60) = " + 23 | s.lastIndexOf("the", 60)); 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter-18/src/insertDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate insert(). 2 | class insertDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("I Java!"); 5 | 6 | sb.insert(2, "like "); 7 | System.out.println(sb); 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-18/src/replaceDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate replace() 2 | class replaceDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("This is a test."); 5 | 6 | sb.replace(5, 7, "was"); 7 | System.out.println("After replace: " + sb); 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-18/src/setCharAtDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate charAt() and setCharAt(). 2 | class setCharAtDemo { 3 | public static void main(String[] args) { 4 | StringBuffer sb = new StringBuffer("Hello"); 5 | System.out.println("buffer before = " + sb); 6 | System.out.println("charAt(1) before = " + sb.charAt(1)); 7 | sb.setCharAt(1, 'i'); 8 | sb.setLength(2); 9 | System.out.println("buffer after = " + sb); 10 | System.out.println("charAt(1) after = " + sb.charAt(1)); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-18/src/toStringDemo.java: -------------------------------------------------------------------------------- 1 | // Override toString() for Box class. 2 | class Box { 3 | double width; 4 | double height; 5 | double depth; 6 | 7 | Box(double w, double h, double d) { 8 | width = w; 9 | height = h; 10 | depth = d; 11 | } 12 | 13 | public String toString() { 14 | return "Dimensions are " + width + " by " + 15 | depth + " by " + height + "."; 16 | } 17 | } 18 | 19 | class toStringDemo { 20 | public static void main(String[] args) { 21 | Box b = new Box(10, 12, 14); 22 | String s = "Box b: " + b; // concatenate Box object 23 | 24 | System.out.println(b); // convert Box to string 25 | System.out.println(s); 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter-19/src/ACDemo.java: -------------------------------------------------------------------------------- 1 | // Using arraycopy(). 2 | 3 | class ACDemo { 4 | static byte[] a = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74}; 5 | static byte[] b = {77, 77, 77, 77, 77, 77, 77, 77, 77, 77}; 6 | 7 | public static void main(String[] args) { 8 | System.out.println("a = " + new String(a)); 9 | System.out.println("b = " + new String(b)); 10 | System.arraycopy(a, 0, b, 0, a.length); 11 | System.out.println("a = " + new String(a)); 12 | System.out.println("b = " + new String(b)); 13 | System.arraycopy(a, 0, a, 1, a.length - 1); 14 | System.arraycopy(b, 1, b, 0, b.length - 1); 15 | System.out.println("a = " + new String(a)); 16 | System.out.println("b = " + new String(b)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter-19/src/Angles.java: -------------------------------------------------------------------------------- 1 | // Demonstrate toDegrees() and toRadians(). 2 | class Angles { 3 | public static void main(String[] args) { 4 | double theta = 120.0; 5 | 6 | System.out.println(theta + " degrees is " + 7 | Math.toRadians(theta) + " radians."); 8 | 9 | theta = 1.312; 10 | System.out.println(theta + " radians is " + 11 | Math.toDegrees(theta) + " degrees."); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-19/src/CloneDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the clone() method. 2 | 3 | class TestClone implements Cloneable { 4 | int a; 5 | double b; 6 | 7 | // This method calls Object's clone(). 8 | TestClone cloneTest() { 9 | try { 10 | // call clone in Object. 11 | return (TestClone) super.clone(); 12 | } catch (CloneNotSupportedException e) { 13 | System.out.println("Cloning not allowed."); 14 | return this; 15 | } 16 | } 17 | } 18 | 19 | 20 | class CloneDemo { 21 | public static void main(String[] args) { 22 | TestClone x1 = new TestClone(); 23 | TestClone x2; 24 | 25 | x1.a = 10; 26 | x1.b = 20.98; 27 | 28 | x2 = x1.cloneTest(); // clone x1 29 | 30 | System.out.println("x1: " + x1.a + " " + x1.b); 31 | System.out.println("x2: " + x2.a + " " + x2.b); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter-19/src/CloneDemo2.java: -------------------------------------------------------------------------------- 1 | // Override the clone() method. 2 | 3 | class TestClone implements Cloneable { 4 | int a; 5 | double b; 6 | 7 | // clone() is now overridden and is public. 8 | public Object clone() { 9 | try { 10 | // call clone in Object. 11 | return super.clone(); 12 | } catch (CloneNotSupportedException e) { 13 | System.out.println("Cloning not allowed."); 14 | return this; 15 | } 16 | } 17 | } 18 | 19 | 20 | class CloneDemo2 { 21 | public static void main(String[] args) { 22 | TestClone x1 = new TestClone(); 23 | TestClone x2; 24 | 25 | x1.a = 10; 26 | x1.b = 20.98; 27 | 28 | // here, clone() is called directly. 29 | x2 = (TestClone) x1.clone(); 30 | 31 | System.out.println("x1: " + x1.a + " " + x1.b); 32 | System.out.println("x2: " + x2.a + " " + x2.b); 33 | } 34 | } -------------------------------------------------------------------------------- /Chapter-19/src/DoubleDemo.java: -------------------------------------------------------------------------------- 1 | class DoubleDemo { 2 | public static void main(String[] args) { 3 | Double d1 = Double.valueOf(3.14159); 4 | Double d2 = Double.valueOf("314159E-5"); 5 | 6 | System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2)); 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter-19/src/Elapsed.java: -------------------------------------------------------------------------------- 1 | // Timing program execution. 2 | 3 | class Elapsed { 4 | public static void main(String[] args) { 5 | long start, end; 6 | 7 | System.out.println("Timing a for loop from 0 to 100,000,000"); 8 | 9 | // time a for loop from 0 to 100,000,000 10 | start = System.currentTimeMillis(); // get starting time 11 | for (long i = 0; i < 100000000L; i++) ; 12 | end = System.currentTimeMillis(); // get ending time 13 | 14 | System.out.println("Elapsed time: " + (end - start)); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-19/src/ExecDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate exec(). 2 | class ExecDemo { 3 | public static void main(String[] args) { 4 | Runtime r = Runtime.getRuntime(); 5 | Process p = null; 6 | 7 | try { 8 | p = r.exec("notepad"); 9 | } catch (Exception e) { 10 | System.out.println("Error executing notepad."); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-19/src/ExecDemoFini.java: -------------------------------------------------------------------------------- 1 | // Wait until notepad is terminated. 2 | class ExecDemoFini { 3 | public static void main(String[] args) { 4 | Runtime r = Runtime.getRuntime(); 5 | Process p = null; 6 | 7 | try { 8 | p = r.exec("notepad"); 9 | p.waitFor(); 10 | } catch (Exception e) { 11 | System.out.println("Error executing notepad."); 12 | } 13 | System.out.println("Notepad returned " + p.exitValue()); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-19/src/InfNaN.java: -------------------------------------------------------------------------------- 1 | // Demonstrate isInfinite() and isNaN(). 2 | class InfNaN { 3 | public static void main(String[] args) { 4 | Double d1 = Double.valueOf(1 / 0.); 5 | Double d2 = Double.valueOf(0 / 0.); 6 | 7 | System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN()); 8 | System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN()); 9 | } 10 | } -------------------------------------------------------------------------------- /Chapter-19/src/IsDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate several Is... methods. 2 | 3 | class IsDemo { 4 | public static void main(String[] args) { 5 | char[] a = {'a', 'b', '5', '?', 'A', ' '}; 6 | 7 | for (int i = 0; i < a.length; i++) { 8 | if (Character.isDigit(a[i])) 9 | System.out.println(a[i] + " is a digit."); 10 | if (Character.isLetter(a[i])) 11 | System.out.println(a[i] + " is a letter."); 12 | if (Character.isWhitespace(a[i])) 13 | System.out.println(a[i] + " is whitespace."); 14 | if (Character.isUpperCase(a[i])) 15 | System.out.println(a[i] + " is uppercase."); 16 | if (Character.isLowerCase(a[i])) 17 | System.out.println(a[i] + " is lowercase."); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-19/src/MyModAppDemo.java: -------------------------------------------------------------------------------- 1 | public class MyModAppDemo { 2 | public static void main(String[] args) { 3 | Module myMod = MyModAppDemo.class.getModule(); 4 | System.out.println("Module is " + myMod.getName()); 5 | 6 | System.out.print("Packages: "); 7 | for (String pkg : myMod.getPackages()) System.out.println(pkg + " "); 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter-19/src/PBDemo.java: -------------------------------------------------------------------------------- 1 | class PBDemo { 2 | public static void main(String[] args) { 3 | 4 | try { 5 | ProcessBuilder proc = 6 | new ProcessBuilder("notepad.exe", "testfile"); 7 | proc.start(); 8 | } catch (Exception e) { 9 | System.out.println("Error executing notepad."); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter-19/src/ParseDemo.java: -------------------------------------------------------------------------------- 1 | /* This program sums a list of numbers entered 2 | by the user. It converts the string representation 3 | of each number into an int using parseInt(). 4 | */ 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | class ParseDemo { 11 | public static void main(String[] args) 12 | throws IOException { 13 | // create a BufferedReader using System.in 14 | BufferedReader br = new 15 | BufferedReader(new InputStreamReader(System.in)); 16 | 17 | String str; 18 | int i; 19 | int sum = 0; 20 | 21 | System.out.println("Enter numbers, 0 to quit."); 22 | do { 23 | str = br.readLine(); 24 | try { 25 | i = Integer.parseInt(str); 26 | } catch (NumberFormatException e) { 27 | System.out.println("Invalid format"); 28 | i = 0; 29 | } 30 | sum += i; 31 | System.out.println("Current sum is: " + sum); 32 | } while (i != 0); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter-19/src/PkgTest.java: -------------------------------------------------------------------------------- 1 | // Demonstrate Package 2 | class PkgTest { 3 | public static void main(String[] args) { 4 | Package[] pkgs; 5 | 6 | pkgs = Package.getPackages(); 7 | 8 | for (int i = 0; i < pkgs.length; i++) 9 | System.out.println( 10 | pkgs[i].getName() + " " + 11 | pkgs[i].getImplementationTitle() + " " + 12 | pkgs[i].getImplementationVendor() + " " + 13 | pkgs[i].getImplementationVersion() 14 | ); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-19/src/RTTI.java: -------------------------------------------------------------------------------- 1 | // Demonstrate Run-Time Type Information. 2 | 3 | class X { 4 | int a; 5 | float b; 6 | } 7 | 8 | class Y extends X { 9 | double c; 10 | } 11 | 12 | class RTTI { 13 | public static void main(String[] args) { 14 | X x = new X(); 15 | Y y = new Y(); 16 | Class clObj; 17 | 18 | clObj = x.getClass(); // get Class reference 19 | System.out.println("x is object of type: " + 20 | clObj.getName()); 21 | 22 | clObj = y.getClass(); // get Class reference 23 | System.out.println("y is object of type: " + 24 | clObj.getName()); 25 | clObj = clObj.getSuperclass(); 26 | System.out.println("y's superclass is " + 27 | clObj.getName()); 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter-19/src/ShowUserDir.java: -------------------------------------------------------------------------------- 1 | class ShowUserDir { 2 | public static void main(String[] args) { 3 | System.out.println(System.getProperty("user.dir")); 4 | } 5 | } -------------------------------------------------------------------------------- /Chapter-19/src/StringConversions.java: -------------------------------------------------------------------------------- 1 | /* Convert an integer into binary, hexadecimal, 2 | and octal. 3 | */ 4 | 5 | class StringConversions { 6 | public static void main(String[] args) { 7 | int num = 19648; 8 | 9 | System.out.println(num + " in binary: " + 10 | Integer.toBinaryString(num)); 11 | 12 | System.out.println(num + " in octal: " + 13 | Integer.toOctalString(num)); 14 | 15 | System.out.println(num + " in hexadecimal: " + 16 | Integer.toHexString(num)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter-19/src/VerDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate Runtime.Version release counters. 2 | class VerDemo { 3 | public static void main(String[] args) { 4 | Runtime.Version ver = Runtime.version(); 5 | 6 | // Display individual counters. 7 | System.out.println("Feature release counter: " + ver.feature()); 8 | System.out.println("Interim release counter: " + ver.interim()); 9 | System.out.println("Update release counter: " + ver.update()); 10 | System.out.println("Patch release counter: " + ver.patch()); 11 | } 12 | } -------------------------------------------------------------------------------- /Chapter-20/src/ArrayDequeDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate ArrayDeque. 2 | 3 | import java.util.ArrayDeque; 4 | 5 | class ArrayDequeDemo { 6 | public static void main(String[] args) { 7 | // Create a tree set. 8 | ArrayDeque adq = new ArrayDeque(); 9 | 10 | // Use an ArrayDeque like a stack. 11 | adq.push("A"); 12 | adq.push("B"); 13 | adq.push("D"); 14 | adq.push("E"); 15 | adq.push("F"); 16 | 17 | System.out.print("Popping the stack: "); 18 | 19 | while (adq.peek() != null) 20 | System.out.print(adq.pop() + " "); 21 | 22 | System.out.println(); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter-20/src/ArrayListDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate ArrayList. 2 | 3 | import java.util.ArrayList; 4 | 5 | class ArrayListDemo { 6 | public static void main(String[] args) { 7 | // Create an array list. 8 | ArrayList al = new ArrayList(); 9 | 10 | System.out.println("Initial size of al: " + 11 | al.size()); 12 | 13 | // Add elements to the array list. 14 | al.add("C"); 15 | al.add("A"); 16 | al.add("E"); 17 | al.add("B"); 18 | al.add("D"); 19 | al.add("F"); 20 | al.add(1, "A2"); 21 | 22 | System.out.println("Size of al after additions: " + 23 | al.size()); 24 | 25 | // Display the array list. 26 | System.out.println("Contents of al: " + al); 27 | 28 | // Remove elements from the array list. 29 | al.remove("F"); 30 | al.remove(2); 31 | 32 | System.out.println("Size of al after deletions: " + 33 | al.size()); 34 | System.out.println("Contents of al: " + al); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter-20/src/ArrayListToArray.java: -------------------------------------------------------------------------------- 1 | // Convert an ArrayList into an array. 2 | 3 | import java.util.ArrayList; 4 | 5 | class ArrayListToArray { 6 | public static void main(String[] args) { 7 | // Create an array list. 8 | ArrayList al = new ArrayList(); 9 | 10 | // Add elements to the array list. 11 | al.add(1); 12 | al.add(2); 13 | al.add(3); 14 | al.add(4); 15 | 16 | System.out.println("Contents of al: " + al); 17 | 18 | // Get the array. 19 | Integer[] ia = new Integer[al.size()]; 20 | ia = al.toArray(ia); 21 | 22 | int sum = 0; 23 | 24 | // Sum the array. 25 | for (int i : ia) sum += i; 26 | 27 | System.out.println("Sum is: " + sum); 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter-20/src/CompDemo.java: -------------------------------------------------------------------------------- 1 | // Use a custom comparator. 2 | 3 | import java.util.Comparator; 4 | import java.util.TreeSet; 5 | 6 | // A reverse comparator for strings. 7 | class MyComp implements Comparator { 8 | public int compare(String aStr, String bStr) { 9 | 10 | // Reverse the comparison. 11 | return bStr.compareTo(aStr); 12 | } 13 | 14 | // No need to override equals or the default methods. 15 | } 16 | 17 | 18 | class CompDemo { 19 | public static void main(String[] args) { 20 | // Create a tree set. 21 | TreeSet ts = new TreeSet(new MyComp()); 22 | 23 | // Add elements to the tree set. 24 | ts.add("C"); 25 | ts.add("A"); 26 | ts.add("B"); 27 | ts.add("E"); 28 | ts.add("F"); 29 | ts.add("D"); 30 | 31 | // Display the elements. 32 | for (String element : ts) 33 | System.out.print(element + " "); 34 | 35 | System.out.println(); 36 | } 37 | } -------------------------------------------------------------------------------- /Chapter-20/src/CompDemo1.java: -------------------------------------------------------------------------------- 1 | // Use a custom comparator. 2 | 3 | import java.util.Comparator; 4 | import java.util.TreeSet; 5 | 6 | // A reverse comparator for strings. 7 | class MyComp2 implements Comparator { 8 | public int compare(String aStr, String bStr) { 9 | 10 | // Reverse the comparison. 11 | return aStr.compareTo(bStr); 12 | } 13 | 14 | // No need to override equals or the default methods. 15 | } 16 | 17 | 18 | class CompDemo1 { 19 | public static void main(String[] args) { 20 | // Create a tree set. 21 | TreeSet ts = new TreeSet(new MyComp2().reversed()); 22 | 23 | // Add elements to the tree set. 24 | ts.add("C"); 25 | ts.add("A"); 26 | ts.add("B"); 27 | ts.add("E"); 28 | ts.add("F"); 29 | ts.add("D"); 30 | 31 | // Display the elements. 32 | for (String element : ts) 33 | System.out.print(element + " "); 34 | 35 | System.out.println(); 36 | } 37 | } -------------------------------------------------------------------------------- /Chapter-20/src/CompDemo2.java: -------------------------------------------------------------------------------- 1 | // Use a lambda expression to create a reverse comparator. 2 | 3 | import java.util.TreeSet; 4 | 5 | class CompDemo2 { 6 | public static void main(String[] args) { 7 | 8 | // Pass a reversed comparator to TreeSet() via a 9 | // lambda expression. 10 | TreeSet ts = new TreeSet( 11 | (aStr, bStr) -> bStr.compareTo(aStr)); 12 | 13 | // Add elements to the tree set. 14 | ts.add("C"); 15 | ts.add("A"); 16 | ts.add("B"); 17 | ts.add("E"); 18 | ts.add("F"); 19 | ts.add("D"); 20 | 21 | // Display the elements. 22 | for (String element : ts) 23 | System.out.print(element + " "); 24 | 25 | System.out.println(); 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter-20/src/EnumSetDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.EnumSet; 2 | 3 | enum Day { 4 | SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 5 | } 6 | 7 | public class EnumSetDemo { 8 | 9 | public static void main(String[] args) { 10 | 11 | // Creating an EnumSet with some initial elements 12 | EnumSet weekdays = EnumSet.of(Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY); 13 | 14 | // Checking if an element is present 15 | System.out.println(weekdays.contains(Day.SUNDAY)); 16 | 17 | System.out.println(weekdays); 18 | 19 | System.out.println(EnumSet.allOf(Day.class)); 20 | 21 | System.out.println(EnumSet.range(Day.WEDNESDAY, Day.FRIDAY)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter-20/src/ForEachDemo.java: -------------------------------------------------------------------------------- 1 | // Use the for-each for loop to cycle through a collection. 2 | 3 | import java.util.ArrayList; 4 | 5 | class ForEachDemo { 6 | public static void main(String[] args) { 7 | // Create an array list for integers. 8 | ArrayList vals = new ArrayList(); 9 | 10 | // Add values to the array list. 11 | vals.add(1); 12 | vals.add(2); 13 | vals.add(3); 14 | vals.add(4); 15 | vals.add(5); 16 | 17 | // Use for loop to display the values. 18 | System.out.print("Original contents of vals: "); 19 | for (int v : vals) 20 | System.out.print(v + " "); 21 | System.out.println(); 22 | 23 | // Now, sum the values by using a for loop. 24 | int sum = 0; 25 | for (int v : vals) 26 | sum += v; 27 | 28 | System.out.println("Sum of values: " + sum); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter-20/src/HashSetDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate HashSet. 2 | 3 | import java.util.HashSet; 4 | 5 | class HashSetDemo { 6 | public static void main(String[] args) { 7 | // Create a hash set. 8 | HashSet hs = new HashSet(); 9 | 10 | // Add elements to the hash set. 11 | hs.add("Beta"); 12 | hs.add("Alpha"); 13 | hs.add("Eta"); 14 | hs.add("Gamma"); 15 | hs.add("Epsilon"); 16 | hs.add("Omega"); 17 | 18 | System.out.println(hs); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-20/src/LinkedHashSetDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate HashSet. 2 | 3 | import java.util.LinkedHashSet; 4 | 5 | class LinkedHashSetDemo { 6 | public static void main(String[] args) { 7 | // Create a hash set. 8 | LinkedHashSet hs = new LinkedHashSet(); 9 | 10 | // Add elements to the hash set. 11 | hs.add("Beta"); 12 | hs.add("Alpha"); 13 | hs.add("Eta"); 14 | hs.add("Gamma"); 15 | hs.add("Epsilon"); 16 | hs.add("Omega"); 17 | 18 | System.out.println(hs); 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter-20/src/PriorityQueueDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.PriorityQueue; 3 | 4 | 5 | public class PriorityQueueDemo { 6 | 7 | public static void main(String[] args) { 8 | PriorityQueue pq = new PriorityQueue<>(); 9 | pq.add(1); 10 | pq.add(2); 11 | pq.addAll(List.of(3, 4, 5)); 12 | 13 | while (!pq.isEmpty()) { 14 | System.out.println(pq.poll()); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-20/src/StackDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the Stack class. 2 | 3 | import java.util.EmptyStackException; 4 | import java.util.Stack; 5 | 6 | class StackDemo { 7 | static void showpush(Stack st, int a) { 8 | st.push(a); 9 | System.out.println("push(" + a + ")"); 10 | System.out.println("stack: " + st); 11 | } 12 | 13 | static void showpop(Stack st) { 14 | System.out.print("pop -> "); 15 | Integer a = st.pop(); 16 | System.out.println(a); 17 | System.out.println("stack: " + st); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Stack st = new Stack(); 22 | 23 | System.out.println("stack: " + st); 24 | showpush(st, 42); 25 | showpush(st, 66); 26 | showpush(st, 99); 27 | showpop(st); 28 | showpop(st); 29 | showpop(st); 30 | 31 | try { 32 | showpop(st); 33 | } catch (EmptyStackException e) { 34 | System.out.println("empty stack"); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Chapter-20/src/TreeSetDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate TreeSet. 2 | 3 | import java.util.TreeSet; 4 | 5 | class TreeSetDemo { 6 | public static void main(String[] args) { 7 | // Create a tree set. 8 | TreeSet ts = new TreeSet(); 9 | 10 | // Add elements to the tree set. 11 | ts.add("C"); 12 | ts.add("A"); 13 | ts.add("B"); 14 | ts.add("E"); 15 | ts.add("F"); 16 | ts.add("D"); 17 | 18 | System.out.println(ts); 19 | 20 | System.out.println(ts.subSet("C", "F")); 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-21/src/AvgNums.java: -------------------------------------------------------------------------------- 1 | // Use Scanner to compute an average of the values. 2 | 3 | import java.util.Scanner; 4 | 5 | class AvgNums { 6 | public static void main(String[] args) { 7 | Scanner conin = new Scanner(System.in); 8 | 9 | int count = 0; 10 | double sum = 0.0; 11 | 12 | System.out.println("Enter numbers to average."); 13 | 14 | // Read and sum numbers. 15 | while (conin.hasNext()) { 16 | if (conin.hasNextDouble()) { 17 | sum += conin.nextDouble(); 18 | count++; 19 | } else { 20 | String str = conin.next(); 21 | if (str.equals("done")) break; 22 | else { 23 | System.out.println("Data format error."); 24 | return; 25 | } 26 | } 27 | } 28 | conin.close(); 29 | System.out.println("Average is " + sum / count); 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter-21/src/BitSetDemo.java: -------------------------------------------------------------------------------- 1 | // BitSet Demonstration. 2 | 3 | import java.util.BitSet; 4 | 5 | class BitSetDemo { 6 | public static void main(String[] args) { 7 | BitSet bits1 = new BitSet(16); 8 | BitSet bits2 = new BitSet(16); 9 | 10 | // set some bits 11 | for (int i = 0; i < 16; i++) { 12 | if ((i % 2) == 0) bits1.set(i); 13 | if ((i % 5) != 0) bits2.set(i); 14 | } 15 | 16 | System.out.println("Initial pattern in bits1: "); 17 | System.out.println(bits1); 18 | System.out.println("\nInitial pattern in bits2: "); 19 | System.out.println(bits2); 20 | 21 | // AND bits 22 | bits2.and(bits1); 23 | System.out.println("\nbits2 AND bits1: "); 24 | System.out.println(bits2); 25 | 26 | // OR bits 27 | bits2.or(bits1); 28 | System.out.println("\nbits2 OR bits1: "); 29 | System.out.println(bits2); 30 | 31 | // XOR bits 32 | bits2.xor(bits1); 33 | System.out.println("\nbits2 XOR bits1: "); 34 | System.out.println(bits2); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter-21/src/CurDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate Currency. 2 | 3 | import java.util.Currency; 4 | import java.util.Locale; 5 | 6 | class CurDemo { 7 | public static void main(String[] args) { 8 | Currency c; 9 | 10 | c = Currency.getInstance(Locale.US); 11 | 12 | System.out.println("Symbol: " + c.getSymbol()); 13 | System.out.println("Default fractional digits: " + 14 | c.getDefaultFractionDigits()); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-21/src/DateDemo.java: -------------------------------------------------------------------------------- 1 | // Show date and time using only Date methods. 2 | 3 | import java.util.Date; 4 | 5 | class DateDemo { 6 | public static void main(String[] args) { 7 | // Instantiate a Date object 8 | Date date = new Date(); 9 | 10 | // display time and date using toString() 11 | System.out.println(date); 12 | 13 | // Display number of milliseconds since midnight, January 1, 1970 GMT 14 | long msec = date.getTime(); 15 | System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-21/src/FieldWidthDemo.java: -------------------------------------------------------------------------------- 1 | // Create a table of squares and cubes. 2 | 3 | import java.util.Formatter; 4 | 5 | class FieldWidthDemo { 6 | public static void main(String[] args) { 7 | Formatter fmt; 8 | 9 | for (int i = 1; i <= 10; i++) { 10 | fmt = new Formatter(); 11 | 12 | fmt.format("%4d %4d %4d", i, i * i, i * i * i); 13 | System.out.println(fmt); 14 | fmt.close(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter-21/src/FindInLineDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate findInLine(). 2 | 3 | import java.util.Scanner; 4 | 5 | class FindInLineDemo { 6 | public static void main(String[] args) { 7 | String instr = "Name: Tom Age: 28 ID: 77"; 8 | 9 | Scanner conin = new Scanner(instr); 10 | 11 | // Find and display age. 12 | conin.findInLine("Age:"); // find Age 13 | 14 | if (conin.hasNext()) 15 | System.out.println(conin.next()); 16 | else 17 | System.out.println("Error!"); 18 | 19 | conin.close(); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo.java: -------------------------------------------------------------------------------- 1 | // A very simple example that uses Formatter. 2 | 3 | import java.util.Formatter; 4 | 5 | class FormatDemo { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | fmt.format("Formatting %s is easy %d %f", "with Java", 10, 98.6); 10 | 11 | System.out.println(fmt); 12 | 13 | fmt.close(); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo2.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the %f and %e format specifiers. 2 | 3 | import java.util.Formatter; 4 | 5 | class FormatDemo2 { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | for (double i = 1.23; i < 1.0e+6; i *= 100) { 10 | fmt.format("%f %e ", i, i); 11 | System.out.println(fmt); 12 | } 13 | fmt.close(); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo3.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the %n and %% format specifiers. 2 | 3 | import java.util.Formatter; 4 | 5 | class FormatDemo3 { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | fmt.format("Copying file%nTransfer is %d%% complete", 88); 10 | System.out.println(fmt); 11 | fmt.close(); 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo4.java: -------------------------------------------------------------------------------- 1 | // Demonstrate a field-width specifier. 2 | 3 | import java.util.Formatter; 4 | 5 | class FormatDemo4 { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | fmt.format("|%f|%n|%12f|%n|%012f|", 10 | 10.12345, 10.12345, 10.12345); 11 | 12 | System.out.println(fmt); 13 | 14 | fmt.close(); 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo5.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the space format specifiers. 2 | 3 | import java.util.Formatter; 4 | 5 | class FormatDemo5 { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | fmt.format("% d", -100); 10 | System.out.println(fmt); 11 | fmt.close(); 12 | 13 | fmt = new Formatter(); 14 | fmt.format("% d", 100); 15 | System.out.println(fmt); 16 | fmt.close(); 17 | 18 | fmt = new Formatter(); 19 | fmt.format("% d", -200); 20 | System.out.println(fmt); 21 | fmt.close(); 22 | 23 | fmt = new Formatter(); 24 | fmt.format("% d", 200); 25 | System.out.println(fmt); 26 | fmt.close(); 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter-21/src/FormatDemo6.java: -------------------------------------------------------------------------------- 1 | // Use arguments indexes to simplify the 2 | // creation of a custom time and date format. 3 | 4 | import java.util.Calendar; 5 | import java.util.Formatter; 6 | 7 | class FormatDemo6 { 8 | public static void main(String[] args) { 9 | Formatter fmt = new Formatter(); 10 | Calendar cal = Calendar.getInstance(); 11 | 12 | fmt.format("Today is day %te of %. 2 | 3 | import java.util.Optional; 4 | 5 | class OptionalDemo { 6 | public static void main(String[] args) { 7 | 8 | Optional noVal = Optional.empty(); 9 | 10 | Optional hasVal = Optional.of("ABCDEFG"); 11 | 12 | if (noVal.isPresent()) System.out.println("This won't be displayed"); 13 | else System.out.println("noVal has no value"); 14 | 15 | if (hasVal.isPresent()) System.out.println("The string in hasVal is: " + 16 | hasVal.get()); 17 | 18 | String defStr = noVal.orElse("Default String"); 19 | System.out.println(defStr); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter-21/src/PrecisionDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate the precision modifier. 2 | 3 | import java.util.Formatter; 4 | 5 | class PrecisionDemo { 6 | public static void main(String[] args) { 7 | Formatter fmt = new Formatter(); 8 | 9 | // Format 4 decimal places. 10 | fmt.format("%.4f", 123.1234567); 11 | System.out.println(fmt); 12 | fmt.close(); 13 | 14 | // Format to 2 decimal places in a 16 character field. 15 | fmt = new Formatter(); 16 | fmt.format("%16.2e", 123.1234567); 17 | System.out.println(fmt); 18 | fmt.close(); 19 | 20 | // Display at most 15 characters in a string. 21 | fmt = new Formatter(); 22 | fmt.format("%.15s", "Formatting with Java is now easy."); 23 | System.out.println(fmt); 24 | fmt.close(); 25 | } 26 | } -------------------------------------------------------------------------------- /Chapter-21/src/RandDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate random Gaussian values. 2 | 3 | import java.util.Random; 4 | 5 | class RandDemo { 6 | public static void main(String[] args) { 7 | Random r = new Random(); 8 | double val; 9 | double sum = 0; 10 | int[] bell = new int[10]; 11 | 12 | for (int i = 0; i < 100; i++) { 13 | val = r.nextGaussian(); 14 | sum += val; 15 | double t = -2; 16 | for (int x = 0; x < 10; x++, t += 0.5) 17 | if (val < t) { 18 | bell[x]++; 19 | break; 20 | } 21 | } 22 | System.out.println("Average of values: " + 23 | (sum / 100)); 24 | 25 | // display bell curve, sideways 26 | for (int i = 0; i < 10; i++) { 27 | for (int x = bell[i]; x > 0; x--) 28 | System.out.print("*"); 29 | System.out.println(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Chapter-21/src/STDemo.java: -------------------------------------------------------------------------------- 1 | // Demonstrate StringTokenizer. 2 | 3 | import java.util.StringTokenizer; 4 | 5 | class STDemo { 6 | static String in = "title=Java: The Complete Reference;" + 7 | "author=Schildt;" + 8 | "publisher=McGraw Hill;" + 9 | "copyright=2022"; 10 | 11 | public static void main(String[] args) { 12 | StringTokenizer st = new StringTokenizer(in, "=;"); 13 | 14 | while (st.hasMoreTokens()) { 15 | String key = st.nextToken(); 16 | String val = st.nextToken(); 17 | System.out.println(key + "\t" + val); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter-21/src/SampleRB.java: -------------------------------------------------------------------------------- 1 | import java.util.ListResourceBundle; 2 | 3 | // Default version (English). 4 | public class SampleRB extends ListResourceBundle { 5 | protected Object[][] getContents() { 6 | Object[][] resources = new Object[3][2]; 7 | 8 | resources[0][0] = "title"; 9 | resources[0][1] = "My Program"; 10 | 11 | resources[1][0] = "StopText"; 12 | resources[1][1] = "Stop"; 13 | 14 | resources[2][0] = "StartText"; 15 | resources[2][1] = "Start"; 16 | 17 | return resources; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter-21/src/SampleRB_de.java: -------------------------------------------------------------------------------- 1 | import java.util.ListResourceBundle; 2 | 3 | // German version. 4 | public class SampleRB_de extends ListResourceBundle { 5 | protected Object[][] getContents() { 6 | Object[][] resources = new Object[3][2]; 7 | 8 | resources[0][0] = "title"; 9 | resources[0][1] = "Mein Programm"; 10 | 11 | resources[1][0] = "StopText"; 12 | resources[1][1] = "Anschlag"; 13 | 14 | resources[2][0] = "StartText"; 15 | resources[2][1] = "Anfang"; 16 | 17 | return resources; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter-21/src/TTest.java: -------------------------------------------------------------------------------- 1 | // Demonstrate Timer and TimerTask. 2 | 3 | import java.util.Timer; 4 | import java.util.TimerTask; 5 | 6 | class MyTimerTask extends TimerTask { 7 | public void run() { 8 | System.out.println("Timer task executed."); 9 | } 10 | } 11 | 12 | 13 | class TTest { 14 | public static void main(String[] args) { 15 | MyTimerTask myTask = new MyTimerTask(); 16 | Timer myTimer = new Timer(); 17 | 18 | /* Set an initial delay of 1 second, 19 | then repeat every half second. 20 | */ 21 | myTimer.schedule(myTask, 1000, 500); 22 | 23 | try { 24 | Thread.sleep(5000); 25 | } catch (InterruptedException exc) { 26 | } 27 | 28 | myTimer.cancel(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter-21/src/TimeDateFormat.java: -------------------------------------------------------------------------------- 1 | // Formatting time and date. 2 | 3 | import java.util.Calendar; 4 | import java.util.Formatter; 5 | 6 | class TimeDateFormat { 7 | public static void main(String[] args) { 8 | Formatter fmt = new Formatter(); 9 | Calendar cal = Calendar.getInstance(); 10 | 11 | // Display standard 12-hour time format. 12 | fmt.format("%tr", cal); 13 | System.out.println(fmt); 14 | fmt.close(); 15 | 16 | // Display complete time and date information. 17 | fmt = new Formatter(); 18 | fmt.format("%tc", cal); 19 | System.out.println(fmt); 20 | fmt.close(); 21 | 22 | // Display just hour and minute. 23 | fmt = new Formatter(); 24 | fmt.format("%tl:%tM", cal, cal); 25 | System.out.println(fmt); 26 | fmt.close(); 27 | 28 | // Display month by name and number. 29 | fmt = new Formatter(); 30 | fmt.format("%tB %tb %tm", cal, cal, cal); 31 | System.out.println(fmt); 32 | fmt.close(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Raju komati 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------