Thinking in Java Fourth Edition Bruce Eckel Chapter 1 Exercise 5

Exercise 5: Modify the previous exercise so that the values of the data in DataOnly are assigned to and printed in main( ).

Solution:

public class DOTest2
{      
    public static void main(String[] args)
    {
        class DataOnly
        {
            int i;
            double d;
            boolean b;
            void show()
            {
                System.out.println(i);
                System.out.println(d);
                System.out.println(b); 
            }
        }  
        DataOnly data = new DataOnly();
        data.i = 234;
        data.d = 2.1234545;
        data.b = true;     
        data.show();
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 1 Exercise 4

Exercise 4: Turn the DataOnly code fragments into a program that compiles and runs.

Solution:

public class DataOnlyTest
{  
    public static void main(String[] args)
    {
        class DataOnly
        {
            int i;
            double d;
            boolean b;
            void show()
            {
                System.out.println(i);
                System.out.println(d);
                System.out.println(b); 
            }
        }  
        DataOnly data = new DataOnly();
        data.i = 3;
        data.d = 2.71828;
        data.b = false;    
        data.show();
    }
}

Output:

 

Thinking in Java Fourth Edition Bruce Eckel Chapter 1 Exercise 3

Exercise 3: Find the code fragments involving ATypeName and turn them into  a program that compiles and runs.

Solution:

public class ATNTest
{      
    public static void main(String[] args)
    {
        class ATypeName
        {
            int i;
            double d;
            boolean b;
            void show()
            {
                System.out.println(i);
                System.out.println(d);
                System.out.println(b); 
            }
        }  
        ATypeName a = new ATypeName();
        a.i = 3;
        a.d = 2.71828;
        a.b = false;       
        a.show();
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 1 Exercise 2

Exercise 2:  (1) Following the HelloDate.java example in this chapter, create a “hello,world” program that simply displays that statement. You need only a single method in your class (the “main” one that gets executed when the program starts). Remember to make it static and to include the argument list,  even though you don’t use the argument list. Compile the program with javac and run it using java . If you are using a different development environment than the JDK, learn how to compile and run programs in that environment.

Solution:

public class HelloWorld
{
    public static void main(String[] args)
    {      
        System.out.println("Hello World!");
    }
}

Output: