├── .gitignore ├── README.md └── src ├── chapter_01 ├── BeTheCompiler_A.java ├── BeTheCompiler_B.java ├── BeTheCompiler_C.java ├── BottleSong.java ├── CodeMagnet.java ├── DooBee.java ├── Mixed_Messages.java ├── PhraseOMatic.java └── PoolPuzzle.java ├── chapter_02 ├── BeTheCompiler_A.java ├── BeTheCompiler_B.java ├── CodeMagnets.java ├── PoolPuzzle.java └── SharpenYourPencil.java ├── chapter_03 ├── BeTheCompiler_A.java ├── BeTheCompiler_B.java ├── CodeMagnets.java ├── HeapQuiz.java └── Triangle.java ├── chapter_04 ├── BeTheCompiler_A.java ├── BeTheCompiler_B.java ├── Mixed_Messages.java └── PoolPuzzle.java ├── chapter_05 ├── CodeMagnets.java ├── Mixed_Messages.java ├── Output.java ├── SimpleStartup.java └── SimpleStartupTest.java ├── chapter_06 ├── Code_Magnets.java ├── GameHelper.java ├── Startup.java └── StartupBust.java ├── chapter_07 ├── BeTheCompiler.java ├── Mixed_Messages.java └── PoolPuzzle.java ├── chapter_08 ├── Nose.java └── Of76.java ├── chapter_09 ├── Animal.java ├── Duck.java └── GC.java ├── chapter_10 ├── Formatting.java ├── StaticFinal.java ├── StaticMethod.java ├── StaticSuper.java └── StaticVariable.java ├── chapter_11 ├── Jukebox1.java ├── Jukebox2_Comparable.java ├── Jukebox3_Comparator.java ├── Jukebox4_Lambda.java ├── Jukebox5_HashSet.java ├── Jukebox_TreeSet.java ├── MapExample.java ├── SortMountains.java └── TestTree.java ├── chapter_12 ├── CoffeeOrder.java ├── ForEachExample.java ├── JukeboxStream_Mapping.java ├── JukeboxStream_filter.java ├── StreamPuzzle.java ├── StreamWithLambdas.java ├── Stream_CollectAndCollectors.java └── TerminalOperations.java ├── chapter_13 ├── ExTestDrive.java ├── MiniMiniMusicApp.java ├── MiniMusicCmdLine.java └── TestExceptions.java ├── chapter_14_GUI ├── Animate.java ├── FirstGUI.java ├── InnerButton.java ├── SimpleAnimation.java ├── SimpleGui3.java └── TwoButtons.java ├── chapter_15_GUI ├── BorderLayoutExample.java ├── BoxLayoutExample.java ├── CheckBox.java ├── ClickCountGUI.java ├── FlowLayoutExample.java ├── List.java ├── LoginGUI.java ├── TextArea.java └── TextField.java ├── chapter_16 ├── DungeonGame.java ├── GameCharacter.java ├── GameSaverTest.java ├── Pond.java ├── QuizCard.java ├── QuizCardBuilder.java ├── QuizCardPlayer.java ├── Square.java └── WriteString.java ├── chapter_17 ├── DailyAdviceClient.java ├── DailyAdviceServer.java ├── PingingClient.java ├── SimpleChatClient.java ├── SimpleChatClientA.java └── SimpleChatServer.java └── chapter_18 ├── RyanAndMonicaTest.java └── TwoThreadsWriting.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /.idea/workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | 10 | /.idea/ 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Head First Java (Third Edition) 2 | This repository is about the Head First Java book exercise solution 3 | -------------------------------------------------------------------------------- /src/chapter_01/BeTheCompiler_A.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class BeTheCompiler_A { 4 | public static void main(String[] args){ 5 | int x = 1; 6 | while(x < 10){ 7 | x = x + 1; // we need to increment the value of x 8 | if (x > 3){ 9 | System.out.println("big x"); 10 | } 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/chapter_01/BeTheCompiler_B.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | // we need at least one class for compile a java program 4 | public class BeTheCompiler_B { 5 | public static void main(String[] args){ 6 | int x = 5; 7 | while(x > 1){ 8 | x = x -1; 9 | if (x < 3){ 10 | System.out.println("small x"); 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/chapter_01/BeTheCompiler_C.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class BeTheCompiler_C { 4 | // In java a program run the main() method is the starting point 5 | // from where compiler starts program execution. 6 | public static void main(String[] args) { 7 | int x = 5; 8 | while(x > 1){ 9 | x = x - 1; 10 | if (x<3){ 11 | System.out.println("small x"); 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/chapter_01/BottleSong.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class BottleSong { 4 | public static void main(String[] args){ 5 | int bottleNum = 10; 6 | String word = "bottles"; 7 | 8 | while(bottleNum > 0){ 9 | if (bottleNum == 1){ 10 | word = "bottle"; // singular, as in ONE bottle 11 | } 12 | if (bottleNum == 10){ 13 | System.out.println(bottleNum + " green "+ word + ", hanging on the wall"); 14 | } 15 | System.out.println(bottleNum + " green "+ word + ", hanging on the wall"); 16 | System.out.println("And if one green bottle should accidentally fall,"); 17 | bottleNum = bottleNum - 1; 18 | 19 | if (bottleNum > 0){ 20 | System.out.println("There will be "+bottleNum + " green "+ word + ", hanging on the wall"); 21 | } 22 | else System.out.println("There will be no green bottles, hanging on the wall"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter_01/CodeMagnet.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class CodeMagnet { 4 | // Head First Java Code Magnet Exercise Solution 5 | public static void main(String[] args){ 6 | int x = 3; 7 | while(x > 0){ 8 | if (x > 2){ 9 | System.out.print("a"); 10 | } 11 | x = x -1; 12 | System.out.print("-"); 13 | if (x == 2){ 14 | System.out.print("b c"); 15 | } 16 | if (x == 1 ){ 17 | System.out.print("d"); 18 | x = x - 1; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/chapter_01/DooBee.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class DooBee { 4 | public static void main(String[] args){ 5 | int x = 1; 6 | while(x < 5){ 7 | System.out.println("Doo"); 8 | System.out.println("Bee"); 9 | x = x + 1; 10 | } 11 | 12 | // it will be print in the last 13 | System.out.println("====================="); 14 | if (x == 5){ 15 | System.out.println("Do"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/chapter_01/Mixed_Messages.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class Mixed_Messages { 4 | public static void main(String[] args){ 5 | int x = 0; 6 | int y = 0; 7 | 8 | while (x < 5){ 9 | y = x - y; 10 | System.out.print(x + "" + y + " "); 11 | x = x +1; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/chapter_01/PhraseOMatic.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | import java.util.Random; 4 | 5 | public class PhraseOMatic { 6 | public static void main(String[] args){ 7 | 8 | // make three sets of words to choose from 9 | String[] wordListOne = {"agnostic", "opinionated", "voice activated", "haptically driven", "extensible", 10 | "reactive", "agent based", "functional", "AI enabled", "strongly typed"}; 11 | 12 | String[] wordListTwo = {"loosely coupled", "six sigma", "asynchronous", "event driven", "pub - sub", "IoT", 13 | "could", "microservices", "distributed ledger"}; 14 | 15 | String[] wordListThree = {"framework", "library", "DSL", "REST API", "repository", "pipeline", "service mesh", 16 | "architecture", "perspective", "design"}; 17 | 18 | // find out how many words are in each list 19 | int oneLength = wordListOne.length; 20 | int twoLength = wordListTwo.length; 21 | int threeLength = wordListThree.length; 22 | 23 | // generate three random numbers 24 | Random randomGenerator = new Random(); 25 | int rand1 = randomGenerator.nextInt(oneLength); 26 | int rand2 = randomGenerator.nextInt(twoLength); 27 | int rand3 = randomGenerator.nextInt(threeLength); 28 | 29 | // now build a phrase 30 | String phrase = wordListOne[rand1] +" "+ wordListTwo[rand2]+" "+ wordListThree[rand3]; 31 | System.out.println("What we need is a "+phrase); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/chapter_01/PoolPuzzle.java: -------------------------------------------------------------------------------- 1 | package chapter_01; 2 | 3 | public class PoolPuzzle { 4 | public static void main(String[] args) { 5 | int x = 0; 6 | // OutPut = a noise, annoys, an oyster 7 | while (x < 4){ 8 | System.out.print("a"); 9 | if (x < 1){ 10 | System.out.print(" "); 11 | } 12 | System.out.print("n"); 13 | 14 | if (x > 1){ 15 | System.out.print(" oyster"); 16 | x = x + 2; 17 | } 18 | if (x == 1){ 19 | System.out.print("noys"); 20 | } 21 | if (x < 1){ 22 | System.out.print("oise"); 23 | } 24 | System.out.println(); 25 | x = x + 1; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/chapter_02/BeTheCompiler_A.java: -------------------------------------------------------------------------------- 1 | package chapter_02; 2 | 3 | class StreamingSong{ 4 | String title; 5 | String artist; 6 | double duration; 7 | void play(){ 8 | System.out.println(title + " is playing"); 9 | } 10 | void playDetails(){ 11 | System.out.println("This is "+ title +" by "+ artist + " duration : "+ duration); 12 | } 13 | } 14 | 15 | public class BeTheCompiler_A { 16 | public static void main(String[] args) { 17 | // We must create an object for StreamingSong Class 18 | StreamingSong song = new StreamingSong(); 19 | song.artist = "The Beatles"; 20 | song.title = "Come Together"; 21 | song.duration = 3.43; 22 | song.play(); 23 | song.playDetails(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter_02/BeTheCompiler_B.java: -------------------------------------------------------------------------------- 1 | package chapter_02; 2 | 3 | class Episode{ 4 | int seriesNumber; 5 | int episodeNumber; 6 | 7 | void play(){ 8 | System.out.println("playing series "+ episodeNumber); 9 | } 10 | void skinIntro(){ 11 | System.out.println("Skipping intro ...."); 12 | } 13 | void skipToNext(){ 14 | System.out.println("Loading next episode..."); 15 | } 16 | } 17 | 18 | public class BeTheCompiler_B { 19 | public static void main(String[] args) { 20 | Episode episode = new Episode(); 21 | episode.seriesNumber = 4; 22 | episode.episodeNumber = 2; 23 | episode.play(); 24 | episode.skinIntro(); 25 | episode.skipToNext(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/chapter_02/CodeMagnets.java: -------------------------------------------------------------------------------- 1 | package chapter_02; 2 | 3 | class DrumKit{ 4 | boolean topHat = true; 5 | boolean snare = true; 6 | void playSnare(){ 7 | System.out.println("bang bang ba-bang"); 8 | } 9 | void playTopHat(){ 10 | System.out.println("ding ding da-ding"); 11 | } 12 | } 13 | 14 | public class CodeMagnets { 15 | public static void main(String[] args) { 16 | DrumKit d = new DrumKit(); 17 | d.playSnare(); 18 | d.playTopHat(); 19 | 20 | d.snare = false; 21 | d.topHat = false; 22 | 23 | if (d.snare){ 24 | d.playSnare(); 25 | } 26 | if (d.topHat){ 27 | d.playTopHat(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter_02/PoolPuzzle.java: -------------------------------------------------------------------------------- 1 | package chapter_02; 2 | 3 | class Echo{ 4 | int count = 0; 5 | void hello(){ 6 | System.out.println("helloooo..."); 7 | } 8 | } 9 | 10 | public class PoolPuzzle { 11 | public static void main(String[] args) { 12 | Echo e1 = new Echo(); 13 | Echo e2 = new Echo(); 14 | // Echo e2 = e1; for 24 output 15 | int x = 0; 16 | 17 | while (x < 4){ 18 | e1.hello(); 19 | e1.count = e1.count+1; 20 | if (x > 0){ 21 | e2.count = e2.count + 1; 22 | } 23 | if (x > 1){ 24 | e2.count = e2.count + e1.count; 25 | } 26 | x = x + 1; 27 | } 28 | System.out.println(e2.count); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter_02/SharpenYourPencil.java: -------------------------------------------------------------------------------- 1 | package chapter_02; 2 | 3 | public class SharpenYourPencil { 4 | public static void main(String[] args) { 5 | Television tv = new Television(); 6 | tv.model = "Sony Bravia"; 7 | tv.price = 1000; 8 | 9 | tv.powerOn(); 10 | tv.getDetails(); 11 | } 12 | } 13 | class Television{ 14 | String model; 15 | int price; 16 | void powerOn(){ 17 | System.out.println("Television is on....."); 18 | } 19 | void getDetails(){ 20 | System.out.println("Model : "+model); 21 | System.out.println("Price : "+price); 22 | } 23 | } -------------------------------------------------------------------------------- /src/chapter_03/BeTheCompiler_A.java: -------------------------------------------------------------------------------- 1 | package chapter_03; 2 | 3 | class Books{ 4 | String title; 5 | String author; 6 | } 7 | 8 | public class BeTheCompiler_A { 9 | public static void main(String[] args) { 10 | // Create myBook array and put some books into it 11 | Books[] myBook = new Books[3]; 12 | myBook[0] = new Books(); 13 | myBook[1] = new Books(); 14 | myBook[2] = new Books(); 15 | 16 | int x = 0; 17 | myBook[0].title = "The Grapes of Java"; 18 | myBook[1].title = "The Java Gatsby"; 19 | myBook[2].title = "The java Cookbook"; 20 | myBook[0].author = "boob"; 21 | myBook[1].author = "sue"; 22 | myBook[2].author = "ian"; 23 | 24 | while (x < 3){ 25 | System.out.print(myBook[x].title); 26 | System.out.print(" by "); 27 | System.out.println(myBook[x].author); 28 | x++; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/chapter_03/BeTheCompiler_B.java: -------------------------------------------------------------------------------- 1 | package chapter_03; 2 | class Hobbits{ 3 | String name; 4 | } 5 | public class BeTheCompiler_B { 6 | public static void main(String[] args) { 7 | Hobbits[] h = new Hobbits[3]; 8 | int z = -1; 9 | while (z < 2){ 10 | z = z + 1; 11 | h[z] = new Hobbits(); 12 | h[z].name = "bilbo"; 13 | if (z == 1){ 14 | h[z].name = "frido"; 15 | } 16 | if (z == 2){ 17 | h[z].name = "sam"; 18 | } 19 | 20 | System.out.print(h[z].name + " is a"); 21 | System.out.println("good Hobbit name"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/chapter_03/CodeMagnets.java: -------------------------------------------------------------------------------- 1 | package chapter_03; 2 | 3 | public class CodeMagnets { 4 | public static void main(String[] args) { 5 | String[] islands = new String[4]; 6 | islands[0] = "Bermuda"; 7 | islands[1] = "Fiji"; 8 | islands[2] = "Azores"; 9 | islands[3] = "Cozumel"; 10 | 11 | int[] index = new int[4]; 12 | index[0] = 1; 13 | index[1] = 3; 14 | index[2] = 0; 15 | index[3] = 2; 16 | 17 | int y = 0; 18 | int ref; 19 | while (y < 4){ 20 | System.out.print("island = "); 21 | ref = index[y]; 22 | y = y + 1; 23 | System.out.println(islands[ref]); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/chapter_03/HeapQuiz.java: -------------------------------------------------------------------------------- 1 | package chapter_03; 2 | 3 | public class HeapQuiz { 4 | int id = 0; 5 | 6 | public static void main(String[] args) { 7 | int x = 0; 8 | HeapQuiz[] hq = new HeapQuiz[5]; 9 | while (x < 3){ 10 | hq[x] = new HeapQuiz(); 11 | hq[x].id = x; 12 | x = x + 1; 13 | } 14 | 15 | hq[3] = hq[1]; 16 | hq[4] = hq[1]; 17 | hq[3] = null; 18 | hq[4] = hq[0]; 19 | hq[0] = null; 20 | hq[3] = hq[2]; 21 | hq[2] = null; 22 | 23 | System.out.println(hq[4].id); 24 | System.out.println(hq[3].id); 25 | System.out.println(hq[1].id); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/chapter_03/Triangle.java: -------------------------------------------------------------------------------- 1 | package chapter_03; 2 | 3 | public class Triangle { 4 | double area; 5 | int height; 6 | int length; 7 | 8 | public static void main(String[] args) { 9 | Triangle[] ta = new Triangle[4]; 10 | int x = 0; 11 | 12 | while (x < 4){ 13 | ta[x] = new Triangle(); 14 | ta[x].height = (x + 1) * 2; 15 | ta[x].length = x+4; 16 | ta[x].setArea(); 17 | 18 | System.out.print("triangle " + x +", area"); 19 | System.out.println(" = "+ta[x].area); 20 | x = x +1; 21 | } 22 | 23 | int y = x; 24 | Triangle t5 = ta[2]; 25 | ta[2].area = 343; 26 | System.out.print("y = "+ y); 27 | System.out.println(", t5 area = "+t5.area); 28 | 29 | } 30 | 31 | private void setArea(){ 32 | area = (height * length) /2; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/chapter_04/BeTheCompiler_A.java: -------------------------------------------------------------------------------- 1 | package chapter_04; 2 | 3 | class Xcopy{ 4 | public static void main(String[] args) { 5 | int orig = 42; 6 | Xcopy x = new Xcopy(); 7 | int y = x.go(orig); 8 | System.out.println(orig+ " " +y); 9 | } 10 | 11 | // Java is pass by value, which means pass by copy, 12 | // and the variable 'orig' is not changed by the go() method 13 | int go(int arg){ 14 | arg = arg * 2; 15 | return arg; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/chapter_04/BeTheCompiler_B.java: -------------------------------------------------------------------------------- 1 | package chapter_04; 2 | 3 | class Clock{ 4 | String time; 5 | 6 | void setTime(String t){ 7 | time = t; 8 | } 9 | 10 | //Getters must be return a value 11 | String getTime(){ 12 | return this.time; 13 | } 14 | } 15 | 16 | public class BeTheCompiler_B{ 17 | public static void main(String[] args) { 18 | Clock c = new Clock(); 19 | 20 | c.setTime("1245"); 21 | String tod = c.getTime(); 22 | System.out.println("time: " + tod); 23 | } 24 | } -------------------------------------------------------------------------------- /src/chapter_04/Mixed_Messages.java: -------------------------------------------------------------------------------- 1 | package chapter_04; 2 | 3 | public class Mixed_Messages { 4 | int counter = 0; 5 | 6 | public static void main(String[] args) { 7 | int count = 0; 8 | Mixed_Messages[] mixes = new Mixed_Messages[20]; 9 | int i = 0; 10 | while (i<20){ 11 | mixes[i] = new Mixed_Messages(); 12 | mixes[i].counter = mixes[i].counter+1; 13 | count = count + 1; 14 | count = count+mixes[i].maybeNew(i); 15 | i = i+ 1; 16 | } 17 | System.out.println(count + " "+ mixes[1].counter); 18 | } 19 | 20 | private int maybeNew(int index){ 21 | if (index < 5){ 22 | Mixed_Messages mix = new Mixed_Messages(); 23 | mix.counter = mix.counter +1; 24 | return 1; 25 | } 26 | return 0; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/chapter_04/PoolPuzzle.java: -------------------------------------------------------------------------------- 1 | package chapter_04; 2 | 3 | public class PoolPuzzle { 4 | public static void main(String[] args) { 5 | Values[] values = new Values[6]; 6 | int number = 1; 7 | int i = 0; 8 | while (i < 6){ 9 | values[i] = new Values(); 10 | values[i].intValue = number; 11 | 12 | number = number * 10; 13 | i = i + 1; 14 | } 15 | 16 | int result = 0; 17 | i = 6; 18 | while (i > 0){ 19 | i = i -1; 20 | result = result + values[i].doStuff(i); 21 | } 22 | System.out.println("result "+result); 23 | } 24 | } 25 | 26 | class Values{ 27 | int intValue; 28 | public int doStuff(int factor){ 29 | if (intValue > 100){ 30 | return intValue * factor; 31 | } 32 | else{ 33 | return intValue * (5 - factor); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/chapter_05/CodeMagnets.java: -------------------------------------------------------------------------------- 1 | package chapter_05; 2 | 3 | // Code Magnets exercise 4 | public class CodeMagnets { 5 | public static void main(String[] args) { 6 | for (int i = 0; i < 4; i++){ 7 | for (int j = 4; j > 2; j--){ 8 | System.out.println(i + " "+ j); 9 | } 10 | if (i == 1){ 11 | i++; 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/chapter_05/Mixed_Messages.java: -------------------------------------------------------------------------------- 1 | package chapter_05; 2 | 3 | public class Mixed_Messages { 4 | public static void main(String[] args) { 5 | int x = 0; 6 | int y = 30; 7 | for (int outer = 0; outer < 3; outer++){ 8 | for (int inner = 4; inner > 1; inner--){ 9 | x = x + 3; 10 | y = y - 2; 11 | if (x == 6){ 12 | break; 13 | } 14 | x = x + 3; 15 | } 16 | y = y - 2; 17 | } 18 | System.out.println(x + " "+ y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/chapter_05/Output.java: -------------------------------------------------------------------------------- 1 | package chapter_05; 2 | 3 | // Be the JVM exercise 4 | public class Output { 5 | public static void main(String[] args) { 6 | go(); 7 | } 8 | 9 | private static void go(){ 10 | int value = 7; 11 | for (int i = 1; i < 8; i++){ 12 | value++; 13 | if (i > 4){ 14 | System.out.print(++value + " "); 15 | } 16 | if (value > 14){ 17 | System.out.println("i = " + i); 18 | break; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/chapter_05/SimpleStartup.java: -------------------------------------------------------------------------------- 1 | package chapter_05; 2 | 3 | public class SimpleStartup { 4 | private int[] locationCells; 5 | private int numOfHits = 0; 6 | 7 | public void setLocationCells(int[] locationCells){ 8 | this.locationCells = locationCells; 9 | } 10 | 11 | public String checkYourself(int guess){ 12 | String result = "miss"; 13 | for (int cell : locationCells){ 14 | if (guess == cell){ 15 | result = "hit"; 16 | numOfHits++; 17 | break; 18 | } 19 | } 20 | 21 | if (numOfHits == locationCells.length){ 22 | result = "kill"; 23 | } 24 | 25 | System.out.println(result); 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/chapter_05/SimpleStartupTest.java: -------------------------------------------------------------------------------- 1 | package chapter_05; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SimpleStartupTest { 6 | public static void main(String[] args){ 7 | int numOfGuess = 0; 8 | SimpleStartup theStartup = new SimpleStartup(); 9 | 10 | int random = (int)(Math.random() * 5); 11 | 12 | int [] locations = {random, random + 1, random + 2}; 13 | theStartup.setLocationCells(locations); 14 | 15 | boolean isAlive = true; 16 | 17 | while (isAlive){ 18 | Scanner input = new Scanner(System.in); 19 | System.out.println("enter a number : "); 20 | int guess = input.nextInt(); 21 | 22 | String result = theStartup.checkYourself(guess); 23 | numOfGuess++; 24 | 25 | if (result.equals("kill")){ 26 | isAlive = false; 27 | System.out.println("You took "+ numOfGuess + " guesses"); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/chapter_06/Code_Magnets.java: -------------------------------------------------------------------------------- 1 | package chapter_06; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Code_Magnets { 6 | public static void main(String[] args) { 7 | ArrayList a = new ArrayList<>(); 8 | a.add(0,"zero"); 9 | a.add(1,"one"); 10 | a.add(2,"two"); 11 | a.add(3,"three"); 12 | printList(a); 13 | 14 | if (a.contains("three")){ 15 | a.add("four"); 16 | } 17 | a.remove(2); 18 | printList(a); 19 | 20 | if (a.indexOf("four") != 4){ 21 | a.add(4,"4.2"); 22 | } 23 | printList(a); 24 | 25 | if (a.contains("two")){ 26 | a.add("2.2"); 27 | } 28 | printList(a); 29 | 30 | } 31 | 32 | private static void printList(ArrayList arrayList) { 33 | for (String element: arrayList){ 34 | System.out.print(element+" "); 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/chapter_06/GameHelper.java: -------------------------------------------------------------------------------- 1 | package chapter_06; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Random; 6 | import java.util.Scanner; 7 | 8 | public class GameHelper { 9 | private static final String ALPHABET = "abcdefg"; 10 | private static final int GRID_LENGTH = 7; 11 | private static final int GRID_SIZE = 49; 12 | private static final int MAX_ATTEMPTS = 200; 13 | 14 | static final int HORIZONTAL_INCREMENT = 1; // A better way to represent these two 15 | static final int VERTICAL_INCREMENT = GRID_LENGTH; // things is an enum (see Appendix B) 16 | 17 | private final int[] grid = new int[GRID_SIZE]; 18 | private final Random random = new Random(); 19 | 20 | private int startupCount = 0; 21 | 22 | public String getUserInput(String prompt) { 23 | System.out.print(prompt + ": "); 24 | Scanner scanner = new Scanner(System.in); 25 | return scanner.nextLine().toLowerCase(); 26 | } //end getUserInput 27 | 28 | public ArrayList placeStartup(int startupSize) { 29 | // holds index to grid (0 - 48) 30 | int[] startupCoords = new int[startupSize]; // current candidate co-ordinates 31 | int attempts = 0; // current attempts counter 32 | boolean success = false; // flag = found a good location? 33 | 34 | startupCount++; // nth Startup to place 35 | int increment = getIncrement(); // alternate vert & horiz alignment 36 | 37 | while (!success & attempts++ < MAX_ATTEMPTS) { // main search loop 38 | int location = random.nextInt(GRID_SIZE); // get random starting point 39 | 40 | for (int i = 0; i < startupCoords.length; i++) { // create array of proposed coords 41 | startupCoords[i] = location; // put current location in array 42 | location += increment; // calculate the next location 43 | } 44 | System.out.println("Trying: " + Arrays.toString(startupCoords)); 45 | 46 | if (startupFits(startupCoords, increment)) { // startup fits on the grid? 47 | success = coordsAvailable(startupCoords); // ...and locations aren't taken? 48 | } // end loop 49 | } // end while 50 | 51 | savePositionToGrid(startupCoords); // coords passed checks, save 52 | ArrayList alphaCells = convertCoordsToAlphaFormat(startupCoords); 53 | System.out.println("Placed at: "+ alphaCells); 54 | return alphaCells; 55 | } //end placeStartup 56 | 57 | boolean startupFits(int[] startupCoords, int increment) { 58 | int finalLocation = startupCoords[startupCoords.length - 1]; 59 | if (increment == HORIZONTAL_INCREMENT) { 60 | // check end is on same row as start 61 | return calcRowFromIndex(startupCoords[0]) == calcRowFromIndex(finalLocation); 62 | } else { 63 | return finalLocation < GRID_SIZE; // check end isn't off the bottom 64 | } 65 | } //end startupFits 66 | 67 | boolean coordsAvailable(int[] startupCoords) { 68 | for (int coord : startupCoords) { // check all potential positions 69 | if (grid[coord] != 0) { // this position already taken 70 | System.out.println("position: " + coord + " already taken."); 71 | return false; // NO success 72 | } 73 | } 74 | return true; // there were no clashes, yay! 75 | } //end coordsAvailable 76 | 77 | void savePositionToGrid(int[] startupCoords) { 78 | for (int index : startupCoords) { 79 | grid[index] = 1; // mark grid position as 'used' 80 | } 81 | } //end savePositionToGrid 82 | 83 | private ArrayList convertCoordsToAlphaFormat(int[] startupCoords) { 84 | ArrayList alphaCells = new ArrayList<>(); 85 | for (int index : startupCoords) { // for each grid coordinate 86 | String alphaCoords = getAlphaCoordsFromIndex(index); // turn it into an "a0" style 87 | alphaCells.add(alphaCoords); // add to a list 88 | } 89 | return alphaCells; // return the "a0"-style coords 90 | } // end convertCoordsToAlphaFormat 91 | 92 | String getAlphaCoordsFromIndex(int index) { 93 | int row = calcRowFromIndex(index); // get row value 94 | int column = index % GRID_LENGTH; // get numeric column value 95 | 96 | String letter = ALPHABET.substring(column, column + 1); // convert to letter 97 | return letter + row; 98 | } // end getAlphaCoordsFromIndex 99 | 100 | private int calcRowFromIndex(int index) { 101 | return index / GRID_LENGTH; 102 | } // end calcRowFromIndex 103 | 104 | private int getIncrement() { 105 | if (startupCount % 2 == 0) { // if EVEN Startup 106 | return HORIZONTAL_INCREMENT; // place horizontally 107 | } else { // else ODD 108 | return VERTICAL_INCREMENT; // place vertically 109 | } 110 | } //end getIncrement 111 | } //end class 112 | -------------------------------------------------------------------------------- /src/chapter_06/Startup.java: -------------------------------------------------------------------------------- 1 | package chapter_06; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Startup { 6 | private ArrayList locationCells; 7 | private String name; 8 | 9 | public void setLocationCells(ArrayList locationCells){ 10 | this.locationCells = locationCells; 11 | } 12 | 13 | public void setName(String name){ 14 | this.name = name; 15 | } 16 | 17 | public String checkYourself(String userInput){ 18 | String result = "miss"; 19 | int index = locationCells.indexOf(userInput); 20 | 21 | if (index>=0){ 22 | locationCells.remove(index); 23 | if (locationCells.isEmpty()){ 24 | result = "kill"; 25 | } 26 | else result = "hit"; 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter_06/StartupBust.java: -------------------------------------------------------------------------------- 1 | package chapter_06; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class StartupBust { 6 | private final GameHelper helper = new GameHelper(); 7 | private final ArrayList startups = new ArrayList<>(); 8 | private int numberOfGuess = 0; 9 | 10 | private void setUpGame(){ 11 | // first make some Startups and give them locations 12 | Startup one = new Startup(); 13 | one.setName("poniez"); 14 | 15 | Startup two = new Startup(); 16 | two.setName("hacqi"); 17 | 18 | Startup three = new Startup(); 19 | three.setName("cabista"); 20 | startups.add(one); 21 | startups.add(two); 22 | startups.add(three); 23 | 24 | System.out.println("Your goal is to sink three Startups."); 25 | System.out.println("poniez, hacqi, cabista"); 26 | System.out.println("Try to sink them all in the fewest number of guesses"); 27 | 28 | for (Startup startup : startups){ 29 | ArrayList newLocations = helper.placeStartup(3); 30 | startup.setLocationCells(newLocations); 31 | } 32 | } 33 | 34 | 35 | private void startPlaying(){ 36 | while (!startups.isEmpty()){ 37 | String userGuess = helper.getUserInput("Enter a guess"); 38 | checkUserGuess(userGuess); 39 | } 40 | finishGame(); 41 | } 42 | 43 | 44 | private void checkUserGuess(String userGuess){ 45 | numberOfGuess++; 46 | String result = "miss"; 47 | 48 | for (Startup startupToTest : startups){ 49 | result = startupToTest.checkYourself(userGuess); 50 | 51 | if (result.equals("hit")){ 52 | break; 53 | } 54 | if (result.equals("kill")){ 55 | startups.remove(startupToTest); 56 | break; 57 | } 58 | } 59 | System.out.println(result); 60 | } 61 | 62 | private void finishGame(){ 63 | System.out.println("All Starups are dead! Your stock is now worthless"); 64 | if (numberOfGuess<= 18){ 65 | System.out.println("It only took you "+ numberOfGuess + " guesses."); 66 | System.out.println("You got out before your options sank"); 67 | } 68 | else{ 69 | System.out.println("Took you long enough. "+numberOfGuess + " guesses."); 70 | System.out.println("Fish are dancing with your options"); 71 | } 72 | } 73 | 74 | public static void main(String[] args){ 75 | StartupBust game = new StartupBust(); 76 | game.setUpGame(); 77 | game.startPlaying(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/chapter_07/BeTheCompiler.java: -------------------------------------------------------------------------------- 1 | package chapter_07; 2 | 3 | // superclass 4 | class Monster{ 5 | boolean frighten (int d){ 6 | System.out.println("arrrgh"); 7 | return true; 8 | } 9 | } 10 | 11 | // subclass 12 | class Vampire extends Monster{ 13 | boolean frighten(int x){ 14 | System.out.println("a bite"); 15 | return true; 16 | } 17 | } 18 | 19 | // subclass 20 | class Dragon extends Monster{ 21 | boolean frighten(int degree){ 22 | System.out.println("breathe fire"); 23 | return true; 24 | } 25 | } 26 | 27 | // MonsterTestDrive 28 | public class BeTheCompiler { 29 | public static void main(String[] args) { 30 | Monster[] monsters = new Monster[3]; 31 | monsters[0] = new Vampire(); 32 | monsters[1] = new Dragon(); 33 | monsters[2] = new Monster(); 34 | 35 | for (int i = 0; i< monsters.length; i++){ 36 | monsters[i].frighten(i); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/chapter_07/Mixed_Messages.java: -------------------------------------------------------------------------------- 1 | package chapter_07; 2 | class A{ 3 | int ivar = 7; 4 | 5 | void m1(){ 6 | System.out.print("A's m1, "); 7 | } 8 | 9 | void m2(){ 10 | System.out.print("A's m2, "); 11 | } 12 | 13 | void m3(){ 14 | System.out.print("A's m3," ); 15 | } 16 | } 17 | 18 | class B extends A{ 19 | @Override 20 | void m1() { 21 | System.out.print("B's m1, "); 22 | } 23 | } 24 | 25 | class C extends B{ 26 | @Override 27 | void m3() { 28 | System.out.print("C's m3, "+ (ivar + 6)); 29 | } 30 | } 31 | public class Mixed_Messages { 32 | public static void main(String[] args) { 33 | A a = new A(); 34 | B b = new B(); 35 | C c = new C(); 36 | A a2 = new C(); 37 | 38 | b.m1(); 39 | c.m2(); 40 | a.m3(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/chapter_07/PoolPuzzle.java: -------------------------------------------------------------------------------- 1 | package chapter_07; 2 | 3 | // superclass 4 | class Boat{ 5 | private int length; 6 | 7 | public void setLength(int len){ 8 | length = len; 9 | } 10 | 11 | public int getLength(){ 12 | return this.length; 13 | } 14 | 15 | public void move(){ 16 | System.out.print("drift "); 17 | } 18 | } 19 | 20 | // subclass 21 | class Rowboat extends Boat{ 22 | public void rowTheBoat(){ 23 | System.out.print("stroke natasha"); 24 | } 25 | } 26 | 27 | // subclass 28 | class Sailboat extends Boat{ 29 | public void move(){ 30 | System.out.print(" hoist sail"); 31 | } 32 | } 33 | 34 | // main class or 35 | public class PoolPuzzle { 36 | public static void main(String[] args) { 37 | Boat b1 = new Boat(); 38 | Sailboat b2 = new Sailboat(); 39 | Rowboat b3 = new Rowboat(); 40 | b2.setLength(32); 41 | 42 | b1.move(); 43 | b3.move(); 44 | b2.move(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/chapter_08/Nose.java: -------------------------------------------------------------------------------- 1 | package chapter_08; 2 | 3 | // Pool Puzzle Exercise 4 | 5 | public interface Nose { 6 | int iMethod(); 7 | } 8 | 9 | abstract class Picasso implements Nose{ 10 | @Override 11 | public int iMethod() { 12 | return 7; 13 | } 14 | } 15 | 16 | class Clowns extends Picasso{ 17 | 18 | } 19 | 20 | class Acts extends Picasso{ 21 | @Override 22 | public int iMethod() { 23 | return 5; 24 | } 25 | } -------------------------------------------------------------------------------- /src/chapter_08/Of76.java: -------------------------------------------------------------------------------- 1 | package chapter_08; 2 | 3 | // Pool Puzzle Test Class 4 | 5 | public class Of76 extends Clowns{ 6 | public static void main(String[] args){ 7 | Nose[] i = new Nose[3]; 8 | i[0] = new Acts();; 9 | i[1] = new Clowns(); 10 | i[2] = new Of76(); 11 | 12 | for (int x = 0; x<3; x++){ 13 | System.out.println(i[x].iMethod()+ " "+i[x].getClass()); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/chapter_09/Animal.java: -------------------------------------------------------------------------------- 1 | package chapter_09; 2 | 3 | public class Animal { 4 | private String name; 5 | 6 | public String getName(){ 7 | return this.name; 8 | } 9 | public Animal(String name){ 10 | this.name = name; 11 | } 12 | } 13 | 14 | class Hippo extends Animal{ 15 | public Hippo(String name){ 16 | super(name); // Passing parameter to super class constructor 17 | } 18 | } 19 | 20 | class TestHippo{ 21 | public static void main(String[] args) { 22 | Hippo h = new Hippo("Buffy"); 23 | System.out.println(h.getName()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter_09/Duck.java: -------------------------------------------------------------------------------- 1 | package chapter_09; 2 | 3 | public class Duck { 4 | int size; 5 | public Duck(int duckSize) { 6 | System.out.println("Quack"); 7 | size = duckSize; 8 | System.out.println("size is " + size); 9 | } 10 | 11 | public Duck(){ 12 | size = 27; 13 | System.out.println("size is "+size); 14 | } 15 | } 16 | 17 | class UseADuck{ 18 | public static void main(String[] args) { 19 | Duck d = new Duck(); // Duck() this calls the Duck constructor 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/chapter_09/GC.java: -------------------------------------------------------------------------------- 1 | package chapter_09; 2 | 3 | public class GC { 4 | public static GC doStuff(){ 5 | GC newGC = new GC(); 6 | doStuff2(newGC); 7 | return newGC; 8 | } 9 | 10 | public static void main(String[] args) { 11 | GC gc1; 12 | GC gc2 = new GC(); 13 | GC gc3 = new GC(); 14 | GC gc4 = gc3; 15 | gc1 = doStuff(); 16 | 17 | gc1 = null; //Object gc1 is now garbage 18 | gc4 = null; //Object gc4 is now garbage 19 | 20 | } 21 | 22 | public static void doStuff2(GC copyGC){ 23 | GC localGC = copyGC; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter_10/Formatting.java: -------------------------------------------------------------------------------- 1 | package chapter_10; 2 | 3 | public class Formatting { 4 | public static void main(String[] args) { 5 | // Decimal Formatting 6 | System.out.println("Decimal Formatting : "); 7 | int a = 13432423; 8 | String s1 = String.format("%,d",a); 9 | System.out.println(s1); 10 | 11 | System.out.println(); 12 | 13 | // Float Formatting 14 | System.out.println("Float Formatting : "); 15 | double b = 4234234.5345235; 16 | String s2 = String.format("%,.2f",b); 17 | System.out.println(s2); 18 | 19 | System.out.println(); 20 | 21 | // Multiple Formatting 22 | System.out.println("Multiple Formatting : "); 23 | int one = 2053454235; 24 | double two = 534523535.23452; 25 | System.out.printf("The rank is %,d out of %,.2f",one,two); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/chapter_10/StaticFinal.java: -------------------------------------------------------------------------------- 1 | package chapter_10; 2 | 3 | public class StaticFinal { 4 | static final double PI = 3.1416; 5 | static final double VAL; 6 | 7 | // static final variable also initialized in static block{} 8 | static { 9 | VAL = Math.random(); 10 | } 11 | 12 | public static void main(String[] args) { 13 | System.out.println("The value of PI : " + StaticFinal.PI); 14 | System.out.println("Random number : " + StaticFinal.VAL); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/chapter_10/StaticMethod.java: -------------------------------------------------------------------------------- 1 | package chapter_10; 2 | 3 | public class StaticMethod { 4 | 5 | public static int calculateSum (int a, int b){ 6 | return a + b; 7 | } 8 | } 9 | 10 | class StaticMethodTest { 11 | public static void main(String[] args) { 12 | int a = 10; 13 | int b = 15; 14 | 15 | // calling the method with className rather than a reference variable 16 | int result = StaticMethod.calculateSum(a,b); 17 | System.out.println(result); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/chapter_10/StaticSuper.java: -------------------------------------------------------------------------------- 1 | package chapter_10; 2 | 3 | public class StaticSuper { 4 | static { 5 | System.out.println("super static block"); 6 | } 7 | 8 | StaticSuper(){ 9 | System.out.println("super constructor"); 10 | } 11 | } 12 | 13 | class StaticTests extends StaticSuper{ 14 | static int rand; 15 | 16 | static { 17 | rand = (int) (Math.random() * 6); 18 | System.out.println("static block "+ rand); 19 | } 20 | 21 | StaticTests(){ 22 | System.out.println("constructor"); 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println("in main"); 27 | StaticTests st = new StaticTests(); 28 | 29 | /* 30 | The Output will be 31 | super static block 32 | static block (random number) 33 | in main 34 | super constructor 35 | constructor 36 | */ 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/chapter_10/StaticVariable.java: -------------------------------------------------------------------------------- 1 | package chapter_10; 2 | class Duck { 3 | private static int duckCount; // static variable is "one value per class" 4 | 5 | public Duck(){ 6 | duckCount++; 7 | } 8 | 9 | public int getCount(){ 10 | return duckCount; 11 | } 12 | } 13 | 14 | public class StaticVariable { 15 | public static void main(String[] args) { 16 | Duck duck1 = new Duck(); // count is now 1 in duck1 instance 17 | System.out.println("Number of count: " + duck1.getCount()); 18 | 19 | Duck duck2 = new Duck(); // count is now 2 in duck2 instance 20 | System.out.println("Number of count: " + duck2.getCount()); 21 | 22 | Duck duck3 = new Duck(); // count is now 3 in duck3 instance 23 | System.out.println("Number of count: " + duck3.getCount()); 24 | 25 | Duck duck4 = new Duck(); // count is now 4 in duck4 instance 26 | System.out.println("Number of count: " + duck4.getCount()); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox1.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class Jukebox1 { 8 | public static void main(String[] args) { 9 | new Jukebox1().go(); 10 | } 11 | 12 | public void go(){ 13 | List songList = new ArrayList<>(MockSongs.getSongStrings()); 14 | System.out.println(songList); 15 | //Sort in Alphabetic Order 16 | Collections.sort(songList); 17 | System.out.println(songList); 18 | } 19 | } 20 | 21 | class MockSongs{ 22 | public static List getSongStrings(){ 23 | return List.of("somersault", "cassidy", "$10", "havana", "Cassidy", "50 Ways"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox2_Comparable.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | class SongV2 implements Comparable{ 8 | private String title; 9 | private String artist; 10 | private int bpm; 11 | 12 | public SongV2(String title, String artist, int bpm) { 13 | this.title = title; 14 | this.artist = artist; 15 | this.bpm = bpm; 16 | } 17 | 18 | public String getTitle() { 19 | return title; 20 | } 21 | 22 | public String getArtist() { 23 | return artist; 24 | } 25 | 26 | public int getBpm() { 27 | return bpm; 28 | } 29 | 30 | // Method for sorting according to title 31 | @Override 32 | public int compareTo(SongV2 song) { 33 | return title.compareTo(song.getTitle()); 34 | } 35 | } 36 | 37 | 38 | class MockSongs2{ 39 | public static List getSongStrings(){ 40 | return List.of("somersault", "cassidy", "$10", "havana", "Cassidy", "50 Ways"); 41 | } 42 | 43 | public static List getSongsV2(){ 44 | List songs = new ArrayList<>(); 45 | songs.add(new SongV2("somersault", "zero 7", 147)); 46 | songs.add(new SongV2("cassidy", "grateful dead", 158)); 47 | songs.add(new SongV2("$10", "hitchhiker", 140)); 48 | 49 | 50 | songs.add(new SongV2("havana", "cabello", 105)); 51 | songs.add(new SongV2("Cassidy", "grateful", 105)); 52 | songs.add(new SongV2("50 Ways", "simon", 102)); 53 | return songs; 54 | } 55 | } 56 | 57 | public class Jukebox2_Comparable { 58 | public static void main(String[] args) { 59 | new Jukebox2_Comparable().go(); 60 | } 61 | 62 | public void go(){ 63 | List songList = new ArrayList<>(MockSongs2.getSongsV2()); 64 | System.out.println(songList); 65 | Collections.sort(songList); // this will not compile!! if we don't implement Comparable interface 66 | // and not override the compareTo() method 67 | 68 | //Iterating over the songList 69 | for (SongV2 songV2 : songList) { 70 | System.out.println("Title: " + songV2.getTitle() + ", Artist: " + 71 | songV2.getArtist() + ", BPM: " + 72 | songV2.getBpm()); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox3_Comparator.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | 7 | class SongV3{ 8 | private String title; 9 | private String artist; 10 | private int bpm; 11 | 12 | public SongV3(String title, String artist, int bpm) { 13 | this.title = title; 14 | this.artist = artist; 15 | this.bpm = bpm; 16 | } 17 | 18 | public String getTitle() { 19 | return title; 20 | } 21 | 22 | public String getArtist() { 23 | return artist; 24 | } 25 | 26 | public int getBpm() { 27 | return bpm; 28 | } 29 | 30 | } 31 | 32 | class MockSongs3{ 33 | public static List getSongStringsV3(){ 34 | List songs = new ArrayList<>(); 35 | 36 | songs.add(new SongV3("somersault", "zero 7", 147)); 37 | songs.add(new SongV3("cassidy", "grateful dead", 158)); 38 | songs.add(new SongV3("$10", "hitchhiker", 140)); 39 | return songs; 40 | } 41 | 42 | } 43 | 44 | class ArtistCompare implements Comparator{ 45 | @Override 46 | public int compare(SongV3 o1, SongV3 o2) { 47 | return o1.getArtist().compareTo(o2.getArtist()); 48 | } 49 | } 50 | 51 | public class Jukebox3_Comparator { 52 | public static void main(String[] args){ 53 | new Jukebox3_Comparator().go(); 54 | } 55 | 56 | 57 | public void go(){ 58 | List songList = new ArrayList<>(MockSongs3.getSongStringsV3()); 59 | System.out.println(songList); 60 | 61 | ArtistCompare artistCompare = new ArtistCompare(); 62 | songList.sort(artistCompare); // another way of sorting 63 | 64 | //Iterating over the songList 65 | for (SongV3 songV3 : songList) { 66 | System.out.println("Title: " + songV3.getTitle() + ", Artist: " + 67 | songV3.getArtist() + ", BPM: " + 68 | songV3.getBpm()); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox4_Lambda.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class SongV4{ 7 | private String title; 8 | private String artist; 9 | private int bpm; 10 | 11 | public SongV4(String title, String artist, int bpm) { 12 | this.title = title; 13 | this.artist = artist; 14 | this.bpm = bpm; 15 | } 16 | 17 | public String getTitle() { 18 | return title; 19 | } 20 | 21 | public String getArtist() { 22 | return artist; 23 | } 24 | 25 | public int getBpm() { 26 | return bpm; 27 | } 28 | 29 | } 30 | 31 | class MockSongs4{ 32 | public static List getSongString(){ 33 | List songs = new ArrayList<>(); 34 | songs.add(new SongV4("somersault", "zero 7", 147)); 35 | songs.add(new SongV4("cassidy", "grateful dead", 158)); 36 | songs.add(new SongV4("$10", "hitchhiker", 140)); 37 | 38 | return songs; 39 | } 40 | } 41 | public class Jukebox4_Lambda { 42 | public static void main(String[] args) { 43 | new Jukebox4_Lambda().go(); 44 | } 45 | 46 | public void go(){ 47 | List songList = MockSongs4.getSongString(); 48 | 49 | //Sort songList according to title using Lambda Expression 50 | //songList.sort((a, b)-> a.getTitle().compareTo(b.getTitle())); //Method - 1 51 | songList.sort((song1, song2) -> song1.getTitle().compareTo(song2.getTitle())); //Method - 2 52 | 53 | //Iterating over the songList 54 | System.out.println("Sorting according to title: "); 55 | for (SongV4 songV4 : songList) { 56 | System.out.println("Title: " + songV4.getTitle() + ", Artist: " + songV4.getArtist() + ", BPM: " + songV4.getBpm()); 57 | } 58 | System.out.println(); 59 | 60 | //Sort songList according artist using Lambda Expression 61 | //Collections.sort(songList, (song1, song2)-> song1.getArtist().compareTo(song2.getArtist())); //Method - 1 62 | songList.sort((song1, song2)-> song1.getArtist().compareTo(song2.getArtist())); //Method - 1 63 | 64 | //Iterating over the songList 65 | System.out.println("Sorting according to artist: "); 66 | for (SongV4 songV4 : songList) { 67 | System.out.println("Title: " + songV4.getTitle() + ", Artist: " + songV4.getArtist() + ", BPM: " + songV4.getBpm()); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox5_HashSet.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | class SongV5{ 9 | private String title; 10 | private String artist; 11 | private int bpm; 12 | 13 | public SongV5(String title, String artist, int bpm) { 14 | this.title = title; 15 | this.artist = artist; 16 | this.bpm = bpm; 17 | } 18 | 19 | public String getTitle() { 20 | return title; 21 | } 22 | 23 | public String getArtist() { 24 | return artist; 25 | } 26 | 27 | public int getBpm() { 28 | return bpm; 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return this.title; 34 | } 35 | 36 | //For avoiding duplicate song title 37 | @Override 38 | public boolean equals(Object aSong) { 39 | SongV5 other = (SongV5) aSong; 40 | return title.equals(other.getTitle()); 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | return title.hashCode(); 46 | } 47 | } 48 | 49 | class MockSongs5{ 50 | public static List getSongString(){ 51 | List songs = new ArrayList<>(); 52 | songs.add(new SongV5("somersault", "zero 7", 147)); 53 | songs.add(new SongV5("cassidy", "grateful dead", 158)); 54 | songs.add(new SongV5("$10", "hitchhiker", 140)); 55 | songs.add(new SongV5("$10", "hitchhiker", 140)); 56 | return songs; 57 | } 58 | } 59 | public class Jukebox5_HashSet { 60 | public static void main(String[] args) { 61 | new Jukebox_TreeSet().go(); 62 | } 63 | 64 | public void go(){ 65 | List songList = new ArrayList<>(MockSongs5.getSongString()); 66 | System.out.println(songList); 67 | 68 | songList.sort((one, two) -> one.getTitle().compareTo(two.getTitle())); 69 | System.out.println(songList); 70 | 71 | Set songSet = new HashSet<>(songList); 72 | System.out.println(songSet); 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/chapter_11/Jukebox_TreeSet.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.*; 4 | 5 | class SongV6{ 6 | private String title; 7 | private String artist; 8 | private int bpm; 9 | 10 | public SongV6(String title, String artist, int bpm) { 11 | this.title = title; 12 | this.artist = artist; 13 | this.bpm = bpm; 14 | } 15 | 16 | public String getTitle() { 17 | return title; 18 | } 19 | 20 | public String getArtist() { 21 | return artist; 22 | } 23 | 24 | public int getBpm() { 25 | return bpm; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return this.title; 31 | } 32 | 33 | } 34 | 35 | class MockSongs6{ 36 | public static List getSongString(){ 37 | List songs = new ArrayList<>(); 38 | songs.add(new SongV6("somersault", "zero 7", 147)); 39 | songs.add(new SongV6("cassidy", "grateful dead", 158)); 40 | songs.add(new SongV6("$10", "hitchhiker", 140)); 41 | songs.add(new SongV6("$10", "hitchhiker", 140)); 42 | songs.add(new SongV6("cassidy", "grateful dead", 158)); 43 | return songs; 44 | } 45 | } 46 | public class Jukebox_TreeSet { 47 | public static void main(String[] args) { 48 | new Jukebox_TreeSet().go(); 49 | } 50 | 51 | public void go(){ 52 | List songList = new ArrayList<>(MockSongs6.getSongString()); 53 | System.out.println(songList); 54 | 55 | songList.sort((one, two) -> one.getTitle().compareTo(two.getTitle())); 56 | System.out.println(songList); 57 | 58 | // create a TreeSet instead of HashSet 59 | // Set songSet = new TreeSet<>((one, two) -> one.getTitle().compareTo(two.getTitle())); 60 | Set songSet = new TreeSet<>((one, two) -> one.getBpm() - two.getBpm()); // sort by BPM 61 | songSet.addAll(songList); 62 | System.out.println(songSet); 63 | 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/chapter_11/MapExample.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapExample { 7 | public static void main(String[] args) { 8 | Map scores = new HashMap<>(); 9 | 10 | scores.put("Kathy", 42); 11 | scores.put("Bert", 343); 12 | scores.put("Skyler", 420); 13 | 14 | System.out.println(scores); 15 | System.out.println(scores.get("Bert")); // get() method takes a key and return its value 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/chapter_11/SortMountains.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class SortMountains { 7 | public static void main(String[] args) { 8 | new SortMountains().go(); 9 | } 10 | 11 | public void go() { 12 | List mountains = new ArrayList<>(); 13 | mountains.add(new Mountain("Longs", 14255)); 14 | mountains.add(new Mountain("Elbert", 14433)); 15 | mountains.add(new Mountain("Maroon", 14156)); 16 | mountains.add(new Mountain("Castle", 14265)); 17 | 18 | System.out.println("as entered: \n" + mountains); 19 | //Sort mountains according to name - Ascending Order 20 | mountains.sort((one, two)-> one.getName().compareTo(two.getName())); 21 | System.out.println("by name: \n" + mountains); 22 | 23 | //Sort mountains according to height - Descending/Reverse Order 24 | mountains.sort((one, two)-> one.getHeight() - (two.getHeight())); 25 | System.out.println("by height: \n" + mountains); 26 | } 27 | 28 | } 29 | 30 | // Mountain Class 31 | class Mountain { 32 | String name; 33 | int height; 34 | 35 | public Mountain(String name, int height) { 36 | this.name = name; 37 | this.height = height; 38 | } 39 | 40 | public String getName(){ 41 | return this.name; 42 | } 43 | 44 | public int getHeight(){ 45 | return this.height; 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return this.name + " "+this.height; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/chapter_11/TestTree.java: -------------------------------------------------------------------------------- 1 | package chapter_11; 2 | 3 | import java.util.Set; 4 | import java.util.TreeSet; 5 | 6 | public class TestTree { 7 | public static void main(String[] args) { 8 | new TestTree().go(); 9 | } 10 | 11 | public void go(){ 12 | Book b1 = new Book("How Cats work"); 13 | Book b2 = new Book("Remix your body"); 14 | Book b3 = new Book("Finding EMo"); 15 | 16 | Set tree = new TreeSet<>(); 17 | tree.add(b1); 18 | tree.add(b2); 19 | tree.add(b3); 20 | 21 | System.out.println(tree); 22 | } 23 | } 24 | 25 | class Book implements Comparable{ 26 | private String title; 27 | public Book(String t ){ 28 | title = t; 29 | } 30 | 31 | @Override 32 | public int compareTo(Book o) { 33 | return title.compareTo(o.title); 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return title; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/chapter_12/CoffeeOrder.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | // Code Magnets Exercise Solution 7 | public class CoffeeOrder { 8 | public static void main(String[] args) { 9 | List coffees = List.of("Cappuccino", "Americano", "Espresso", "Cortado", 10 | "Mocha", "Cappuccino","Flat White", "Latte"); 11 | 12 | List coffeesEndingInO = coffees.stream() 13 | .filter((s -> s.endsWith("o"))) 14 | .sorted() 15 | .distinct() 16 | .collect(Collectors.toList()); 17 | 18 | System.out.println(coffeesEndingInO); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/chapter_12/ForEachExample.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | 5 | public class ForEachExample { 6 | public static void main(String[] args){ 7 | List allColors = List.of("Red", "Blue", "Yellow"); // this is convenience factory method 8 | for (String color : allColors){ 9 | System.out.println(color); 10 | } 11 | 12 | System.out.println("#### Using Lambda ####"); 13 | // using lambda 14 | allColors.forEach(color -> System.out.println(color)); 15 | System.out.println("\n"); 16 | 17 | List names = List.of("Rahim", "Karim", "Shanto", "Asif", "Shuvo"); 18 | names.forEach(name -> System.out.print(name+", ")); // printing all the element using lambda 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/chapter_12/JukeboxStream_Mapping.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | import java.util.stream.Collectors; 6 | 7 | public class JukeboxStream_Mapping { 8 | public static void main(String[] args) { 9 | List songs = new Songs().getSongs(); 10 | 11 | //Creating a new List of all the genres 12 | List genres = songs.stream() 13 | .map(song -> song.getGenre()) //mapping genres into a new List 14 | .collect(Collectors.toList()); 15 | System.out.println(genres); 16 | System.out.println(); 17 | 18 | // Creating a new List of distinct genre 19 | List genre = songs.stream() 20 | .map(song -> song.getGenre()) 21 | .distinct() 22 | .collect(Collectors.toList()); 23 | System.out.println("Distinct genres are: "+genre); 24 | System.out.println(); 25 | 26 | // Another way creating a List and remove duplicate by using Set 27 | Set setGenres = songs.stream() 28 | .map(song -> song.getGenre()) 29 | .collect(Collectors.toSet()); 30 | System.out.println("Set of Genres : " + setGenres); 31 | 32 | //Counting Songs with distinct title 33 | long count = songs.stream() 34 | .map(song -> song.getTitle()) 35 | .distinct() 36 | .count(); 37 | System.out.println("Number of distinct song titles are: "+count); 38 | System.out.println(); 39 | 40 | //Creating a new List - artist of "With a Little Help from My Friends", except "The Beatles" 41 | String songTitle = "With a Little Help from My Friends"; 42 | List result = songs.stream() 43 | .filter(song -> song.getTitle().equals(songTitle)) 44 | .map(song -> song.getArtist()) 45 | .filter(artist -> !artist.equals("The Beatles")) 46 | .collect(Collectors.toList()); 47 | System.out.println(result); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/chapter_12/JukeboxStream_filter.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | class Songs{ 7 | public List getSongs(){ 8 | return List.of( 9 | new Song("$10", "Hitchhiker", "Electronic", 2016, 183), 10 | new Song("Havana", "Camila Cabello", "R&B", 2017, 324), 11 | new Song("Cassidy", "Grateful Dead", "Rock", 1972, 123), 12 | new Song("50 ways", "Paul Simon", "Soft Rock", 1975, 199), 13 | new Song("Hurt", "Nine Inch Nails", "Industrial Rock", 1995, 14 | 257), 15 | new Song("Silence", "Delerium", "Electronic", 1999, 134), 16 | new Song("Hurt", "Johnny Cash", "Soft Rock", 2002, 392), 17 | new Song("Watercolour", "Pendulum", "Electronic", 2010, 18 | 155), 19 | new Song("The Outsider", "A Perfect Circle", "Alternative Rock", 2004, 312), 20 | new Song("With a Little Help from My Friends", "The Beatles", "Rock", 1967, 168), 21 | new Song("Come Together", "The Beatles", "Blues rock", 1968, 22 | 173), 23 | new Song("Come Together", "Ike & Tina Turner", "Rock", 1970, 24 | 165), 25 | new Song("With a Little Help from My Friends", "Joe Cocker", 26 | "Rock", 1968, 46), 27 | new Song("Immigrant Song", "Karen O", "Industrial Rock", 28 | 2011, 12), 29 | new Song("Breathe", "The Prodigy", "Electronic", 1996, 337), 30 | new Song("What's Going On", "Gaye", "R&B", 1971, 420), 31 | new Song("Hallucinate", "Dua Lipa", "Pop", 2020, 75), 32 | new Song("Walk Me Home", "P!nk", "Pop", 2019, 459), 33 | new Song("I am not a woman, I'm a god", "Halsey", 34 | "Alternative Rock", 2021, 384)); 35 | } 36 | } 37 | 38 | class Song{ 39 | private final String title; 40 | private final String artist; 41 | private final String genre; 42 | private final int year; 43 | private final int timesPlayed; 44 | 45 | public Song(String title, String artist, String genre, int year, int timesPlayed) { 46 | this.title = title; 47 | this.artist = artist; 48 | this.genre = genre; 49 | this.year = year; 50 | this.timesPlayed = timesPlayed; 51 | } 52 | 53 | public String getTitle() { 54 | return title; 55 | } 56 | 57 | public String getArtist() { 58 | return artist; 59 | } 60 | 61 | public String getGenre() { 62 | return genre; 63 | } 64 | 65 | public int getYear() { 66 | return year; 67 | } 68 | 69 | public int getTimesPlayed() { 70 | return timesPlayed; 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "Song{" + 76 | "title='" + title + '\'' + 77 | ", artist='" + artist + '\'' + 78 | ", genre='" + genre + '\'' + 79 | ", year=" + year + 80 | ", timesPlayed=" + timesPlayed + 81 | '}'; 82 | } 83 | } 84 | 85 | 86 | public class JukeboxStream_filter { 87 | public static void main(String[] args){ 88 | List songs = new Songs().getSongs(); 89 | 90 | //Filtering songs with genre = "Rock" 91 | List rockSongs = songs.stream() 92 | .filter(song -> song.getGenre().equals("Rock")) 93 | .collect(Collectors.toList()); 94 | System.out.println(rockSongs); 95 | 96 | System.out.println("\n"); 97 | //Filtering songs with genre contains Rock : (Rock, Soft Rock, ..... Rock) 98 | List containRock = songs.stream() 99 | .filter(song -> song.getGenre().contains("Rock")) 100 | .collect(Collectors.toList()); 101 | System.out.println(containRock); 102 | 103 | System.out.println("\n"); 104 | 105 | // Filtering songs with title start with "H" 106 | List songStartWithH = songs.stream() 107 | .filter(song -> song.getTitle().startsWith("H")) 108 | .collect(Collectors.toList()); 109 | System.out.println(songStartWithH); 110 | 111 | System.out.println("\n"); 112 | 113 | // Filtering songs year More recent than 1995 114 | List s = songs.stream() 115 | .filter(song -> song.getYear() > 1995) 116 | .collect(Collectors.toList()); 117 | System.out.println(s); 118 | 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/chapter_12/StreamPuzzle.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.Comparator; 4 | import java.util.List; 5 | import java.util.Optional; 6 | import java.util.stream.Collectors; 7 | 8 | // Pool Puzzle Exercise Solution 9 | public class StreamPuzzle { 10 | public static void main(String[] args) { 11 | SongSearch songSearch = new SongSearch(); 12 | songSearch.printTopFiveSongs(); 13 | songSearch.search("The Beatles"); 14 | songSearch.search("The Beach Boys"); 15 | } 16 | } 17 | 18 | class SongSearch{ 19 | private final List songs = new Songs().getSongs(); 20 | 21 | void printTopFiveSongs(){ 22 | List topFive = songs.stream() 23 | .sorted(Comparator.comparingInt(Song::getTimesPlayed)) 24 | .map(song -> song.getTitle()) 25 | .limit(5) 26 | .collect(Collectors.toList()); 27 | System.out.println(topFive); 28 | } 29 | 30 | void search(String artist){ 31 | Optional result = songs.stream() 32 | .filter(song -> song.getArtist().equals(artist)) 33 | .findAny(); 34 | 35 | if (result.isPresent()){ 36 | System.out.println(result.get().getTitle()); 37 | } 38 | else System.out.println("No songs found by: " + artist); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/chapter_12/StreamWithLambdas.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class StreamWithLambdas { 7 | public static void main(String[] args) { 8 | List strings = List.of("I", "am", "a", "list", "of", "Strings"); 9 | 10 | List result = strings.stream() 11 | .sorted((s1, s2)-> s1.compareToIgnoreCase(s2)) // sorted in ascending order 12 | .skip(2) // the stream skipped over the first two elements 13 | .limit(4) 14 | .collect(Collectors.toList()); 15 | 16 | System.out.println("result = "+ result); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/chapter_12/Stream_CollectAndCollectors.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Stream_CollectAndCollectors { 8 | public static void main(String[] args) { 9 | List strings = List.of("I", "am", "a", "list", "of", "Strings"); 10 | 11 | // add string into stream 12 | Stream stream = strings.stream(); 13 | 14 | Stream limit = stream.limit(4); 15 | List result = limit.collect(Collectors.toList()); 16 | System.out.println("result = "+result); 17 | 18 | 19 | // we can rewrite the limit and collect together 20 | List result2 = strings.stream().limit(4).collect(Collectors.toList()); 21 | System.out.println("result = "+result2); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/chapter_12/TerminalOperations.java: -------------------------------------------------------------------------------- 1 | package chapter_12; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | public class TerminalOperations { 7 | public static void main(String[] args) { 8 | List songs = new Songs().getSongs(); 9 | 10 | // checking something exits 11 | boolean result = songs.stream() 12 | .anyMatch(s -> s.getGenre().equals("R&B")); // return true 13 | System.out.println("result = "+ result); 14 | 15 | 16 | // Find a specific thing 17 | Optional optionalSong = songs.stream() 18 | .filter(s -> s.getYear() == 1995) 19 | .findFirst(); 20 | System.out.println("First song played was released in 1995 : "+ optionalSong); 21 | 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/chapter_13/ExTestDrive.java: -------------------------------------------------------------------------------- 1 | package chapter_13; 2 | 3 | public class ExTestDrive { 4 | public static void main(String[] args) { 5 | String test = "yes"; 6 | try{ 7 | System.out.print("t"); 8 | doRisky(test); 9 | System.out.print("o"); 10 | } 11 | catch(MyEx e){ 12 | System.out.print("a"); 13 | } 14 | finally{ 15 | System.out.print("w"); 16 | } 17 | System.out.println("s"); 18 | } 19 | 20 | public static void doRisky(String t) throws MyEx { 21 | System.out.print("h"); 22 | if("yes".equals(t)){ 23 | throw new MyEx(); 24 | } 25 | System.out.print("r"); 26 | } 27 | 28 | } 29 | 30 | class MyEx extends Exception{} 31 | -------------------------------------------------------------------------------- /src/chapter_13/MiniMiniMusicApp.java: -------------------------------------------------------------------------------- 1 | package chapter_13; 2 | 3 | import javax.sound.midi.*; 4 | 5 | import static javax.sound.midi.ShortMessage.NOTE_OFF; 6 | 7 | public class MiniMiniMusicApp { 8 | public static void main(String[] args) { 9 | MiniMiniMusicApp mini = new MiniMiniMusicApp(); 10 | mini.play(); 11 | } 12 | 13 | public void play(){ 14 | try { 15 | Sequencer player = MidiSystem.getSequencer(); 16 | player.open(); 17 | 18 | Sequence seq = new Sequence(Sequence.PPQ,4); 19 | 20 | Track track = seq.createTrack(); 21 | 22 | ShortMessage msg1 = new ShortMessage(); 23 | msg1.setMessage(ShortMessage.NOTE_ON, 1,44,100); 24 | MidiEvent noteOn = new MidiEvent(msg1, 1); 25 | track.add(noteOn); 26 | 27 | ShortMessage msg2 = new ShortMessage(); 28 | msg2.setMessage(NOTE_OFF, 1, 44, 100); 29 | MidiEvent noteOff = new MidiEvent(msg2, 16); 30 | track.add(noteOff); 31 | 32 | player.setSequence(seq); 33 | player.start(); 34 | 35 | }catch (Exception e){ 36 | e.printStackTrace(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/chapter_13/MiniMusicCmdLine.java: -------------------------------------------------------------------------------- 1 | package chapter_13; 2 | 3 | import javax.sound.midi.*; 4 | import java.util.Scanner; 5 | 6 | import static javax.sound.midi.ShortMessage.*; 7 | 8 | public class MiniMusicCmdLine { 9 | public static void main(String[] args) throws InvalidMidiDataException, MidiUnavailableException { 10 | MiniMusicCmdLine mini = new MiniMusicCmdLine(); 11 | Scanner sc = new Scanner(System.in); 12 | String arr[] = new String[2]; 13 | arr[0] = sc.nextLine(); 14 | arr[1] = sc.nextLine(); 15 | 16 | if(arr.length < 2){ 17 | System.out.println("Don't forget the instrument and note args"); 18 | } 19 | else{ 20 | int instrument = Integer.parseInt(arr[0]); 21 | int note = Integer.parseInt(arr[1]); 22 | mini.play(instrument, note); 23 | } 24 | } 25 | 26 | public void play(int instrument, int note){ 27 | try{ 28 | Sequencer player = MidiSystem.getSequencer(); 29 | player.open(); 30 | Sequence seq = new Sequence(Sequence.PPQ, 4); 31 | Track track = seq.createTrack(); 32 | 33 | ShortMessage msg1 = new ShortMessage(); 34 | msg1.setMessage(PROGRAM_CHANGE, 1, instrument, 0); 35 | MidiEvent changeInstrument = new MidiEvent(msg1, 1); 36 | track.add(changeInstrument); 37 | 38 | ShortMessage msg2 = new ShortMessage(); 39 | msg2.setMessage(NOTE_ON, 1, note, 100); 40 | MidiEvent noteOn = new MidiEvent(msg2, 1); 41 | track.add(noteOn); 42 | 43 | ShortMessage msg3 = new ShortMessage(); 44 | msg3.setMessage(NOTE_OFF, 1, note, 100); 45 | MidiEvent noteOff = new MidiEvent(msg3, 16); 46 | track.add(noteOff); 47 | 48 | player.setSequence(seq); 49 | player.start(); 50 | } 51 | catch(Exception ex){ 52 | ex.printStackTrace(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/chapter_13/TestExceptions.java: -------------------------------------------------------------------------------- 1 | package chapter_13; 2 | 3 | public class TestExceptions { 4 | public static void main(String[] args){ 5 | String test = "yes"; 6 | try { 7 | System.out.println("Start try"); 8 | doRisky(test); 9 | System.out.println("End try"); 10 | } catch (ScaryException se){ 11 | System.out.println("scary exception"); 12 | } finally { 13 | System.out.println("finally"); 14 | } 15 | 16 | System.out.println("end of main"); 17 | } 18 | 19 | static void doRisky(String test) throws ScaryException { 20 | System.out.println("start risky"); 21 | if ("yes".equalsIgnoreCase(test)){ 22 | throw new ScaryException(); 23 | } 24 | System.out.println("end risky"); 25 | } 26 | } 27 | 28 | class ScaryException extends Exception{} 29 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/Animate.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class Animate { 8 | int x = 1; 9 | int y = 1; 10 | 11 | public static void main(String[] args) { 12 | Animate gui = new Animate(); 13 | gui.go(); 14 | } 15 | 16 | public void go(){ 17 | JFrame frame = new JFrame(); 18 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 | 20 | MyDrawP drawP = new MyDrawP(); 21 | frame.getContentPane().add(drawP); 22 | frame.setSize(500,270); 23 | frame.setVisible(true); 24 | 25 | for (int i = 0; i<124; i++, y++, x++){ 26 | x++; 27 | drawP.repaint(); 28 | try { 29 | TimeUnit.MILLISECONDS.sleep(50); 30 | }catch (Exception e){ 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | 36 | 37 | class MyDrawP extends JPanel{ 38 | @Override 39 | protected void paintComponent(Graphics g) { 40 | g.setColor(Color.white); 41 | g.fillRect(0,0,500,250); 42 | g.setColor(Color.orange); 43 | g.fillRect(x,y, 500-x*2,250-y*2); 44 | 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/FirstGUI.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class FirstGUI { 7 | public static void main(String[] args) { 8 | JFrame frame = new JFrame("First GUI Program"); 9 | JButton button = new JButton("Click Me"); 10 | 11 | // Set the preferred size of the button 12 | button.setPreferredSize(new Dimension(100, 100)); 13 | 14 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15 | 16 | // Set the layout manager to FlowLayout 17 | frame.setLayout(new FlowLayout()); 18 | 19 | frame.getContentPane().add(BorderLayout.CENTER, button); 20 | frame.setSize(500,500); 21 | 22 | // Let the layout manager handle the size and position of the components 23 | frame.setVisible(true); 24 | 25 | button.addActionListener(e -> button.setText("I am clicked")); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/InnerButton.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | public class InnerButton { 9 | private JButton button; 10 | 11 | public static void main(String[] args) { 12 | InnerButton gui = new InnerButton(); 13 | gui.go(); 14 | } 15 | 16 | public void go(){ 17 | JFrame frame = new JFrame(); 18 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 | 20 | button = new JButton("A"); 21 | button.addActionListener(new ButtonListener()); 22 | 23 | frame.getContentPane().add(BorderLayout.SOUTH, button); 24 | frame.setSize(200,100); 25 | frame.setVisible(true); 26 | } 27 | 28 | class ButtonListener implements ActionListener{ 29 | @Override 30 | public void actionPerformed(ActionEvent e) { 31 | if (button.getText().equals("A")){ 32 | button.setText("B"); 33 | } 34 | else button.setText("A"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/SimpleAnimation.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class SimpleAnimation { 8 | private int xPos = 70; 9 | private int yPos = 70; 10 | 11 | public static void main(String[] args){ 12 | SimpleAnimation gui = new SimpleAnimation(); 13 | gui.go(); 14 | } 15 | 16 | public void go(){ 17 | JFrame frame = new JFrame(); 18 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 | 20 | MyDrawPanel drawPanel = new MyDrawPanel(); 21 | 22 | frame.getContentPane().add(drawPanel); 23 | frame.setSize(300,300); 24 | frame.setVisible(true); 25 | 26 | for (int i = 0; i<130; i++){ 27 | xPos++; 28 | yPos++; 29 | 30 | drawPanel.repaint(); 31 | 32 | try{ 33 | TimeUnit.MILLISECONDS.sleep(50); 34 | }catch (Exception e ){ 35 | e.printStackTrace(); 36 | } 37 | } 38 | } 39 | 40 | class MyDrawPanel extends JPanel{ 41 | @Override 42 | public void paint(Graphics g) { 43 | g.setColor(Color.white); 44 | g.fillRect(0,0, this.getWidth(), this.getHeight()); 45 | 46 | g.setColor(Color.green); 47 | g.fillOval(xPos, yPos, 40,40); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/SimpleGui3.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.util.Random; 6 | 7 | public class SimpleGui3 { 8 | private JFrame frame; 9 | 10 | public static void main(String[] args){ 11 | SimpleGui3 gui = new SimpleGui3(); 12 | gui.go(); 13 | } 14 | 15 | public void go(){ 16 | frame = new JFrame(); 17 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 | 19 | JButton button = new JButton("Change colors"); 20 | button.addActionListener(e -> frame.repaint()); 21 | 22 | MyDrawPanel drawPanel = new MyDrawPanel(); 23 | 24 | frame.getContentPane().add(BorderLayout.SOUTH, button); 25 | frame.getContentPane().add(BorderLayout.CENTER, drawPanel); 26 | frame.setSize(400,400); 27 | frame.setVisible(true); 28 | } 29 | 30 | } 31 | 32 | 33 | class MyDrawPanel extends JPanel{ 34 | public void paintComponent(Graphics graphics){ 35 | Graphics2D g2d = (Graphics2D) graphics; 36 | 37 | Random random = new Random(); 38 | int red = random.nextInt(256); 39 | int green = random.nextInt(256); 40 | int blue = random.nextInt(256); 41 | Color startColor = new Color(red, green, blue); 42 | 43 | red = random.nextInt(256); 44 | green = random.nextInt(256); 45 | blue = random.nextInt(256); 46 | Color endColor = new Color(red, green, blue); 47 | 48 | GradientPaint gradient = new GradientPaint(70,70, startColor, 150,150, endColor); 49 | g2d.setPaint(gradient); 50 | g2d.fillOval(70,70,100,100); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/chapter_14_GUI/TwoButtons.java: -------------------------------------------------------------------------------- 1 | package chapter_14_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class TwoButtons { 7 | private JFrame frame; 8 | private JLabel label; 9 | 10 | public static void main(String[] args) { 11 | TwoButtons gui = new TwoButtons(); 12 | gui.go(); 13 | } 14 | 15 | public void go(){ 16 | frame = new JFrame(); 17 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 | 19 | JButton labelButton = new JButton("Change Label"); 20 | // labelButton.addActionListener(new LabelListener()); 21 | labelButton.addActionListener(e -> label.setText("Ouch")); // we can use lambdas instead of using inner class 22 | 23 | JButton colorButton = new JButton("Change Circle"); 24 | // colorButton.addActionListener(new ColorListener()); 25 | colorButton.addActionListener(e -> frame.repaint()); // we can use lambdas instead of using inner class 26 | 27 | label = new JLabel("I'm a label"); 28 | MyDrawPanel drawPanel = new MyDrawPanel(); 29 | 30 | frame.getContentPane().add(BorderLayout.SOUTH, colorButton); 31 | frame.getContentPane().add(BorderLayout.CENTER, drawPanel); 32 | frame.getContentPane().add(BorderLayout.EAST, labelButton); 33 | frame.getContentPane().add(BorderLayout.WEST, label); 34 | 35 | frame.setSize(500,400); 36 | frame.setVisible(true); 37 | } 38 | 39 | // class LabelListener implements ActionListener{ 40 | // @Override 41 | // public void actionPerformed(ActionEvent e) { 42 | // label.setText("Ouch!"); 43 | // } 44 | // } 45 | // 46 | // class ColorListener implements ActionListener{ 47 | // @Override 48 | // public void actionPerformed(ActionEvent e) { 49 | // frame.repaint(); 50 | // } 51 | // } 52 | } 53 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/BorderLayoutExample.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class BorderLayoutExample { 7 | public static void main(String[] args) { 8 | go(); 9 | } 10 | 11 | private static void go(){ 12 | JFrame frame = new JFrame(); 13 | JButton button = new JButton("click like you mean it"); 14 | frame.getContentPane().add(BorderLayout.NORTH, button); 15 | frame.setSize(200,200); 16 | frame.setVisible(true); 17 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/BoxLayoutExample.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class BoxLayoutExample { 7 | public static void main(String[] args) { 8 | go(); 9 | } 10 | 11 | private static void go(){ 12 | JFrame frame = new JFrame(); 13 | JPanel panel = new JPanel(); 14 | panel.setBackground(Color.DARK_GRAY); 15 | 16 | panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 17 | 18 | JButton button = new JButton("shock me"); 19 | JButton button1 = new JButton("bliss"); 20 | 21 | panel.add(button); 22 | panel.add(button1); 23 | 24 | frame.getContentPane().add(BorderLayout.EAST, panel); 25 | frame.setVisible(true); 26 | frame.setSize(250,200); 27 | panel.setSize(250,200); 28 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/CheckBox.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.event.ItemEvent; 5 | import java.awt.event.ItemListener; 6 | 7 | public class CheckBox implements ItemListener { 8 | private static JCheckBox checkBox; 9 | private static JCheckBox checkBox2; 10 | 11 | public static void main(String[] args) { 12 | new CheckBox().go(); 13 | } 14 | 15 | private void go(){ 16 | JFrame frame = new JFrame(); 17 | JPanel panel = new JPanel(); 18 | frame.setSize(350,300); 19 | frame.getContentPane().add(panel); 20 | 21 | checkBox = new JCheckBox("Goes to 11"); 22 | checkBox.addItemListener(this); 23 | checkBox2 = new JCheckBox("Hello"); 24 | checkBox2.addItemListener(this); 25 | 26 | panel.add(checkBox); 27 | panel.add(checkBox2); 28 | 29 | frame.setVisible(true); 30 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 31 | } 32 | 33 | @Override 34 | public void itemStateChanged(ItemEvent e) { 35 | String onOrOff = "off"; 36 | if (checkBox.isSelected()){ 37 | onOrOff = "on"; 38 | } 39 | System.out.println("Check box is "+ onOrOff); 40 | 41 | if (checkBox2.isSelected()){ 42 | System.out.println("Hello world"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/ClickCountGUI.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | public class ClickCountGUI { 9 | private static int count = 0; 10 | public static void main(String[] args){ 11 | JFrame frame = new JFrame(); 12 | JPanel panel = new JPanel(); 13 | JButton clickButton = new JButton("Click me"); 14 | clickButton.setSize(200,100); 15 | JButton resetButton = new JButton("Reset"); 16 | JLabel label = new JLabel("Number of count: 0"); 17 | frame.setSize(350,200); 18 | 19 | panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 20 | panel.setSize(350,200); 21 | panel.add(clickButton); 22 | panel.add(label); 23 | panel.add(resetButton); 24 | 25 | // Using lambda 26 | clickButton.addActionListener(e -> { 27 | count++; 28 | label.setText("Number of counts: " + count); 29 | }); 30 | 31 | // using anonymous class 32 | resetButton.addActionListener(new ActionListener() { 33 | @Override 34 | public void actionPerformed(ActionEvent e) { 35 | label.setText("Number of count: 0"); 36 | count = 0; 37 | } 38 | }); 39 | 40 | frame.getContentPane().add(BorderLayout.CENTER, panel); 41 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 42 | frame.setVisible(true); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/FlowLayoutExample.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class FlowLayoutExample { 7 | public static void main(String[] args) { 8 | go(); 9 | } 10 | 11 | private static void go(){ 12 | JFrame frame = new JFrame(); 13 | JPanel panel = new JPanel(); 14 | panel.setBackground(Color.DARK_GRAY); 15 | 16 | JButton button = new JButton("shock me "); 17 | JButton button2 = new JButton("bliss"); 18 | panel.add(button); 19 | panel.add(button2); 20 | button.setSize(30,50); 21 | 22 | frame.getContentPane().add(BorderLayout.EAST, panel); 23 | panel.setSize(250,200); 24 | frame.setSize(250,200); 25 | frame.setVisible(true); 26 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/List.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import javax.swing.event.ListSelectionEvent; 5 | import javax.swing.event.ListSelectionListener; 6 | 7 | public class List implements ListSelectionListener{ 8 | private JList myList; 9 | 10 | public static void main(String[] args) { 11 | new List().go(); 12 | } 13 | 14 | private void go(){ 15 | JFrame frame = new JFrame(); 16 | JPanel panel = new JPanel(); 17 | frame.setSize(350,300); 18 | frame.getContentPane().add(panel); 19 | 20 | String[] listEntries = {"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta"}; 21 | myList = new JList<>(listEntries); 22 | 23 | JScrollPane scroller = new JScrollPane(myList); 24 | scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 25 | scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 26 | 27 | myList.setVisibleRowCount(4); 28 | myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 29 | myList.addListSelectionListener(this); 30 | 31 | 32 | panel.add(myList); 33 | 34 | frame.setVisible(true); 35 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 36 | } 37 | 38 | @Override 39 | public void valueChanged(ListSelectionEvent e) { 40 | if (!e.getValueIsAdjusting()){ 41 | String selection = myList.getSelectedValue(); 42 | System.out.println(selection); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/LoginGUI.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | 5 | public class LoginGUI { 6 | public static void main(String[] args) { 7 | JFrame frame = new JFrame("Login GUI"); 8 | JPanel panel = new JPanel(); 9 | 10 | panel.setLayout(null); 11 | frame.setSize(350,200); 12 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 13 | frame.add(panel); 14 | frame.getContentPane().add(panel); 15 | 16 | JLabel userLabel = new JLabel("User"); 17 | userLabel.setBounds(10,20,80,25); 18 | panel.add(userLabel); 19 | 20 | JTextField userField = new JTextField(20); 21 | userField.setBounds(100, 20, 165, 25); 22 | panel.add(userField); 23 | 24 | 25 | JLabel passwordLabel = new JLabel("Password"); 26 | passwordLabel.setBounds(10,50,80,25); 27 | panel.add(passwordLabel); 28 | 29 | JPasswordField password = new JPasswordField(); 30 | password.setBounds(100, 50, 165, 25); 31 | panel.add(password); 32 | 33 | JButton loginButton = new JButton("Login"); 34 | loginButton.setBounds(10,80,80,25); 35 | panel.add(loginButton); 36 | 37 | JLabel successLabel = new JLabel("Login successfully"); 38 | successLabel.setBounds(10,110,300,25); 39 | successLabel.setVisible(false); 40 | panel.add(successLabel); 41 | 42 | 43 | 44 | loginButton.addActionListener(e -> { 45 | if (userField.getText().equals("hello") && password.getText().equals("world")){ 46 | successLabel.setVisible(true); 47 | } 48 | else{ 49 | successLabel.setText("Not match"); 50 | successLabel.setVisible(true); 51 | } 52 | }); 53 | 54 | 55 | frame.setVisible(true); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/TextArea.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | 5 | public class TextArea { 6 | private static int count = 0; 7 | public static void main(String[] args) { 8 | JFrame frame = new JFrame(); 9 | JPanel panel = new JPanel(); 10 | frame.getContentPane().add(panel); 11 | frame.setSize(350,300); 12 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 13 | 14 | JTextArea text = new JTextArea(10,20); 15 | 16 | JScrollPane scroller = new JScrollPane(text); 17 | text.setLineWrap(true); 18 | 19 | scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 20 | scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 21 | panel.add(scroller); 22 | 23 | JButton button = new JButton("Click me"); 24 | panel.add(button); 25 | 26 | button.addActionListener(e -> { 27 | count++; 28 | text.append("button clicked \n"); 29 | if (count == 10) { 30 | button.setVisible(false); 31 | text.append("Too many operation"); 32 | } 33 | }); 34 | frame.setVisible(true); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/chapter_15_GUI/TextField.java: -------------------------------------------------------------------------------- 1 | package chapter_15_GUI; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | 6 | public class TextField { 7 | public static void main(String[] args) { 8 | JFrame frame = new JFrame(); 9 | JPanel panel = new JPanel(); 10 | JTextField textField = new JTextField(20); 11 | JLabel label = new JLabel("Enter your name"); 12 | panel.add(label); 13 | panel.add(textField); 14 | 15 | 16 | frame.setSize(350,200); 17 | frame.getContentPane().add(panel, BorderLayout.CENTER); 18 | frame.setVisible(true); 19 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/chapter_16/DungeonGame.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.*; 4 | 5 | public class DungeonGame implements Serializable { 6 | public int x = 3; 7 | transient long y = 4; 8 | private short z = 5; 9 | 10 | int getX(){ 11 | return x; 12 | } 13 | 14 | long getY(){ 15 | return y; 16 | } 17 | 18 | short getZ(){ 19 | return z; 20 | } 21 | } 22 | 23 | class DungeonTest{ 24 | public static void main(String[] args) { 25 | DungeonGame d = new DungeonGame(); 26 | System.out.println(d.getX() + d.getY()+ d.getZ()); 27 | 28 | try { 29 | FileOutputStream fos = new FileOutputStream("dg.ser"); 30 | ObjectOutputStream oos = new ObjectOutputStream(fos); 31 | oos.writeObject(d); 32 | oos.close(); 33 | 34 | 35 | FileInputStream fis = new FileInputStream("dg.ser"); 36 | ObjectInputStream ois = new ObjectInputStream(fis); 37 | d = (DungeonGame) ois.readObject(); 38 | ois.close(); 39 | } catch (Exception e){ 40 | e.printStackTrace(); 41 | } 42 | 43 | System.out.println(d.getX() + d.getY() + d.getZ()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/chapter_16/GameCharacter.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.Serializable; 4 | 5 | public class GameCharacter implements Serializable { 6 | private final int power; 7 | private final String type; 8 | private final String[] weapons; 9 | 10 | public GameCharacter(int power, String type, String[] weapons) { 11 | this.power = power; 12 | this.type = type; 13 | this.weapons = weapons; 14 | } 15 | 16 | public int getPower() { 17 | return power; 18 | } 19 | 20 | public String getType() { 21 | return type; 22 | } 23 | 24 | public String[] getWeapons() { 25 | return weapons; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/chapter_16/GameSaverTest.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | 8 | public class GameSaverTest { 9 | public static void main(String[] args) { 10 | GameCharacter one = new GameCharacter(50, "Ef",new String[]{"bow","sword", "dust"}); 11 | GameCharacter two = new GameCharacter(200, "Troll", new String[]{"bare hands", "big ax"}); 12 | GameCharacter three = new GameCharacter(120,"Magician", new String[]{"spells","invisibility"}); 13 | 14 | try { 15 | // Serialized the objects 16 | ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser")); 17 | os.writeObject(one); 18 | os.writeObject(two); 19 | os.writeObject(three); 20 | os.close(); 21 | 22 | } catch (Exception e){ 23 | e.printStackTrace(); 24 | } 25 | 26 | try { 27 | // Deserialized the objects 28 | ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser")); 29 | GameCharacter oneRestore = (GameCharacter) is.readObject(); 30 | GameCharacter twoRestore = (GameCharacter) is.readObject(); 31 | GameCharacter threeRestore = (GameCharacter) is.readObject(); 32 | 33 | System.out.println("One's type: " + oneRestore.getType()); 34 | System.out.println("Two's type: " + twoRestore.getType()); 35 | System.out.println("Three's type: " + threeRestore.getType()); 36 | 37 | } catch (Exception e){ 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/chapter_16/Pond.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | import java.io.FileOutputStream; 3 | import java.io.ObjectOutputStream; 4 | import java.io.Serializable; 5 | 6 | public class Pond implements Serializable { 7 | private Duck duck = new Duck(); 8 | 9 | 10 | public static void main(String[] args) { 11 | Pond myPond = new Pond(); 12 | try { 13 | FileOutputStream fs = new FileOutputStream("Pond.ser"); 14 | ObjectOutputStream os = new ObjectOutputStream(fs); 15 | os.writeObject(myPond); 16 | os.close(); 17 | } catch (Exception e){ 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | 23 | // Duck class must be implements Serializable interface otherwise runtime exception will be thrown 24 | class Duck implements Serializable { 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/chapter_16/QuizCard.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.Serializable; 4 | 5 | public class QuizCard implements Serializable { 6 | private String question; 7 | private String answer; 8 | 9 | public QuizCard(String q, String a) { 10 | question = q; 11 | answer = a; 12 | } 13 | 14 | 15 | public void setQuestion(String q) { 16 | question = q; 17 | } 18 | 19 | public String getQuestion() { 20 | return question; 21 | } 22 | 23 | public void setAnswer(String a) { 24 | answer = a; 25 | } 26 | 27 | public String getAnswer() { 28 | return answer; 29 | } 30 | 31 | 32 | } -------------------------------------------------------------------------------- /src/chapter_16/QuizCardBuilder.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.io.BufferedWriter; 6 | import java.io.File; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | 11 | public class QuizCardBuilder { 12 | private ArrayList cardList = new ArrayList<>(); 13 | private JTextArea question; 14 | private JTextArea answer; 15 | private JFrame frame; 16 | 17 | public static void main (String[] args){ 18 | new QuizCardBuilder().go(); 19 | } 20 | 21 | private void go(){ 22 | frame = new JFrame("Quiz Card Builder"); 23 | JPanel mainPanel = new JPanel(); 24 | Font bigFont = new Font("sanserif", Font.BOLD,24); 25 | 26 | question = createTextArea(bigFont); 27 | JScrollPane qScroller = new JScrollPane(question); 28 | answer = createTextArea(bigFont); 29 | JScrollPane aScoller = createScroller(answer); 30 | 31 | mainPanel.add(new JLabel("Question")); 32 | mainPanel.add(qScroller); 33 | mainPanel.add(new JLabel("Answer")); 34 | mainPanel.add(qScroller); 35 | 36 | JButton nextButton = new JButton("Next card"); 37 | nextButton.addActionListener(e -> nextCard()); 38 | mainPanel.add(nextButton); 39 | 40 | JMenuBar menuBar = new JMenuBar(); 41 | JMenu fileMenu = new JMenu("File"); 42 | 43 | JMenuItem newMenuItem = new JMenuItem("New"); 44 | newMenuItem.addActionListener(e -> clearAll()); 45 | 46 | JMenuItem saveMenuItem = new JMenuItem("save"); 47 | saveMenuItem.addActionListener(e -> { 48 | try { 49 | saveCard(); 50 | } catch (IOException ex) { 51 | throw new RuntimeException(ex); 52 | } 53 | }); 54 | 55 | fileMenu.add(newMenuItem); 56 | fileMenu.add(saveMenuItem); 57 | menuBar.add(fileMenu); 58 | frame.setJMenuBar(menuBar); 59 | 60 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 61 | frame.setSize(500,600); 62 | frame.setVisible(true); 63 | } 64 | 65 | private JScrollPane createScroller(JTextArea textArea){ 66 | JScrollPane scrollPane = new JScrollPane(textArea); 67 | scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 68 | scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 69 | return scrollPane; 70 | } 71 | 72 | private JTextArea createTextArea(Font font){ 73 | JTextArea textArea = new JTextArea(6,20); 74 | textArea.setLineWrap(true); 75 | textArea.setWrapStyleWord(true); 76 | textArea.setFont(font); 77 | return textArea; 78 | } 79 | 80 | private void nextCard(){ 81 | QuizCard card = new QuizCard(question.getText(), answer.getText()); 82 | cardList.add(card); 83 | clearCard(); 84 | } 85 | 86 | private void saveCard() throws IOException { 87 | QuizCard card = new QuizCard(question.getText(), answer.getText()); 88 | cardList.add(card); 89 | 90 | JFileChooser fileSave = new JFileChooser(); 91 | fileSave.showSaveDialog(frame); 92 | saveFile(fileSave.getSelectedFile()); 93 | } 94 | 95 | 96 | private void clearAll(){ 97 | cardList.clear(); 98 | clearCard(); 99 | } 100 | 101 | private void clearCard(){ 102 | question.setText(""); 103 | answer.setText(""); 104 | question.requestFocus(); 105 | } 106 | 107 | private void saveFile(File file) throws IOException { 108 | BufferedWriter writer = new BufferedWriter(new FileWriter(file)); 109 | for (QuizCard card : cardList){ 110 | writer.write(card.getQuestion() + "/"); 111 | writer.write(card.getAnswer() + "\n"); 112 | } 113 | writer.close(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/chapter_16/QuizCardPlayer.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.io.BufferedReader; 6 | import java.io.File; 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | 11 | public class QuizCardPlayer { 12 | private ArrayList cardList; 13 | private int currentCardIndex; 14 | private QuizCard currentCard; 15 | private JTextArea display; 16 | private JButton nextButton; 17 | private JFrame frame; 18 | private boolean isShowAnswer; 19 | 20 | public static void main(String[] args) { 21 | new QuizCardPlayer().go(); 22 | } 23 | 24 | private void go(){ 25 | frame = new JFrame("Quiz Card PLayer"); 26 | JPanel mainPanel = new JPanel(); 27 | Font bigFont = new Font("sanserif", Font.BOLD, 24); 28 | 29 | display = new JTextArea(10,20); 30 | display.setFont(bigFont); 31 | display.setLineWrap(true); 32 | display.setEditable(false); 33 | 34 | JScrollPane scroller = new JScrollPane(display); 35 | scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 36 | scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 37 | mainPanel.add(scroller); 38 | 39 | nextButton = new JButton("Show Question"); 40 | nextButton.addActionListener(e -> nextCard()); 41 | mainPanel.add(nextButton); 42 | 43 | JMenuBar menuBar = new JMenuBar(); 44 | JMenu fileMenu = new JMenu("File"); 45 | JMenuItem loadMenuItem = new JMenuItem("Load card set"); 46 | loadMenuItem.addActionListener(e-> open()); 47 | fileMenu.add(loadMenuItem); 48 | menuBar.add(fileMenu); 49 | frame.setJMenuBar(menuBar); 50 | 51 | 52 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 53 | frame.setSize(500,400); 54 | frame.setVisible(true); 55 | 56 | } 57 | 58 | private void nextCard(){ 59 | if (isShowAnswer){ 60 | // show the answer because they've seen the question 61 | display.setText(currentCard.getAnswer()); 62 | nextButton.setText("Next Card"); 63 | isShowAnswer = false; 64 | } 65 | 66 | else{ 67 | // show the next question 68 | if (currentCardIndex < cardList.size()){ 69 | showNextCard(); 70 | } 71 | else{ 72 | // there are no more cards! 73 | display.setText("That was last card"); 74 | nextButton.setEnabled(false); 75 | } 76 | } 77 | } 78 | 79 | 80 | private void open(){ 81 | JFileChooser fileOpen = new JFileChooser(); 82 | fileOpen.showOpenDialog(frame); 83 | loadFile(fileOpen.getSelectedFile()); 84 | } 85 | 86 | private void loadFile(File file){ 87 | cardList = new ArrayList<>(); 88 | currentCardIndex = 0; 89 | try { 90 | BufferedReader reader = new BufferedReader(new FileReader(file)); 91 | String line; 92 | while((line = reader.readLine()) != null){ 93 | makeCard(line); 94 | } 95 | reader.close(); 96 | } 97 | catch (IOException e){ 98 | System.out.println("Couldn't write the cardList out : " + e.getMessage()); 99 | } 100 | showNextCard(); 101 | } 102 | 103 | private void makeCard(String lineToParse){ 104 | String[] result = lineToParse.split("/"); 105 | QuizCard card = new QuizCard(result[0], result[1]); 106 | cardList.add(card); 107 | System.out.println("made a card"); 108 | } 109 | 110 | private void showNextCard(){ 111 | currentCard = cardList.get(currentCardIndex); 112 | currentCardIndex++; 113 | display.setText(currentCard.getQuestion()); 114 | nextButton.setText("Show Answer"); 115 | isShowAnswer = true; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/chapter_16/Square.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.ObjectOutputStream; 5 | import java.io.Serializable; 6 | 7 | public class Square implements Serializable { 8 | private int width; 9 | private int height; 10 | 11 | public Square(int width, int height){ 12 | this.width = width; 13 | this.height = height; 14 | } 15 | 16 | public static void main(String[] args) { 17 | Square mySquare = new Square(50,30); 18 | 19 | try { 20 | FileOutputStream fs = new FileOutputStream("foo.ser"); 21 | ObjectOutputStream os = new ObjectOutputStream(fs); 22 | os.writeObject(mySquare); 23 | os.close(); 24 | } catch (Exception e){ 25 | e.printStackTrace(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/chapter_16/WriteString.java: -------------------------------------------------------------------------------- 1 | package chapter_16; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | public class WriteString { 7 | public static void main(String[] args) throws IOException { 8 | String s = "Hello World from java"; 9 | FileWriter writer = new FileWriter("foo.txt"); 10 | writer.write(s); 11 | 12 | writer.close(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/chapter_17/DailyAdviceClient.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.Reader; 6 | import java.net.InetSocketAddress; 7 | import java.nio.channels.Channels; 8 | import java.nio.channels.SocketChannel; 9 | import java.nio.charset.StandardCharsets; 10 | 11 | public class DailyAdviceClient { 12 | public void go() { 13 | // define the server address as being port 500, on the same host this code is running on the "localhost" 14 | InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 6000); 15 | try(SocketChannel socketChannel = SocketChannel.open(serverAddress)){// create a socket channel by opening one for the server's address 16 | 17 | // Create a Reader that reads from the SocketChannel 18 | Reader channelReader = Channels.newReader(socketChannel, StandardCharsets.UTF_8); 19 | 20 | // Chain a BufferedReader to the Reader from the SocketChannel 21 | BufferedReader reader = new BufferedReader(channelReader); 22 | 23 | // This readLine() is EXACTLY the same as if you were using a BufferedReader chained to a FILE 24 | String advice = reader.readLine(); 25 | System.out.println("Today you should: " + advice); 26 | 27 | reader.close(); // this closes the channelReader and this BufferedReader 28 | }catch (IOException e){ 29 | e.printStackTrace(); 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | new DailyAdviceClient().go(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/chapter_17/DailyAdviceServer.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.net.InetSocketAddress; 6 | import java.nio.channels.Channels; 7 | import java.nio.channels.ServerSocketChannel; 8 | import java.nio.channels.SocketChannel; 9 | import java.util.Random; 10 | 11 | public class DailyAdviceServer { 12 | final private String[] adviceList = { 13 | "Take smaller bites", 14 | "Go for the tight jeans. No they do NOT make you look fat", 15 | "One word: inappropriate", 16 | "Just for today, be honest. Tell your boss what you *really* think.", 17 | "You might want to rethink that haircut." 18 | }; 19 | 20 | private final Random random = new Random(); 21 | 22 | public void go(){ 23 | // SeverSocketChannel makes this server application "listen" for client request on the port it's bound to. 24 | try(ServerSocketChannel serverChannel = ServerSocketChannel.open()){ 25 | // You have to bind the ServerSocketChannel to the port you want to run the application on 26 | serverChannel.bind(new InetSocketAddress(6000)); 27 | 28 | // This server goes into a permanent loop, waiting for client request 29 | while(serverChannel.isOpen()){ 30 | // The accept method blocks until a request comes in, 31 | // and then the method returns a SocketChannel for communicating with the client 32 | SocketChannel clientChannel = serverChannel.accept(); 33 | 34 | /* 35 | Create an output stream for the client's channel, 36 | and wrap it in a PrintWrite. You can use newOutputStream or newWrite here. 37 | */ 38 | PrintWriter writer = new PrintWriter(Channels.newOutputStream(clientChannel)); 39 | 40 | String advice = getAdvice(); 41 | writer.println(advice); // Send the client a String advice message 42 | writer.close(); // close the writer, which will also close the client SocketChannel. 43 | System.out.println(advice); 44 | } 45 | 46 | }catch (IOException ex){ 47 | ex.printStackTrace(); 48 | } 49 | } 50 | 51 | private String getAdvice(){ 52 | int nextAdvice = random.nextInt(adviceList.length); 53 | return adviceList[nextAdvice]; 54 | } 55 | 56 | public static void main(String[] args) { 57 | new DailyAdviceServer().go(); 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /src/chapter_17/PingingClient.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.net.InetSocketAddress; 6 | import java.nio.channels.Channels; 7 | import java.nio.channels.SocketChannel; 8 | import java.nio.charset.StandardCharsets; 9 | import java.time.format.FormatStyle; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | import static java.time.LocalDateTime.now; 13 | import static java.time.format.DateTimeFormatter.ofLocalizedTime; 14 | 15 | public class PingingClient { 16 | public static void main(String[] args) { 17 | InetSocketAddress server = new InetSocketAddress("127.0.0.1", 6000); 18 | 19 | try(SocketChannel channel = SocketChannel.open(server)) { 20 | PrintWriter writer = new PrintWriter(Channels.newWriter(channel, StandardCharsets.UTF_8)); 21 | System.out.println("Networking established"); 22 | 23 | for (int i = 0; i<10; i++){ 24 | String message = "ping " + i; 25 | writer.println(message); 26 | writer.flush(); 27 | 28 | String currentTime = now().format(ofLocalizedTime(FormatStyle.MEDIUM)); 29 | System.out.println(currentTime + " Sent " + message); 30 | TimeUnit.SECONDS.sleep(1); 31 | } 32 | 33 | }catch (IOException | InterruptedException e){ 34 | e.printStackTrace(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/chapter_17/SimpleChatClient.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.io.BufferedReader; 6 | import java.io.IOException; 7 | import java.io.PrintWriter; 8 | import java.net.InetSocketAddress; 9 | import java.nio.channels.Channels; 10 | import java.nio.channels.SocketChannel; 11 | import java.nio.charset.StandardCharsets; 12 | import java.util.concurrent.ExecutorService; 13 | import java.util.concurrent.Executors; 14 | 15 | public class SimpleChatClient { 16 | private JTextField outgoing; 17 | private PrintWriter writer; 18 | private BufferedReader reader; 19 | private JTextArea incoming; 20 | 21 | 22 | private void go(){ 23 | setUpNetWorking(); 24 | 25 | JScrollPane scoller = createScrollableTextArea(); 26 | 27 | outgoing = new JTextField(20); 28 | 29 | JButton sendButton = new JButton("Send"); 30 | sendButton.addActionListener(e -> sendMessage()); 31 | 32 | JPanel mainPanel = new JPanel(); 33 | mainPanel.add(scoller); 34 | mainPanel.add(outgoing); 35 | mainPanel.add(sendButton); 36 | 37 | ExecutorService executor = Executors.newSingleThreadExecutor(); 38 | executor.execute(new IncomingReader()); 39 | 40 | 41 | JFrame frame = new JFrame("Simple Chat Client"); 42 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 43 | frame.setSize(400,350); 44 | frame.setVisible(true); 45 | frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 46 | } 47 | 48 | private JScrollPane createScrollableTextArea(){ 49 | incoming = new JTextArea(15,30); 50 | incoming.setLineWrap(true); 51 | incoming.setWrapStyleWord(true); 52 | incoming.setEditable(false); 53 | JScrollPane scoller = new JScrollPane(incoming); 54 | scoller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 55 | scoller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 56 | return scoller; 57 | } 58 | 59 | private void setUpNetWorking() { 60 | try { 61 | InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 6000); 62 | SocketChannel socketChannel = SocketChannel.open(serverAddress); 63 | 64 | reader = new BufferedReader(Channels.newReader(socketChannel, StandardCharsets.UTF_8)); 65 | writer = new PrintWriter(Channels.newWriter(socketChannel, StandardCharsets.UTF_8)); 66 | System.out.println("Networking established."); 67 | }catch (IOException e){ 68 | e.printStackTrace(); 69 | } 70 | } 71 | 72 | private void sendMessage(){ 73 | writer.println(outgoing.getText()); 74 | writer.flush(); 75 | outgoing.setText(""); 76 | outgoing.requestFocus(); 77 | } 78 | 79 | 80 | public class IncomingReader implements Runnable{ 81 | @Override 82 | public void run() { 83 | String message; 84 | 85 | try { 86 | while((message = reader.readLine()) != null){ 87 | System.out.println("read " + message); 88 | incoming.append(message + "\n"); 89 | } 90 | }catch (IOException e){ 91 | e.printStackTrace(); 92 | } 93 | } 94 | } 95 | 96 | public static void main(String[] args) { 97 | new SimpleChatClient().go(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/chapter_17/SimpleChatClientA.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | import java.net.InetSocketAddress; 8 | import java.nio.channels.Channels; 9 | import java.nio.channels.SocketChannel; 10 | import java.nio.charset.StandardCharsets; 11 | 12 | public class SimpleChatClientA { 13 | private JTextField outgoing; 14 | private PrintWriter writer; 15 | 16 | private void go(){ 17 | setUpNetWorking(); 18 | 19 | outgoing = new JTextField(20); 20 | 21 | JButton sendButton = new JButton("Send"); 22 | sendButton.addActionListener(e -> sendMessage()); 23 | 24 | JPanel mainPanel = new JPanel(); 25 | mainPanel.add(outgoing); 26 | mainPanel.add(sendButton); 27 | JFrame frame = new JFrame("Simple Chat Client"); 28 | frame.getContentPane().add(BorderLayout.CENTER,mainPanel); 29 | frame.setSize(400,100); 30 | frame.setVisible(true); 31 | frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 32 | } 33 | 34 | private void setUpNetWorking() { 35 | try { 36 | InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 6000); 37 | SocketChannel socketChannel = SocketChannel.open(serverAddress); 38 | writer = new PrintWriter(Channels.newWriter(socketChannel, StandardCharsets.UTF_8)); 39 | System.out.println("Networking established."); 40 | }catch (IOException e){ 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | private void sendMessage(){ 46 | writer.println(outgoing.getText()); 47 | writer.flush(); 48 | outgoing.setText(""); 49 | outgoing.requestFocus(); 50 | } 51 | 52 | public static void main(String[] args) { 53 | new SimpleChatClientA().go(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/chapter_17/SimpleChatServer.java: -------------------------------------------------------------------------------- 1 | package chapter_17; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | import java.net.InetSocketAddress; 7 | import java.nio.channels.Channels; 8 | import java.nio.channels.ServerSocketChannel; 9 | import java.nio.channels.SocketChannel; 10 | import java.nio.charset.StandardCharsets; 11 | import java.util.ArrayList; 12 | import java.util.concurrent.ExecutorService; 13 | import java.util.concurrent.Executors; 14 | 15 | public class SimpleChatServer { 16 | private final ArrayList clientWriters = new ArrayList<>(); 17 | 18 | public static void main(String[] args) { 19 | new SimpleChatServer().go(); 20 | } 21 | 22 | private void go(){ 23 | ExecutorService threadPool = Executors.newCachedThreadPool(); 24 | try { 25 | ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 26 | serverSocketChannel.bind(new InetSocketAddress(6000)); 27 | 28 | while(serverSocketChannel.isOpen()){ 29 | SocketChannel clientSocket = serverSocketChannel.accept(); 30 | PrintWriter writer = new PrintWriter(Channels.newWriter(clientSocket, StandardCharsets.UTF_8)); 31 | clientWriters.add(writer); 32 | threadPool.submit(new ClientHandler(clientSocket)); 33 | System.out.println("got a connection"); 34 | } 35 | }catch (IOException e){ 36 | e.printStackTrace(); 37 | } 38 | } 39 | 40 | private void tellEveryone(String message){ 41 | for (PrintWriter writer : clientWriters){ 42 | writer.println(message); 43 | writer.flush(); 44 | } 45 | } 46 | 47 | public class ClientHandler implements Runnable{ 48 | BufferedReader reader; 49 | SocketChannel socket; 50 | 51 | public ClientHandler(SocketChannel clientSocket){ 52 | socket = clientSocket; 53 | reader = new BufferedReader(Channels.newReader(socket,StandardCharsets.UTF_8)); 54 | } 55 | 56 | public void run(){ 57 | String message; 58 | try { 59 | while ((message = reader.readLine()) != null){ 60 | if (!message.isEmpty()){ 61 | System.out.println("read: "+ message); 62 | tellEveryone(message); 63 | } 64 | } 65 | }catch (IOException e){ 66 | e.printStackTrace(); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/chapter_18/RyanAndMonicaTest.java: -------------------------------------------------------------------------------- 1 | package chapter_18; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | public class RyanAndMonicaTest { 8 | public static void main(String[] args) { 9 | 10 | BankAccount account = new BankAccount(); 11 | RyanAndMonicaJob ryan = new RyanAndMonicaJob("Ryan", account, 50); 12 | RyanAndMonicaJob monica = new RyanAndMonicaJob("Monica", account, 100); 13 | 14 | ExecutorService executor = Executors.newFixedThreadPool(2); 15 | executor.execute(ryan); 16 | executor.execute(monica); 17 | executor.shutdown(); 18 | 19 | } 20 | } 21 | 22 | class RyanAndMonicaJob implements Runnable{ 23 | private final String name; 24 | private final BankAccount account; 25 | private final int amountToSpend; 26 | 27 | public RyanAndMonicaJob(String name, BankAccount account, int amountToSpend) { 28 | this.name = name; 29 | this.account = account; 30 | this.amountToSpend = amountToSpend; 31 | } 32 | 33 | @Override 34 | public void run() { 35 | goShopping (amountToSpend); 36 | } 37 | 38 | private void goShopping(int amount){ 39 | System.out.println(name + " is about to spend"); 40 | account.spend(name, amount); 41 | System.out.println(name + " finishes spending"); 42 | } 43 | } 44 | 45 | class BankAccount { 46 | private final AtomicInteger balance = new AtomicInteger(100); 47 | public int getBalance() { 48 | return balance.get(); 49 | } 50 | 51 | public void spend(String name, int amount){ 52 | int initialBalance = getBalance(); 53 | if (initialBalance >= amount){ 54 | boolean success = balance.compareAndSet(initialBalance, initialBalance - amount); 55 | 56 | if (!success){ 57 | System.out.println("Sorry " + name + ", you haven't spent the money."); 58 | } 59 | } 60 | else { 61 | System.out.println("Sorry, not enough for " + name); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/chapter_18/TwoThreadsWriting.java: -------------------------------------------------------------------------------- 1 | package chapter_18; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CopyOnWriteArrayList; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | 8 | public class TwoThreadsWriting { 9 | public static void main(String[] args) { 10 | ExecutorService threadPool = Executors.newFixedThreadPool(2); 11 | Data data = new Data(); 12 | threadPool.execute(() -> addLetterToData('a', data)); 13 | threadPool.execute(() -> addLetterToData('A', data)); 14 | threadPool.shutdown(); 15 | } 16 | 17 | private static void addLetterToData(char letter, Data data){ 18 | for (int i = 0; i<26; i++){ 19 | data.addLetter(letter++); 20 | try { 21 | Thread.sleep(50); 22 | }catch (InterruptedException e){ 23 | e.printStackTrace(); 24 | } 25 | } 26 | 27 | System.out.println(Thread.currentThread().getName() + data.getLetters()); 28 | System.out.println(Thread.currentThread().getName() + " size " + data.getLetters().size()); 29 | } 30 | } 31 | 32 | final class Data{ 33 | // Use a thread safe collection CopyOnWriteArrayList 34 | private final List letters = new CopyOnWriteArrayList<>(); 35 | 36 | public List getLetters() { 37 | return letters; 38 | } 39 | 40 | public void addLetter(char letter){ 41 | letters.add(String.valueOf(letter)); 42 | } 43 | } --------------------------------------------------------------------------------