Static final in (Class or Interface)

Hello Friends ,
What is the difference in having a public static final variable in an class and having the same kind of
declarations in an Interface ?
Does the interface is better or having it in a class ?
Thanks in Advance,
-S

shyamnambiar wrote:
But I'm not clear . you mean to say its all the same .It does not make any difference ?The only difference that it makes (and that might be an important difference) is what you communicate with your design an intention.
Constants should usually be placed within their context since that's where they are going to be used, and that's where developers will look. It's more common to place the constants in the class that they are related to. They should not be placed in an empty final class just because you want to group constants. You should also avoid placing constants in an interface just because you then can implement that interface to "get hold of" the constants.
Kaj

Similar Messages

  • ERROR: serializable class HelloComponent does not declare a static final

    Hi everyone! I'm sorry but I'm a newbie to Java and I'm having some, I assume, basic problems learning to compile and run with javac. Here is my code:
    import javax.swing.* ;
    import java.awt.* ;
    public class MyJava {
    * @param args
    public static void main(String[] args)
    // TODO Auto-generated method stub
    JFrame frame = new JFrame( "HelloJava" ) ;
    HelloComponent hello = new HelloComponent() ;
    frame.add( hello ) ;
    frame.setSize( 300, 300 ) ;
    frame.setVisible( true ) ;
    class HelloComponent extends JComponent
    public void paintComponent( Graphics g )
    g.drawString( "Hello Java it's me!", 125, 95 ) ;
    And here is the error:
    1. WARNING in HelloJava.java
    (at line 20)
    class HelloComponent extends JComponent {
    ^^^^^^^^^^^^^^
    The serializable class HelloComponent does not declare a static final serialVersionUID field of type long
    ANY HELP WOULD BE GREAT! THANKS! =)

    Every time I extend GameLoop, it gives me the warning
    serializable class X does not declare a static final serialVersionUID field of type long
    This is just a warning. You do not need to fix this because the class you are writing will never be serialized by the gaming engine. If you really want the warning to go away, add the code to your class:
    static final long serialVersionUID=0;

  • The serializable class SpacePainter does not declare a static final serial

    The serializable class SpacePainter does not declare a static final serialVersionUID field of type longWhat does this mean??? It appears as a warning in Eclipse but I have no idea what it is. It happens when I create a class the extends JFrame or JCompnent or JApplet. I finnally got it to stop with this:
    static final long serialVersionUID = 1;

    Because your eclipse is configured that way. You can probably filter the warning. You don't have to implement the serialVersionUID, but you should if you really serialize the exceptions.

  • Serializable class doesn�t declare static final serialVersion of type long

    The serializable class SomeClassName does not declare a static final serialVersionUID field of type long
    I have a lot of these warnings in my current application.
    What does it really mean?
    In what situations do I actually want/need to use this?
    If I need it somehwere, do I just declare this field?

    Putting a version number on a serializable class is a precaution against the class definition changing in a way that confuses ObjectStreams when reading old serialisations.
    You can just declare the varialble, initially make it 1 and crank it up in your source when you change the fields of the class.

  • How to fix 'class' or 'interface' expected for jsp

    below is the stack trace
    org.apache.jasper.JasperException: Unable to compile class for JSP
    Generated servlet error:
    /home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:7: 'class' or 'interface' expected
    import java.util.*;
    ^
    Generated servlet error:
    /home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:8: 'class' or 'interface' expected
    import java.io.*;
    ^
    2 errors
    thanks a lot in advance.
    my jsp is
    <%@ page session="false" %>
    <%@ page import="tauvex.*;" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>
    <html>
    <head>
    <title>Tauvex Search Results</title>
    <%
    * Pager Tag Library
    * Copyright (C) 2002 James Klicman <[email protected]>
    * The latest release of this tag library can be found at
    * http://jsptags.com/tags/navigation/pager/
    * This library is free software; you can redistribute it and/or
    * modify it under the terms of the GNU Lesser General Public
    * License as published by the Free Software Foundation; either
    * version 2.1 of the License, or (at your option) any later version.
    * This library is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    * Lesser General Public License for more details.
    * You should have received a copy of the GNU Lesser General Public
    * License along with this library; if not, write to the Free Software
    * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
    %>
    <style type="text/css">
    A.nodec { text-decoration: none; }
    </style>
    </head>
    <body bgcolor="#ffffff">
    <%
    String style = getParam(request, "style", "simple");
    String position = getParam(request, "position", "top");
    String index = getParam(request, "index", "center");
    int maxPageItems = getParam(request, "maxPageItems", 3);
    int maxIndexPages = getParam(request, "maxIndexPages", 3);
    %>
    <%
    String query1=(String)request.getAttribute("query1");
    String query=(String)request.getAttribute("query");
    String ShowFile=(String)request.getAttribute("ShowFile");
    String ShowRA=(String)request.getAttribute("ShowRA");
    String ShowDEC=(String)request.getAttribute("ShowDEC");
    String Telescope=(String)request.getAttribute("Telescope");
    String ObservationDates=(String)request.getAttribute("ObservationDates");
    String Filter=(String)request.getAttribute("Filter");
    String RA=(String)request.getAttribute("RA");
    String DEC=(String)request.getAttribute("DEC");
    String DATE=(String)request.getAttribute("DATE");
    String DATE1=(String)request.getAttribute("DATE1");
    String Radious=(String)request.getAttribute("Radious");
    String FILTER[]=(String[])request.getAttribute("FILTER");
    String OrderBy1=(String)request.getAttribute("OrderBy1");
    String OrderBy2=(String)request.getAttribute("OrderBy2");
    String OrderBy3=(String)request.getAttribute("OrderBy3");
    %>
    <%
    out.println("<form action=\"PlainSQLQuery\" method=POST>");
    out.println("<textarea rows = 5 cols = 40 name=query id=\"query\">");
    out.println(query);
    out.println("</textarea>");
    out.println("<input type = submit value = \"Submit\">");
    out.println("<input type = reset value = \"Reset\">");
    out.println("</form>");
    %>
    <center>
    <table border="0" width="90%" cellpadding="4">
    <tr>
    <td colspan="2" align="left" valign="top">
    <table border="0" cellspacing="2" cellpadding="0">
    <tr><td>Max. Page Items </td>
    <td><input type="text" size="4" name="maxPageItems" value="<%= maxPageItems %>" onChange="this.form.submit();"></td></tr>
    <tr><td>Max. Index Pages </td>
    <td><input type="text" size="4" name="maxIndexPages" value="<%= maxIndexPages %>" onChange="this.form.submit();"></td></tr>
    </table>
    </td>
    </tr>
    </table>
    <pg:pager
    index="<%= index %>"
    maxPageItems="<%= maxPageItems %>"
    maxIndexPages="<%= maxIndexPages %>"
    url="TauvexDataServlet"
    export="offset,currentPageNumber=pageNumber"
    scope="request">
    <%-- keep track of preference --%>
    <pg:param name="style"/>
    <pg:param name="position"/>
    <pg:param name="index"/>
    <pg:param name="maxPageItems"/>
    <pg:param name="maxIndexPages"/>
    <pg:param name="RA"/>
    <pg:param name="DEC"/>
    <pg:param name="DATE"/>
    <pg:param name="DATE1"/>
    <pg:param name="Radious"/>
    <pg:param name="FILTER"/>
    <pg:param name="ShowRA"/>
    <pg:param name="ShowDEC"/>
    <pg:param name="Telescope"/>
    <pg:param name="ObservationDates"/>
    <pg:param name="Filter"/>
    <pg:param name="OrderBy1"/>
    <pg:param name="OrderBy2"/>
    <pg:param name="OrderBy3"/>
    <%-- save pager offset during form changes --%>
    <input type="hidden" name="pager.offset" value="<%= offset %>">
    <%-- warn if offset is not a multiple of maxPageItems --%>
    <% if (offset.intValue() % maxPageItems != 0 &&
    ("alltheweb".equals(style) || "lycos".equals(style)) )
    %>
    <p>Warning: The current page offset is not a multiple of Max. Page Items.
    <br>Please
    <pg:first><a href="<%= pageUrl %>">return to the first page</a></pg:first>
    if any displayed range numbers appear incorrect.</p>
    <% } %>
    <%-- the pg:pager items attribute must be set to the total number of
    items for index before items to work properly --%>
    <% if ("top".equals(position) || "both".equals(position)) { %>
    <br>
    <pg:index>
    <% if ("texticon".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
    <% } else if ("jsptags".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
    <% } else if ("google".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
    <% } else if ("altavista".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
    <% } else if ("lycos".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
    <% } else if ("yahoo".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
    <% } else if ("alltheweb".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
    <% } else { %>
    <jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
    <% } %>
    </pg:index>
    <% } %>
    <hr>
    <form action="ZipServlet" method="get" name="download" onsubmit="return Form1_Validator(this)">
    <table id="output">
    <CAPTION><EM>Fits file Search Results</EM></CAPTION><tr>
    <%
    out.println("<th>Check Box</th>");
    out.println("<th>File Name</th>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<th>RA_START</th>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<th>RA_END</th>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<th>DEC_START</th>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<th>DEC_END</th>");
    if(Telescope!=null && "on".equals(Telescope))
    out.println("<th>Telescope</th>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<th>STARTOBS</th>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<th>ENDOBS</th>");
    if(Filter!=null && "on".equals(Filter))
    out.println("<th>FILTER</th>");
    out.println("</tr>");
    %>
    <%--
    <table width="90%" cellspacing="4" cellpadding="4">
    Since the data source is static, it's easy to offset and limit the
    loop for efficiency. If the data set size is not known or cannot
    be easily offset, the pager tag library can count the items and display
    the correct subset for you.
    The following is an example using an enumeration data source of
    unknown size. The pg:pager items and isOffset attributes must
    not be set for this example:
    --%>
    <%
    Enumeration myDataList1 = (Enumeration)request.getAttribute("myDataList1");
    if (myDataList1 == null)
    throw new RuntimeException("myDataList1 is null");
    %>
    <% while (myDataList1.hasMoreElements()) { %>
    <% TauvexData elem = (TauvexData)myDataList1.nextElement(); %>
    <pg:item> <%
    out.println("<tr>");
    %>
    <td><input type= "checkbox" name="cb" value="<%=elem.getDownload()%>"></td>
    <td><a href="<%= elem.getDownload() %>"><%= elem.Fitsfilename %></a></td>
    <%
    // out.println("<td> "+elem.Fitsfilename+" </td>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<td> "+elem.RA_START+" </td>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<td> "+elem.RA_END+"</td>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<td> "+elem.DEC_START+" </td>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<td> "+elem.DEC_END+" </td>");
    if(Telescope!=null && "on".equals(Telescope))
    out.println("<td> "+elem.telescope+" </td>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<td> "+elem.STARTOBS+" </td>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println(" <td> "+elem.ENDOBS+" </td>");
    if(Filter!=null && "on".equals(Filter))
    out.println("<td> "+elem.FILTER+" </td>");
    out.println("</tr>");
    %> </pg:item>
    <% } %>
    </table>
    <input type="button" name="CheckAll" value="Check All Boxes" onclick="modify_boxes(true,3)">
    <input type="button" name="UnCheckAll" value="UnCheck All Boxes" onclick="modify_boxes(false,3)">
    <input type="submit" value="Download">
    </form>
    <hr>
    <pg:pages>
    <a href="<%= pageUrl %>"><%= pageNumber %></a>
    </pg:pages>
    <pg:last>
    <a href="<%= pageUrl %>">[ Last >| (<%= pageNumber %>) ]</a>
    </pg:last>
    <% if ("bottom".equals(position) || "both".equals(position)) { %>
    <pg:index>
    <% if ("texticon".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
    <% } else if ("jsptags".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
    <% } else if ("google".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
    <% } else if ("altavista".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
    <% } else if ("lycos".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
    <% } else if ("yahoo".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
    <% } else if ("alltheweb".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
    <% } else { %>
    <jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
    <% } %>
    </pg:index>
    <% } %>
    </pg:pager>
    </center>
    </body>
    </html>
    <%!
    private static int num =1;
    private static String getName(){
    String str="cb";
    str=str+num;
    num++;
    return str ;
    private static final String getParam(ServletRequest request, String name,
    String defval)
    String param = request.getParameter(name);
    return (param != null ? param : defval);
    private static final int getParam(ServletRequest request, String name,
    int defval)
    String param = request.getParameter(name);
    int value = defval;
    if (param != null) {
    try { value = Integer.parseInt(param); }
    catch (NumberFormatException ignore) { }
    return value;
    private static void radio(PageContext pc, String name, String value,
    boolean isDefault) throws java.io.IOException
    JspWriter out = pc.getOut();
    String param = pc.getRequest().getParameter(name);
    out.write("<input type=\"radio\" name=\"");
    out.write(name);
    out.write("\" value=\"");
    out.write(value);
    out.write("\" onChange=\"this.form.submit();\"");
    if (value.equals(param) || (isDefault && param == null))
    out.write(" checked");
    out.write('>');
    %>

    Well, putting all that Java code into a JSP was a bad idea in the first place, just on general design principles. But you've done it in such a way that the result of compiling the JSP is malformed Java code. Frankly I would just throw it away and put the Java code into a servlet or some other Java class, where it belongs.
    But if you're really working in a place where nobody has learned anything since 2003, and you're forced to support that old junk, then I would point out that the error occurs before the place which generates this line:
    import java.util.*;You only need to look at two of the thousand lines of code you posted.

  • Abstract class Vs interface

    Hi,
    I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
    I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface  ?
    Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
    Thanks
    Prince

    When inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
    Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
    Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
    abstract classes are designed with implemantion gaps for sub-class to fill in.
    interfaces are sintacticlly similar to classes but they lack insance variables & methods.
    abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
    regards
    Preetesh

  • "class or interface expected error"

    hi,
    i have these two classes that am using and when i try and compile them i get a class or interface expected error.
    i have looked at previous posts and checked that i have the right number of closed brackets.
    anyone any ideas?
    import java.io.*;
    import java.net.*;
    public class BookingServer {
    public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
         Socket mysocket = null;
    try {
    serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
    System.err.println("Could not listen on port: 4444.");
    System.exit(1);
    Socket clientSocket = null;
    try {
    clientSocket = serverSocket.accept();
    } catch (IOException e) {
    System.err.println("Accept failed.");
    System.exit(1);
    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String inputLine, outputLine;
    BookingProtocol bp = new BookingProtocol();
    outputLine = bp.processInput(null);
    out.println(outputLine);
    while ((inputLine = in.readLine()) != null) {
    out.println(inputLine);
    outputLine = bp.processInput(inputLine);
    out.println(outputLine);
    if (outputLine.equals("BYE"))
    break;
    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();
    *****************PROTOCOL***********************
    import java.io.*;
    import java.net.*;
    public class BookingProtocol {
    private static final int WAITING = 0;
    private static final int SENTLOGON = 1;
    private static final int SENTSEATREQ = 2;
    private static final int SENTSTATUSREQ = 3;
    private static final String LOGONPROMPT = "LOGON";
    private static final String SEATPROMPT = "SEAT";
    private static final String STATUSPROMPT = "STATUS";
    private static final String BYEPROMPT = "BYE";
    private int state = WAITING;
    public String processInput(String theInput) {
    String theOutput = null;
    if (state == WAITING) {
    theOutput = LOGONPROMPT;
    state = SENTLOGON;
    } else if (state == SENTLOGON) {
    theOutput = SEATPROMPT;
    state = SENTSEATREQ;
    } else if (state == SENTSEATREQ) {
    theOutput = STATUSPROMPT;
    state = SENTSTATUSREQ;
    } else if (state == SENTSTATUSREQ) {
    theOutput = BYEPROMPT;
    state = WAITING;
    return theOutput;
    in.close();
    clientSocket.close();
    serverSocket.close();

    you have too many }-brackets, the finalin.close();
    clientSocket.close();
    serverSocket.close();
    }is not inside any class

  • 'class' or 'interface' expected, advice please!

    Hi! I have problems running a program. it is supposed to 1) open a file 2) find word 1-3, 2-4, 3-5 a.s.o. 3) write the wordstrings it found in a system.out.println. In the former version, I only had private static void and got this: Exception in thread "main" java.lang.NoSuchMethodError: main when i ran it. I was adviced to add public static void but now it says: 'class' or 'interface' expected, does someone know why this is?
    this is what the code looks like:
    import java.io.*;
    import java.io.*;
    import java.util.*; //tillagd f�r att removeFirst4 skall funka
    import javax.swing.*; //tillagd f�r att removeFirst4 skall fungera
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    import java.lang.*;
    import javax.swing.*;
    public static void main(String[] foo) {
    public class AttLaesaEnFil2 {
         private static void main(String name, BufferedReader in) throws
         IOException {
         String a;
         WordExtractor b;
    String c = " ";
    String d;
    WordExtractor e;
    String f;
    String g;
    WordExtractor h;
    String i;
    String j;
    String k;
    String l;
    String line;
    do {
                   line = in.readLine();
                   if (line != null)
    b = new WordExtractor(line);
         c = b.getFirst();
         d = b.getRest();
         e = new WordExtractor(d);
         f = e.getFirst();
         g = e.getRest();
         h = new WordExtractor(g);
         i = h.getFirst();
         j = h.getRest();
         k = c + f + i;
         l = c + " " + f + " " + i;
    System.out.println("The first three words are: " + l);
         a = b.getRest();
    while (line != null);
              System.out.println("Klart!");
              private static void main(String fileName) {
              BufferedReader in = null;
              try {
                   FileReader fileReader = new FileReader(fileName);
                   in = new BufferedReader(fileReader);
                   main(fileName, in);
              } catch (IOException ioe) {
                   ioe.printStackTrace();
              } finally {
                   if (in != null) {
                        try {
                             in.close();
                        } catch (IOException ioe) {
                             ioe.printStackTrace();
         private static void main(String streamName, InputStream input) {
              try {
                   InputStreamReader inputStreamReader = new InputStreamReader(input);
                   BufferedReader in = new BufferedReader(inputStreamReader);
                   main(streamName, in);
                   in.close();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
    i tried to add public static void before each private but with the same result.
    Thank you in advance

    This wins the award for Funniest Code Snippet of the
    Day. Four main methods, with a class nested inside
    the first main method.Hey! stop mocking me, i'm doing my best!
    this is the code i'm learning this from, it also includes four methods (not main though, maybe that's the pr.) but works fine but mine still won't:
    import java.io.*;
    * Command line program to count lines, words and characters
    * in files or from standard input, similar to the wc
    * utility.
    * Run like that: java WordCount FILE1 FILE2 ... or
    * like that: java WordCount < FILENAME.
    * @author Marco Schmidt
    public class WordCount {
         * Count lines, words and characters in given input stream
         * and print stream name and those numbers to standard output.
         * @param name name of input source
         * @param input stream to be processed
         * @throws IOException if there were I/O errors
         private static void count(String name, BufferedReader in) throws
         IOException {
              long numLines = 0;
              long numWords = 0;
              long numChars = 0;
              String line;
              do {
                   line = in.readLine();
                   if (line != null)
                        numLines++;
                        numChars += line.length();
                        numWords += countWords(line);
              while (line != null);
              System.out.println(name + "\t" + numLines + "\t" +
                   numWords + "\t" + numChars);
         * Open file, count its words, lines and characters
         * and print them to standard output.
         * @param fileName name of file to be processed
         private static void count(String fileName) {
              BufferedReader in = null;
              try {
                   FileReader fileReader = new FileReader(fileName);
                   in = new BufferedReader(fileReader);
                   count(fileName, in);
              } catch (IOException ioe) {
                   ioe.printStackTrace();
              } finally {
                   if (in != null) {
                        try {
                             in.close();
                        } catch (IOException ioe) {
                             ioe.printStackTrace();
         * Count words, lines and characters of given input stream
         * and print them to standard output.
         * @param streamName name of input stream (to print it to stdout)
         * @param input InputStream to read from
         private static void count(String streamName, InputStream input) {
              try {
                   InputStreamReader inputStreamReader = new InputStreamReader(input);
                   BufferedReader in = new BufferedReader(inputStreamReader);
                   count(streamName, in);
                   in.close();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
         * Determine the number of words in the argument line.
         * @param line String to be examined, must be non-null
         * @return number of words, 0 or higher
         private static long countWords(String line) {
              long numWords = 0;
              int index = 0;
              boolean prevWhitespace = true;
              while (index < line.length()) {
                   char c = line.charAt(index++);
                   boolean currWhitespace = Character.isWhitespace(c);
                   if (prevWhitespace && !currWhitespace) {
                        numWords++;
                   prevWhitespace = currWhitespace;
              return numWords;
         public static void main(String[] args) {
              if (args.length == 0) {
                   count("stdin", System.in);
              } else {
                   for (int i = 0; i < args.length; i++) {
                        count(args);

  • Use of Class Vs Interface for defining application constants

    I want to use some constants through out the application. For that I found two ways to do that as given below
    1. We can define constants in a class as
    public class ConstantClass {
    public static final String applConstant = "Some Constant";
    and use it ConstantClass.applConstant whereever needed
    Or
    2. We can define an interface as
    public interface IConstantInterface {
    String applConstant = "Some Constant";
    and use it IConstantInterface.applConstant
    Can you pls explain which is the best method to be used in the application and why?
    Thanks in advance.

    Hmmm - that would imply that if I have a reference a
    static final variable in a 3rd party class, then
    compile my class to a .class file, then the 3rd party
    changes their class file, that my .class file would
    not contain the correct values.Yep, that is what would happen
    I doubt this. I haven't read the compiler specs, but
    my assumption would be that compile time optimizations
    such as this only apply to constants within a single
    .class file.You don't need the compiler specs, you just need a compiler.
    Compile the two classes below, and run Main. Your output should look like:
    3
    Hello
    5
    Hooky
    Then delete the Constants.class file and run Main again and see what happens.
    == Constants.java ==
    public class Constants {
    public static final int INT_CONSTANT = 3;
    public static final String STRING_CONSTANT = "Hello";
    public static int i = 5;
    public static String s = "Hooky";
    == End Constants.java ==
    == Main.java ==
    public class Main {
    public static void main(String[] args) {
    System.out.println(Constants.INT_CONSTANT);
    System.out.println(Constants.STRING_CONSTANT);
    System.out.println(Constants.i);
    System.out.println(Constants.s);
    == End Main.java ==
    In case you are wondering:
    java version "1.4.1_02"
    OS: Solaris 8
    Arch: Sparc
    I get the same thing on windows with 1.4 and 1.3
    and on FreeBSD with diablo jdk 1.3

  • Comparison between constants in class and interface

    Hi,
    I have recently read an article which says it is a better use of your memory if you declare constants in an Interface rather than in a Class. Can any one explain this is more detail? Have a great day.
    Thank you,
    npaila

    @ricardo_moral
    Hm ...
    we are talking of constants in this topic - constants are always final, otherwise it would not be garanteed, that they cannot change. Also we are not talking of holding a copy of this constant field in a class, we are talking of directly referring to this static final field, regardless if it is declared in an interface or in a class.
    I prefer using an interface - my reason is that I can use it the same way, I can use a class, which declares this constant - via qualifier - AND I can implement it, if I want to - so, I follow the swing route and declare constants, which are shared by many classes, in an interface - but I implement it only there, where these constants are heavily used.
    greetings Marsian

  • Constant values (public static final String) are not shown??

    This has already been posted and no body answered. Any help is appreciated.
    In web service is it possible to expose the Constants used in the application. Let say for my web service I need to pass value for Operation, possible values for this are (add, delete, update). Is it possible expose these constant values(add, delete, update) visible to client application accesssing the web service.
    Server Side:
    public static final String ADD = "ADDOPP";
    public static final String DELETE = "DELETEOPP";
    public static final String UPDATE = "UPDATEOPP";
    client Side: mywebserviceport.setOperation( mywebservicePort.ADD );
    thanks
    vijay

    Sure, you can use JAX-WS and enums.
    For example on the server:
    @WebService
    public class echo {
    public enum Status {RED, YELLOW, GREEN}
    @WebMethod
    public Status echoStatus(Status status) {
    return status;
    on the client you get.
    @WebService(name = "Echo", wsdlLocation ="..." )
    public interface Echo {
    @WebMethod
    public Status echoStatus(
    @WebParam(name = "arg0", targetNamespace = "")
    Status arg0);
    @XmlEnum
    public enum Status {
    GREEN,
    RED,
    YELLOW;
    public String value() {
    return name();
    public static Status fromValue(String v) {
    return valueOf(v);
    }

  • Question about Classes, Abstract  Classes and Interfaces.

    I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
    I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
    First I create an abstract class like this:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public static void setServerName(String serverName) {
              ServerName = serverName;
         public static String getServerName() {
              return ServerName;
    }and then I created an interface
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }And finally the class itself with some test lines in it so I could see what was going on:
    public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
         public CreateDatabase(){     
              setServerName("Server Name 1");
              System.out.println ("Before update ");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("After update ");
              setServerName("Server Name 2");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("==========================");
    }The output I get from the above is:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================I also tried this in another class which calls the above class to see if I get the same effect
    public class CheckDatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
              CreateDatabase.setServerName("Server 3");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 4");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 5");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
    }The output of which is this:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
    Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
    Or is there a better way of doing this.
    What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
    Any help appreciated
    Regards
    John

    Not gonna read all of it, but this jumps out:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
    Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
    Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.

  • Will declaring primitives as static final (constants) conserve memory?

    I wrote a code
    int a = flag?1:0;on which my supervisor commented that 1 and 0 should be replaced by SomeInterface.ONE (=1) and SomeInterface.ZERO (=0) respectively. The reason he gave was that since constants are static so it will conserve memory.
    Is this really true?

    First of all, this Interface for Constants anti-pattern is widely derided.
    Secondly, one of the reasons it was used in the first place was readability, not performance, and in that case constants that pertain to the meaning of that 1 and 0, and not the values, might have been understandable (e.g. SomeInterface.TRUE = 1 and SomeInterface.FALSE = 0), but definately not ONE and ZERO.
    Thirdly, memory use is the same as public static final variables (as interface constants are), have their value compiled directly into the class using them, at the point where it used, so whether a constant is used, or a literal value, the space that that class definition uses is the same. In addition, there is then an interface definition that also has those values so the memory use is more, in end effect. And, regardless, that memory space is not on the heap, which is the memory space you will be most interested in, so it has no noticeable effect on memory space either way.

  • Static Final Long Results in RMIC Failure

    I have a variable in my remote interface:
    public static final Long ID = new Long("0");Which causes an RMIC failure with the following error:
    ID is not a valid primitive or String constant.So my question is, why must a static final variable be a primitive or a String?
    Thanks,
    toby

    I couldn't reproduce your case maybe you could post more info. Here is what I did: I created a remote interface with a Long declaration like your's. I created an implementation of that remote interface and compiled and rmic'ed them with noe errors, here are the source files:
    package junk;
    import java.rmi.*;
    public interface RIntf extends Remote {
        public static final Long ID = new Long("O");
        public String hello() throws RemoteException;
    package junk;
    import java.rmi.*;
    import java.rmi.server.*;
    public class RImpl extends UnicastRemoteObject implements RIntf {
        public RImpl() throws RemoteException {
        public String hello() throws RemoteException {
         System.err.println("junk");
         return "junk";
    }After javac'ing these two source files I ran rmic on junk.RImpl to produce the stubs and skeletons without any issue. Let me know if this is similar to your issue. By the way, there is an RMI specific forum located here: http://forum.java.sun.com/forum.jsp?forum=58

  • Error like 'class' or 'interface' expected

    hi,
    I write one simple program :-
    enum Apple
            a,b,c;
    public class AppleDemo
            public static void main(String args[])
                    Apple app;
                    app=Apple.a;
                    System.out.println("The Apple is:"+app);
                    app=Apple.b;
                    if(app==Apple.b)
                    System.out.println("Apple is:"+app);
    }My qry is- I am trying to compile this program.I am using j2sdk1.5.0 for compilation...but i got error that is
    *'class' or 'interface' expected*
    Thanks in advance.

    This forum is for Sun Instant Messaging related questions. For simple java questions I suggest you refer to the following forum:
    http://forums.sun.com/forum.jspa?forumID=54
    Regards,
    Shane.

Maybe you are looking for

  • Can't make a workable custom codec with ProRes 422 (HQ)

    I've only just now found that there is a Support Community for Compressor.  Wish I'd known sooner. I see my version of Compressor is 3.5.3. I've been on a little saga. I started out with the challenge of converting some MP4 files from a Blackberry Pl

  • Opening pdf in adobe acrobat vs. photoshop

    Somehow my computer settings have been changed to open pdf fils in photoshop vs adobe acrobat...does anyone know how to swich it back so pdf files open in adobe acrobat?

  • Internet Sharing keeps needing to be reset

    Hello-I am using internet sharing to allow my iPhone, iPad, and 2nd iMac access to my cable internet connection. This certainly works fine, except lately, I will try to connect to the internet on my phone, and the web pages do not load. I can fix it

  • Uploading site with database

    I am ready to upload my website to the internet but am unsure how I would upload my database. Thank you.

  • Actions not working in LEAD

    hi all i have a problem that actions assigned in LEAD transaction isnt working.i have checked all the customising that in action profile workflow is attached and action is assigned to the transaction but when i open the transaction in menu "maintain