Thinking in Java

Bruce Eckel

Mentioned 24

Bruce Eckel's Classic, award-winning Thinking in Java, Fourth Edition - now fully updated and revised for J2SE 5.0!

More on Amazon.com

Mentioned in questions and answers.

Java has generics and C++ provides a very strong programming model with templates. So then, what is the difference between C++ and Java generics?

Java Generics are massively different to C++ templates.

Basically in C++ templates are basically a glorified preprocessor/macro set (Note: since some people seem unable to comprehend an analogy, I'm not saying template processing is a macro). In Java they are basically syntactic sugar to minimize boilerplate casting of Objects. Here is a pretty decent introduction to C++ templates vs Java generics.

To elaborate on this point: when you use a C++ template, you're basically creating another copy of the code, just as if you used a #define macro. This allows you to do things like have int parameters in template definitions that determine sizes of arrays and such.

Java doesn't work like that. In Java all objects extent from java.lang.Object so, pre-Generics, you'd write code like this:

public class PhoneNumbers {
  private Map phoneNumbers = new HashMap();

  public String getPhoneNumber(String name) {
    return (String)phoneNumbers.get(name);
  }

  ...
}

because all the Java collection types used Object as their base type so you could put anything in them. Java 5 rolls around and adds generics so you can do things like:

public class PhoneNumbers {
  private Map<String, String> phoneNumbers = new HashMap<String, String>();

  public String getPhoneNumber(String name) {
    return phoneNumbers.get(name);
  }

  ...
}

And that's all Java Generics are: wrappers for casting objects. That's because Java Generics aren't refined. They use type erasure. This decision was made because Java Generics came along so late in the piece that they didn't want to break backward compatibility (a Map<String, String> is usable whenever a Map is called for). Compare this to .Net/C# where type erasure isn't used, which leads to all sorts of differences (e.g. you can use primitive types and IEnumerable and IEnumerable<T> bear no relation to each other).

And a class using generics compiled with a Java 5+ compiler is usable on JDK 1.4 (assuming it doesn't use any other features or classes that require Java 5+).

That's why Java Generics are called syntactic sugar.

But this decision on how to do generics has profound effects so much so that the (superb) Java Generics FAQ has sprung up to answer the many, many questions people have about Java Generics.

C++ templates have a number of features that Java Generics don't:

  • Use of primitive type arguments.

    For example:

    template<class T, int i>
    class Matrix {
      int T[i][i];
      ...
    }
    

    Java does not allow the use of primitive type arguments in generics.

  • Use of default type arguments, which is one feature I miss in Java but there are backwards compatibility reasons for this;

  • Java allows bounding of arguments.

For example:

public class ObservableList<T extends List> {
  ...
}

It really does need to be stressed that template invocations with different arguments really are different types. They don't even share static members. In Java this is not the case.

Aside from the differences with generics, for completeness, here is a basic comparison of C++ and Java (and another one).

And I can also suggest Thinking in Java. As a C++ programmer a lot of the concepts like objects will be second nature already but there are subtle differences so it can be worthwhile to have an introductory text even if you skim parts.

A lot of what you'll learn when learning Java is all the libraries (both standard--what comes in the JDK--and nonstandard, which includes commonly used things like Spring). Java syntax is more verbose than C++ syntax and doesn't have a lot of C++ features (e.g. operator overloading, multiple inheritance, the destructor mechanism, etc) but that doesn't strictly make it a subset of C++ either.

This is the code I have:

public class StupidClass {
    static {
        System.out.println("Stupid class loaded!");
    }
}

And the tests I have, which I run separately.

import org.junit.Test;

public class StupidTest {
    @Test
    public void foo() throws ClassNotFoundException {
        final Class<?> stupidClass = Class.forName("StupidClass");
        System.out.println(stupidClass.getSimpleName());
    }

    @Test
    public void bar() throws ClassNotFoundException {
        final Class<StupidClass> stupidClassClass = StupidClass.class;
        System.out.println(stupidClassClass.getSimpleName());
    }
}

When I run test foo I will see:

Stupid class loaded!
StupidClass

But when I run the test bar all I see is:

StupidClass

Quoting from this page..

Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

So my understanding is, in test bar, Stupid class is loaded, otherwise I would have seen a null I guess? So Class object is created because class itself is loaded..

And now quoting from this page

Static initialization blocks are run when the JVM (class loader - to be specific) loads StaticClass (which occurs the first time it is referenced in code).

So I am expecting to see the "Stupid class loaded!" text in test bar as well, but I am not.

Also quoting from Thinking in Java

Each of the classes Candy, Gum, and Cookie has a static clause that is executed as the class is loaded for the first time.

which is not very accurate it seems..

What am I missing?

Static initialization blocks are run when the JVM (class loader - to be specific) loads StaticClass (which occurs the first time it is referenced in code).

The above quote is plain wrong, but it is just one instance of a very widespread misconception.

  1. Class is not initialized when it's being loaded, but when a static class member is first referenced. This is precisely governed by the specification.

  2. Class loading does not occur when the class is first referenced, but at an implementation-dependent point.

  3. The last moment when the class must be loaded is when the class is referenced, which is not the same as referencing a class member.

Class.forName initializes the class by default, but you have the choice of calling an overload that takes a boolean initialize and supplying false. You'll get the class loaded without initializing.

I was wondering when I should use interfaces.

Lets think about the following:

public abstract class Vehicle {
   abstract float getSpeed();
}

and :

public interface IVehicle {
  float getSpeed();
}

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

What is the reason to use interfacs?

Thanks!

EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

From Java How to Program about abstract classes:

Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

To answer your question "What is the reason to use interfacs?":

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.

As opposed to an interface:

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

This is an direct excerpt from the excellent book 'Thinking in Java' by Bruce Eckel.

[..] Should you use an interface or an abstract class?

Well, an interface gives you the benefits of an abstract class and the benefits of an interface, so if it’s possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes.

In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change to an abstract class.

What are the pro's and con's of calling out to a mutator from a constructor (if any)

i.e.:

public MyConstructor(int x) {
  this.x = x;
}

versus:

public MyConstructor(int x) {
  setX(x);
}

public void setX(int x) {
  this.x = x;
}

Do you have a preference? (This is not homework, just looking at our coding standards doc where it says to always call out to mutators when setting instance var's in the constructor and I don't always to this)

Invoking any public, static, non-final methods within constructor it's up to you, but the best practice is never invoke such methods within constructor, because this methods can be overridden in subclasses and actually only overridden version of this methods will be invoked (If you use polymorphic behavior).

For example:

public class Foo {

public Foo() {
    doSmth(); // If you use polymorphic behavior this method will never be invoked
}

public void doSmth() {
    System.out.println("doSmth in super class");
}

public static void main(String[] args) {
    new Bar(200);
}
}

class Bar extends Foo {

private int y;;

public Bar(int y) {
    this.y = y;
}

@Override
public void doSmth() { // This version will be invoked even before Barr object initialized
    System.out.println(y);
}

}

It will print 0.

For mo details read Bruce Eckel "Thinking in Java" chapter "Polymorphism"

It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.

The typical solutions are to make either a struct or a plain old data class and return that, or to pass at least some of the parameters by reference or pointer instead of returning them.

Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass.

The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity.

Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.

The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:

a, b = foo(c)  # a and b are regular variables.
myTuple = foo(c)  # myTuple is a tuple of (a, b)

Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.

As for Java, see Bruce Eckel's Thinking in Java for a nice solution (pp. 621 ff).

In essence, you can define a class equivalent to the following:

public class Pair<T,U> {
    public final T left;
    public final U right;
    public Pair (T t, U u) { left = t; right = u; }
}

You can then use this as the return type for a function, with appropriate type parameters:

public Pair<String,Integer> getAnswer() {
    return new Pair<String,Integer>("the universe", 42);
}

After invoking that function:

Pair<String,Integer> myPair = getAnswer();

you can refer to myPair.left and myPair.right for access to the constituent values.

There are other syntactical sugar options, but the above is the key point.

What is the quickest/easiest way to learn Java for a seasoned .NET/C# (more than 7 years) and C++ (5years) developer.

When I say to learn Java - I mean being able to write applications in a "Java way" using base classes library + where needed using a popular Java libraries (it is great that so many of them are open source).

I know that Java development comes in a lot of flavors - enterprise applicatons (Java EE), mobile devices (Java ME), objects hosted in application servers (to my knowledge Java has a buch of these) - however at the moment I am interested in a general Java development - may be with a some emphasis on a integration projects/enterprise development.

So basically - I am a strong, passionate about technology, proud to be a senior C#/C++ developer with a dozen years of experience who wants to dedicate a month-worth (may be more) of evenings to learn to effectively program in Java environment.

Having said that I don't mean I am switching from .NET/C++ to Java - but I would probably going have to spend 30%-50% of my devevelpment time developing/supporting/whateverstageintheSDLC in Java.

Thank you.

I am on the quest to be a good OO-developer. OO intrigues me, because I understand the patterns, know why composition gives you more flexibility then inheritance, and more of such wisdom. However, I came to the conclusion that I know how to implement a factory of a singleton, but that I do not know how to come up with a robust OO design.

I have a bunch of books

  1. Design Patterns by the GoF
  2. AntiPatterns Brown et al.
  3. Refactoring by Fowler
  4. Code complete 2

They might be very good books, but they don't teach you to architect an application. I am often paralysed by some very basic decisions (example). I am looking for a book that teaches the when and why. There are many books about hammers and nails, but I have yet to find a book that tells you something about their practical relationship.

What book was most instrumental in making you a confident OO-architect/designer?

  1. "Object-oriented software construction" by Bertrand Meyer

Most fundamental work about object-orientation ever published. This is absolutely must have book for every "object-oriented" programmmer.

2. "Object-Oriented Analysis and Design with Applications" by Grady Booch et al

Not so formal as Meyer's book, but this book can open your eyes on many questions in object-oriented world and in software development in general

3. "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma et al.

This is famous "Gang of Four" book about design patterns

4. "Refactoring: Improving the Design of Existing Code" by Martin Fowler et al.

This is another classical book. First part perfectly describe many problem that modern software developer may faced during his work: code smells, readability vs performance, premature optimization drawbacks and many other topics.

5. "Thinking in Java" by Bruce Eckel

This book may help many beginners not only in Java language but in object-oriented way of thinking too.

6. "Touch of Class: Learning to Program Well with Objects and Contracts" by Bertrand Meyer

Excellent textbook by famous author.

Craig Larman's Applying UML and Patterns summarized a lot about what I had learned from experience. What I like about it is that it addresses all the aspects of software design -- which includes things like iterative design and development. Don't stare too hard at the use of UML: design descriptions are a means towards an end, and I found Larman's approach fairly pragmatic. You can't just code: you have to communicate your intentions (and understand what is needed). UML and cleanly designed, well commented code are some of the means towards that end.

And, of course, as others mention: no book will make you a good developer or designer. But it might help accelerate the process.

After reading some questions and answers about enum I don't find it really useful...

It's something between class and a variable but I know where can I use it so it would be more useful then a class, or a couple of variables for example.

I use Enums for anything that has multiple nonchanging "type" of something. i.e days of a week.

Why I don't use String in this case is because I can't do switch statement on the String and I can on Enum so for every day of a week I can do something specific.

I also use Enum when working with singleton pattern, Check the Effective Java book CH2(CHAPTER 2 CREATING AND DESTROYING OBJECTS), quote :

"While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton." not gonna paste code read the book it's excellent.

If I were you I'd firstly read Thinking in java chapter Enumerated Types. Then after that Effective Java chapter 6 and you should be good

I've been doing C++ development for the last 5 years and need to pick up Java for a new job. Do you have any suggestions on books/websites/etc to help me with the transition?

Bruce eckel's free book : http://www.mindview.net/Books/TIJ/

CORE JAVA :

Effective Java, 2nd edition

http://www.amazon.com/Java-Generics-Collections-Maurice-Naftalin/dp/0596527756 -- book on java generics. nice.

Then again, more depends on whether you're going to build desktop apps or serverside apps.

Good luck with java

javaranch
infoq.com
theserverside.com
javablogs.com
jguru.com

Head First Java is the best book for learning Java. It's an introduction to object oriented programming, as well as Java, so as an experienced programmer you might be better served by Thinking in Java.

What is the java class type used for? I am confused about what it means and how it is different than declaring an object type:

Class className;

Thanks

From the book Thinking in Java:

The Class object

To understand how Run Time Type Information (RTTI) works in Java, you must first know how type information is represented at run time. This is accomplished through a special kind of object called the Class object, which contains information about the class. In fact, the Class object is used to create all of the 'regular' objects of your class.

I am looking for a good and short article+examples of how working with interfaces. I am not interesting the technical part, but I need the design part. For example, how to programming using interfaces, when and how create implementations, design patterns for regular development with interfaces.

I have many similar classes that repeat themselves in several ways. I want to use interfaces and abstract classes in order to make things more modular - but I can't find out how to do it properly.

This book as been the canonical reference for design patterns and contains examples of using interfaces. However you may want to start at an even more fundamental level. Thinking in Java is what got me into object oriented programming, there are likely similar titles for C# though the content of the book should be mostly agnostic of the language. You may also search for online tutorials on object oriented programming.

Edit: Great book about patterns and their implementation and usage in C# is C# 3.0 Design Patterns

@Naor, its seems, based on your above comment "It doesn't seem logical to create interface for each class I have - right?" that the best book for you to read is HEAD FIRST; DESIGN PATTERNS - it has an incredible and easy way of teaching how to use an apply design patterns. I first read of them in this book and it has definetly changed my mind!!! By reading this you'll be able to read more complicated stuff like Martin Fowler, Patterns of Enterprise Application Archtecture - which I believe approaches exatcly what you want, real world applicatoins of patterns. Going straight to to GoF, or M. Fowler, or more complicated stuff may disspoint you or make you just lose time.

I'e been programming Java forever, but have been away from it for a while. Can anyone recommend a really good Java reference, where "really good" is defined by "Good coverage of the language, detailed coverage of recent extensions, and written for the technical reader (not a "for Dummies" sort of book)"?

As well as references saying what has changed in the languages (which other answers already cover better than I could) I can't recommend highly enough the Second edition of Effective Java by Joshua Bloch - which explains the most effective ways of using the language.

I'm a newbie Java programmer, who is reading Thinking In Java by Bruce Eckel.

In the 5th chapter, operators have been discussed. Where it is talking about shift operators (<<, >>, >>>) he says:

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

Which I can't understand the meaning. Specially the bold sentences. Could you clarify it a bit?

I feel that the other answers are a bit incomplete.

It's true that an int is 32 bits, and the language doesn't let you shift more than 32 bits. What's gotten left out is that if you tell it to shift more than 32 bits, the shift amount will be taken modulo 32. That is, if x is an int, x >> 32 is the same as x >> 0 (i.e. just x), x >> 33 is the same as x >> 1, x >> 66 is the same as x >> 2, etc. Using only the low-order 5 bits of the right argument is the same as taking the argument modulo 32 (using the mathematical definition, so that -1 mod 32 == 31, -2 mod 32 == 30, etc.).

Similarly, long is 64 bits, which means that the right argument is computed modulo 64, which is the same as using only the low-order 6 bits of the right argument.

Why Java did it this way, I don't know. In my opinion, it would be more consistent if it simply let you shift by a large amount, shifting all the bits out of the integer and resulting in 0 (except that >> sign-extends, so the result would be 0 or -1). It would be consistent mathematically, because for positive x and y, x >> y would always be equal to x / (2^y) truncated down to an integer, even if y >= 32. Java's way of handling shift amounts that are >= 32 or >= 64 isn't useful in any way I can see.

I'm curious is there any real difference between usage of raw Class type and generic Class<?> one? I actively use both Java SE 6 and SE 7. At least Oracle generics tutorial has no answer to this question and my initial try to google around did not bring any suitable result.

Thank you in advance.

The unbounded wildcard <?> appears to mean "anything", and so using an unbounded wildcard seems equivalent to using a raw type. Indeed, the compiler seems at first to agree with this assessment:

import java.util.ArrayList;
import java.util.List;

public class UnboundedWildcards1 {
    static List list1;
    static List<?> list2;
    static List<? extends Object> list3;

    static void assign1(List list) {
        list1 = list;
        list2 = list;
        // list3 = list; // Warning: unchecked conversion
        // Found: List, Required: List<? extends Object>
    }

    static void assign2(List<?> list) {
        list1 = list;
        list2 = list;
        list3 = list;
    }

    static void assign3(List<? extends Object> list) {
        list1 = list;
        list2 = list;
        list3 = list;
    }

    public static void main(String[] args) {
        assign1(new ArrayList());
        assign2(new ArrayList());
        // assign3(new ArrayList()); // Warning:
        // Unchecked conversion. Found: ArrayList
        // Required: List<? extends Object>
        assign1(new ArrayList<String>());
        assign2(new ArrayList<String>());
        assign3(new ArrayList<String>());
        // Both forms are acceptable as List<?>:
        List<?> wildList = new ArrayList();
        wildList = new ArrayList<String>();
        assign1(wildList);
        assign2(wildList);
        assign3(wildList);
    }
}

There are many cases like the ones you see here where the compiler could care less whether you use a raw type or <?>. In those cases, <?> can be thought of as a decoration; and yet it is valuable because, in effect, it says, "I wrote this code with Java generics in mind, and I don't mean here that I'm using a raw type, but that in this case the generic parameter can hold any type."

A second example shows an important use of unbound wildcards. When you are dealing with multiple generic parameters, it's sometimes important to allow one parameter to be any type while establishing a particular type for the other parameter:

import java.util.HashMap;
import java.util.Map;

public class UnboundedWildcards2 {
    static Map map1;
    static Map<?, ?> map2;
    static Map<String, ?> map3;

    static void assign1(Map map) {
        map1 = map;
    }

    static void assign2(Map<?, ?> map) {
        map2 = map;
    }

    static void assign3(Map<String, ?> map) {
        map3 = map;
    }

    public static void main(String[] args) {
        assign1(new HashMap());
        assign2(new HashMap());
        // assign3(new HashMap()); // Warning:
        // Unchecked conversion. Found: HashMap
        // Required: Map<String,?>
        assign1(new HashMap<String, Integer>());
        assign2(new HashMap<String, Integer>());
        assign3(new HashMap<String, Integer>());
    }
}

But again, when you have all unbounded wildcards, as seen in Map<?,?>, the compiler doesn't seem to distinguish it from a raw Map. In addition, the first example shows that the compiler treats List<?> and List<? extends Object> differently.

For more information you are welcome to read Bruce Eckel's book: Thinking in Java

Because of the nature of new project we are about to start, I need to get into Java world rather quickly.

I have about 8 years of PHP experience, and about 3 year in Javascript. (CI, Kohana and my own MVC framework)

I have solid knowledge of OOP (as much as you can get from PHP/JS and little ActionScript & python here and there)

So instead of learning from scratch, i was thinking to grab some web framework (at the end, project will be web based) and learn java along the way. Java code it self don't seam too strange, and i have solid experience with MVC in php so the whole concept makes sense to me.

So I'm looking a list of instructions on how should I learn Java.

(and not to spend too much time on things that are not so important)

Also you can suggest framework, from what i seen, struts looks nice, spring too, but it seam that it have too much XML configuration...

None of them required extensive XML configuration anymore, those were the old days.

I will suggest you to grab Java concepts, anyway. Grab a good Java book to learn it along the way, as you said. Thinking in Java is good to go, but its just about core java and concepts. For java web you might want to look into Servlet and JSP basic, which you can learn using official J2EE Tutorial from Sun.

For Java web framework, there are plenty. But I would suggest you something you are already familiar with. You are right MVC based Java framework. Struts and Spring both are MVC frameworks and give you are clear separation of layers. Spring is a giant in itself, it has the answer for almost everything, that might confuse you in the start. Struts 1 is already outdated, and Struts 2 has a very tough competition.

I would suggest you to look into Wicket. It just a web framework, unlike Spring, and a very well written and easy to grasp.

Its a tough task, I must say. Lets see what other has to recommend.

Hi I'm a techie with no programing experience. I know html and css, but I'd like to someday be able to make an app for my phone (I have an android) and possibly mobile websites.

I made learning a programing language and creating a mobile app a goal for my job, and now my boss would like me to pick a programing language to learn. I found a free open course from MIT (http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/) called introduction to computer science. In the course they teach python, but more importantly it seems they teach how to think like a programmer.

When I told my boss about the free online course she didn't think that Python was an appropriate language for me to learn. She'd like me to learn a language that is more similar to one used to make Phone apps. Does anyone out there know a better language for me to pick up that would be similar to Android or iPhone's App language.

Thank you

A few things stood out to me as your goals:

  1. You want formal training on how to program (this is independent of a language)
  2. You want to learn how to develop apps for a mobile device
  3. Your boss is on board with goals 1 and 2, but wants to see the best return on her investment.

I think the easiest way for you to meet all of these goals is to start learning how to program with Java. Java is often used in introductory computer science courses, so you should be able to learn the language and programming concepts in parallel. Once you have that foundation, you will be able to start learning Android development, since Android applications are built with the Java language.

You can start off by reading some of the resources from Oracle: http://download.oracle.com/javase/tutorial/java/concepts/index.html

And there are plenty of good intro books too:

There is nothing wrong with starting off by learning Python. Once you have a good grasp of programming fundamentals, you can learn new languages relatively quickly. However, from your boss's perspective, there is more value in paying for you to learn a language for mobile development and programming at the same time.

I am going to begin my Computer Science & Information Systems degree in April. My first class is an introduction to Java programming.

Lately I have had an interest in Objective-C, but slowly declined due to lack of persistence and comprehension difficulties, (mostly some OOP). Obviously I would like to do well in my classes, so I am asking what is the best way for me to prepare?

Should I complete the Alice training and then start learning some Java on my own? Continue to work through Objective-C religiously until I see results? What do you think a newby should do?

edit: I have been reading reviews for a lot of Java books, just curious, are there any other well written beginner books? Thanks!

Objective-C probably has some barriers that will be problematic if you're learning.

I would suggest picking up a copy of either Thinking in Java or Head First Java and reading through that to get started.

When you're learning it can be useful to not be distracted by too many details. Master the basics. Learn about basic OO design. Frustration is the biggest enemy. If what you're doing seems daunting, the greater the chance you'll just give up. So keep it simple so each time you do something it feels like you're making progress.

I am new to Java, hence this basic question.

I am having trouble in accessing a field (jlabel in this case) throughout the program. My code is as follows :

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class accessvariable {

    public static void main(String[] args) {

        //basic setup of display frame
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        JPanel panel=new JPanel();

        //text field to take user input
        JTextField txt= new JTextField(10);

        //adding action listener for text field
        txt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (true) { //if condition not checking anything here, just to make it enter the loop
                    JLabel j =new JLabel("Access successful"); //a jlabel created inside this 
                    System.out.println("inside j : "+j.getText()); //statement to check whether jlabel is accessible from here
                }
            }
        });

        System.out.println("outside j : "+j.getText()); //statement to check whether jlabel is accessible from here

        //basic setup for final display
        panel.add(txt);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

The error is on this line:

System.out.println("outside j : "+j.getText());

If I comment out this line, it works fine. The inside j is displayed correctly. But if I don't comment it, I am getting this error:

Exception in thread "Exception in thread "main" java.lang.Error: Unresolved compilation problem: j cannot be resolved"

To correct this, I have made j an instance variable as follows:

private JLabel j; 

However the above is generating a new error:

Cannot make a static reference to the non-static field j

I understand that the problem is with this single line:

System.out.println("outside j : "+j.getText());

How can I fix the above problem so that if it works correctly, the output when I enter some text in the text field should be as follows:

inside j : Access successful
outside j : Access successful

Wait. Stop. Start over.

Your program is nothing more than a static main method, which is fine for "Hello World" type programs, but if you are desiring to create anything more powerful, you will want to, no need to learn about Object-Oriented concepts and how to apply them in Java programs. For instance, for a start for this project you should create at least one class that has non-static fields and methods, including a field for your JLabel (by which you would allow non-static methods of your class access to this field), and you should build your GUI, meaning add components to the containers, outside of the main method, and more like in some non-static init() method or constructor. The main method should only be for creating your objects and setting them into action and little else. But again most importantly, learn OOP concepts and how they relate to the Java programming language. A decent book for this is Bruce Eckel's "Thinking in Java".

Another concept to hit hard now is scope including variable scope. If you have a variable, here the JLabel variable, j, buried and declared not just inside of a method, but in a method that is buried inside of an anonymous inner ActionListener class, it will be almost impossible for other class code to interact with this variable. If it is an instance field, then it is visible throughout all the non-static parts of the class that holds it.

For example:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class AccessVariable extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private JLabel myLabel = new JLabel();
    private JTextField textField = new JTextField(10);

    public AccessVariable() {
        add(textField);
        add(myLabel);

        textField.addActionListener(new MyListener());
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private class MyListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            myLabel.setText("Text is: " + text);

            textField.requestFocusInWindow();
            textField.selectAll();
        }
    }

    private static void createAndShowGui() {
        AccessVariable mainPanel = new AccessVariable();

        JFrame frame = new JFrame("Access Variable");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

I have always had problems reading documentation for example I was just researching about file paths for java and I so this : " Usage Example:

Path file = ...
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);

" //http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributes.html

What is ..... ??? :| I know im not a expert but example code that is full coded would be nice, Or Is is it becouse im not at that level yet...

I tried testing it..did not even run :(

Please Help

The ... is called an ellipsis, and means that something has been left out there. On this case, it's a call to the Path constructor, putting a path in place ready for the rest of the code.

They do that because they don't want to clutter the example with extraneous stuff.

If you want fully coded examples, the Java Almanac has good ones, albeit a little dated.

http://www.amazon.com/The-Java%C2%BF-Developers-Almanac-Volume/dp/0201752808

API documentation is meant to give you details about a particular class and serve as a reference to come back to. It's purpose is not to provide you with an explanation how concepts fit together. So ... stands as a placeholder for any code that might make sense in a particular use case. For a general overview Oracle hosts an excellent set of tutorials.

And if you want to see even a bigger picture, I can recommend an excellent book Thinking in Java.

I met this variations of switch statement, and I wondering to know in witch cases it can be used?

Strangeness is because it doesn't have cases before default value, only after. And doesn't have break statement. But works fine.

Here is code:

public static Item newItem() {
    switch (rand.nextInt(3)) {
    default:
    case 0:
        return new Scissors();
    case 1:
        return new Paper();
    case 2:
        return new Rock();
    }
}

How does it really can be execute at this strange style. I tried to make easy debugging all works fine it return accuracy one explicit instance.

Question: why does we need write:

default:
case 0: 

instead typical usage:

case 0:
default:

Compiler didn't let to change or comment default statement.

Any suggestions?

PS please, don't write silly explanation how does switch works. it's clear. write only about this explicit example.

BTW I met this peace of code at Thinking in Java by Bruce Eckel.

The default branch just means "the branch for all the options not explicitly specified. It's a convention to put it at the end of the switch-case statement, but is not required.

break is also not required - if a branch of the switch-case does not end with break, it will just continue on executing the code in the next branch - this is called fallthrough. However, here you do not need it because each branch just returns, so the function's execution does not continue.

Im inserting 3 values into a database on a click of a button, 1 is the insert date, 2 is a number from a editText and the 3rd is the value assigned to the button being clicked(there are six different buttons that can be clicked)

What I want to do is check if the date and number are already in the database the 3rd value does not matter. I cant use unique on any of the columns as I want the number from the editText to be able to be entered again but just not on the same day.

I have got this far... and it does not enter any data to database

From MainActivity

    public void onClick_30(View v) {

    counter++;
    cnt_bcs30++;

    String getCowNum = CowNum.getText().toString();

    Cursor C = myDB.dubUpCheck();
    String ddate = C.getString(DBAdapter.COL_DATE);
    String cow = C.getString(DBAdapter.COL_COW);


    if(C.moveToFirst()){

        do {

            if(ddate == dateFormat.format(date) && cow == getCowNum){
        Toast.makeText(getBaseContext(), getCowNum + "Has already been scored today ",
                Toast.LENGTH_SHORT).show();
            }
        }while (C.moveToNext());


    }else{



    myDB.insertRow(dateFormat.format(date), getCowNum, 3.0);

    Toast.makeText(getBaseContext(), getCowNum + " " + score30,
            Toast.LENGTH_SHORT).show();
    CowNum.clearFocus();
    }
}

From my DBAdapter

            public Cursor dubUpCheck() {

    Cursor c = db.query(DATABASE_TABLE, new String []{KEY_DATE, KEY_COW}, null, null,
            null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }

    return c;

}

I need to check if there is a row with dateFormat.format(date) and getCowNum but i cant seem to get it to work, not sure if it is due to the way I am storing the date which is a string in the format of dd-MM-yyyy

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = new Date(); 

like this, enters data but still allows dupicates

    public void onClick_30(View v) {

    counter++;
    cnt_bcs30++;

    String getCowNum = CowNum.getText().toString();

    Cursor C = myDB.dubUpCheck();
    String ddate = C.getString(DBAdapter.COL_DATE);
    String cow = C.getString(DBAdapter.COL_COW);


    if(ddate == dateFormat.format(date) && cow == getCowNum){
        Toast.makeText(getBaseContext(), getCowNum + "Has already been scored today ",
                Toast.LENGTH_SHORT).show();
        }else{



    myDB.insertRow(dateFormat.format(date), getCowNum, 3.0);

    Toast.makeText(getBaseContext(), getCowNum + " " + score30,
            Toast.LENGTH_SHORT).show();
    CowNum.clearFocus();
    }

UPD: Another attempt... the else statement is in the wrong place I know but thats not all thats wrong Im guessing

        public void onClick_30(View v) {

    counter++;
    cnt_bcs30++;

    String getCowNum = CowNum.getText().toString();

    Cursor C = myDB.dubUpCheck();
    String ddate = C.getString(DBAdapter.COL_DATE);
    String cow = C.getString(DBAdapter.COL_COW);

    if (C.moveToFirst()) {
        do {
            if (ddate.equals(dateFormat.format(date)) && cow.equals(getCowNum)) {

                Toast.makeText(getBaseContext(),
                        getCowNum + "Has already been scored today ",
                        Toast.LENGTH_SHORT).show();

            }

        } while (C.moveToNext());
    } else {

        myDB.insertRow(dateFormat.format(date), getCowNum, 3.0);

        Toast.makeText(getBaseContext(), getCowNum + " " + score30,
                Toast.LENGTH_SHORT).show();
        CowNum.clearFocus();
    }
}

Why not just a simple WHERE?

/** @return true if given date/cowNum combination is already in the db, false otherwise */
public boolean dubUpCheck(Date date, String cowNum) {
  /* The 3rd parameter is treated as SQL WHERE clause, ? are replaced by strings
   * from the 4th parameter */
  Cursor cur = db.query(DATABASE_TABLE, null, "DATE = ? AND COW_NUM = ?", new String[] {dateFormat.format(date), getCowNum}, null, null, null, null);
  if (cur != null && cur.getCount()>0) {
      // duplicate found
      return true;
  }
  return false;
}

UPD In your approach where you manually compare strings you've made a classic Java rookie mistake. You're comparing String objects using the operator == : it will return false for different [in terms of instances] objects that might actually be identical content-wise (e.g. this "foo" == new String("foo") will give you false). You have to use .equals() like so:

ddate.equals(dateFormat.format(date)) && cow.equals(getCowNum)

But really, try the approach above, it creates less objects and will spare you all the string comparison stuff.

It seems you could benefit from reading a good book on Java -- e.g. Thinking in Java by Bruce Eckel is hands down one of the most awesome reads for both novice and intermediate Java devs

I am relatively new in Java. In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe. Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist. Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe. If I can access the arraylist then I think I can move forward. My question is "How can I access arraylist from one jframe (ShowDataFrame) to another frame(LoadDatafromExcelframe)?"I am using Netbeans IDE.

private void jMenuItemShowDataActionPerformed(java.awt.event.ActionEvent evt) {                                                   
            showDataFrame.setVisible(true);
}

The key issue has little to do with JFrames or Swing in fact, but is simply one of passing information from one object to another. The only way Swing gets involved is if you want to pass this information in response to an event of one sort or another.

The solution is usually one of simply giving your classes appropriate getter and setter methods, of separating out your "model", the logical portion of your program, from your "view", the GUI portion of your program, and of using some sort of listener or observer type interface (such as can be obtained via Swing event listeners) to notify one class when the other is ready to push or pull information.

More general recommendations:

  • Avoid making anything static that does not need to be static. That is a quick solution that usually causes more pain in the long run as it makes your code very hard to enhance later and to test.
  • Avoid using lots of JFrames. Most professional GUI's have but one master window, one "JFrame" if you will. Often it is better to swap views in this JFrame such as with a CardLayout or with tabbed panes if needed. Also information that needs to be obtained in another window in a modal fashion can be displayed in a modal dialog.
  • Get a good book on OOPs basics as it applies to Java programming, such as Bruce Eckel's "Thinking in Java".
  • And get a good book on use of design patterns with Java such as Head First Design Patterns. These two concepts are key to moving ahead in Java.
  • Avoid using code generation utilities such as NetBean's form creation utility as it shields you from learning Swing specifics, and hinders your ability to learn to create complex Swing GUI's. Sure, use these tools once your a Swing journeyman, but until then, use the Swing tutorials to learn the library and code by hand.

For more specific advice, you will need to provide more details and provide more code.


Edit 2

More advice based on your post:

In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe.

This looks to be better implemented creating 3 JPanels and not 3 JFrames. Then you could display the JPanels as needed in a single JFrame using a CardLayout to help you swap them.

Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist.

This ArrayList should not be "read into a JFrame" but rather the data belongs in a non-GUI class, one of your "model" classes to be exact. Then the view classes, your GUI code can ask the model for this data whenever necessary. Read up on Model-View-Control program design on this site to learn more about this useful pattern.

Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe.

Here using MVC structure, one of your "view" classes, the one holding the "menulist" should notify the "control" class that your code needs the ArrayList data held by the "model" class. This could all be done by having the Control class hold references to both "model" and "view" and having the "view" class hold references to the control thus allowing communication between classes.

i have been trying to make an easy calculator

    import java.util.Scanner;

    public class Math {

    static Scanner input = new Scanner(System.in);

    private static void Add(int a, int b,int c){

        System.out.println("First nummber...");
        a = input.nextInt();
        System.out.println("secound nummber...");
        b = input.nextInt();

        c = a + b;

        System.err.println(c);



    }

    public static void main(String[] args) {

        Add();

    }

}

but i got this error " The method Add(int, int, int) in the type Math is not applicable for the arguments () "

i tried then to add the variables to the Add() in the main function

public static void main(String[] args) {

    Add(a,b,c);

}

and then i got this error " Multiple markers at this line - b cannot be resolved to a variable - c cannot be resolved to a variable - a cannot be resolved to a variable "

How can i call the Add() function ?

You can re-write your code like this.

import java.util.Scanner;

public class Math {

   static Scanner input = new Scanner(System.in);

   private static int Add(int a, int b){    
       return a + b;
   }

   public static void main(String[] args) {
       System.out.println("First nummber...");
       int a = input.nextInt();
       System.out.println("secound nummber...");
       int b = input.nextInt();
       int c = Add(a,b);
       System.out.println(c);        

   }

}

But from your code I can see that you are really new to java perhaps new to programming. So I will recommend you to learn basic java and programming first. You can learn online from

Or can read some books

Can someone tell me what is the need to declare a class like this:

public class Test {

 String k;
 public Test(String a, String b, String c){
  k = a + " " + b + " " + c; //do something

 }

 public void run(){
  System.out.println(k);
 }

 public static void main(String[] args) {
  String l = args[0];
  String m = args[1];
  String n = args[2];
  Test obj = new Test(l,m,n);
  obj.run();
 }

}

Of course it works but I don't get the point why would one use such way to implement something. Is it because we need to pass arguments directly to the class main method that is why we use this way or is there some other reason?

What is the purpose of public Test(...) using the same class name. Why is it like this?

Learn Java.

A constructor is a function that gets called to create an object, and it's denoted by a function with the same name as the class, but no return type. Multiple constructors can be declared with different arguments.

In this case, the arguments are taken out of the argument array and passed as arguments to the constructor for Test.

These are fundamentally basic concepts to the Java programming language. You should read up on Java. Try Thinking in Java, this is a great book to get started.