Use of const keyword in java ?

Hi All,,
I want to know the use of const keyword with proper example.
Many many thx in advance
Cheers
Souvik

I want to know the use of const keyword with proper example.
There is no proper example, because const is not used in Java. If you want to create a constant, use the final keyword.

Similar Messages

  • Object or Statement Block locking using synchronized keyword in java

    Hi ,
    Can anyone tell me how java is implementing the Object locking and the code block locking mechanism using the 'synchronized' keyword internally??
    Thanks in advance
    Raj

    The JVM implements a concept known as a monitor using a combination of direct implementation and support by the operating system. For more detail, refer to the Java JVM and language specifications.
    Chuck

  • Can i make Thread safe without using synchronised keyword in java

    Hi all,
    please tell me code and concept that we can make Thread safe without using synchronised keyword in java programming.
    regards
    Mohan kumar

    There's a series of new features in Java 5.0 (JDK 1.5.0) to address things like concurrency.
    See: http://java.sun.com/j2se/1.5.0/docs/guide/concurrency/overview.html
    -Alexis

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • Constant problems with Java since upgrade to OS X 10.7

    I recently purchased a Macbook Air with OS X 10.7 installed, now updated to version 10.7.5.
    I'm having constant issues with Java and repeatedly being told to update to the latest version, even when I have the latest version installed (now Java 7 update 9). I've visited dozens of forums and seen posts about the same issue, but none of the solutions work for me.
    I've seen variations of the following advice in several places:
    Apple disables the Java plug-in and Webstart applications when the Java update is done using Software Update. Also, if the Java plug-in detects that no applets have been run for an extended period of time it will again disable the Java plug-in.
    To enable the Java plug-in
    Go to Finder > Applications > Utilities > Java Preferences.
    In the Java Preferences window check the box for Enable Applet plug-in and Webstart applications.
    But I can't find anything called "Java Preferences" in my Utilities folder. I found a Java control panel in my System preferences, and it tells me everything is OK and running.
    I also see comments about emptying the cache (Java cache?), but can't find where it's kept. I also can't find where the Java plugins are stored. So what to do?
    Thanks for any assistance.
    Martha

    I went to the link on the Support website, downloaded the Java from there (Java for OS X 2012-006) and installed it. Then I went to the Java control panel in System prefs and the information is exactly the same as it was before I installed Java version 6. It still says I have the recommended version of Java (Java 7 update 9), which is what I installed a few hours ago.
    Then I went back to the website where I've been having problems today and went through the process of requesting a document from the Spanish tax authorities, which I've never had trouble with in the past (before Lion). I got the same results as earlier and the same page sending me to www.java.com to "download the latest version". So I'm back to square one.
    There's a comment on the page your link sent me to that mentions the "Missing plug-in" region on some web pages, but I've never seen this anywhere. All I ever get is a message telling me to update my Java.
    Is there another version of Java that would work better? If so, where can I get it?
    Thanks.

  • Using the 'this' keyword

    What is the use of the this keyword:
    import java.util.*;
    public abstract class LegalEntity implements HasAddress{
    private String address;
    private String area;
    private String registrationDate;
    private ArrayList accounts;
    public LegalEntity()
         accounts = new ArrayList();
    public void addAddress(String address){this.address = address;}
    public String getAddress(){return address;}
    public void addAccount(Account account)
         accounts.add(account);
    public ArrayList returnAccounts()
         return accounts;
    }

    This can be used when there are lots of static functions and you want to be sure you are invoking the current objects methods/members.

  • Suns standard classes use of constants - bad coding convention

    Wasn't sure where to post this, it didn't quite fit into Java Runtime Environment or Java Virtual Machine forums.
    I was browsing through The Java Standard classes and was amazed by their use of constants. Throughout the codes there is inserted direct constants in the code without any use of global constant declarations.
    Eg: java.lang.StringCoding:
    All over the code is inserted "ISO-8859-1" (used as default encoding) directly instead of using a declared constant DEFAULTENCODING. What if Sun want to change default encoding?
    Seems strange to me that such coding conventions are used by Sun. Any reason for this or just sloppy programing?
    Gil

    Looks like sloppy programming to me. I see no possible
    reason for it. You're not the first person to
    criticise Sun's source code. Maybe they outsourced it
    to http://www.newtechusa.com/PPI/main.asp (I can never
    remember how to format links, no matter how often
    people tell me!)
    RObinThere's logic in getting primates to program.
    Based on the popular theory that an infinite number of monkeys could
    randomly produce the works of Shakespeare, they could also produce the perfect software implementation of any given problem. The downside being that the printed documentation will be smeared liberally with faeces.
    regards,
    Owen

  • Chainging the color of a Keyword on Java

    How do I highlight a keyword on Java ? I'm making a Java IDE which is for free
    that you may see at : http://www.freewebs.com/cube-j I'm currently using a
    3rd party jar file to make the keywords change its colors. The problem is
    every 10 min a reminder will pop-out to remind me to register it for a fee.
    I dont want to do that can anyone here show me how to do that or give some
    sample on how to change the color of every keywords on JTextPane, Or does anyone
    knows of a jar file which is free, thanks.
    Hope to here from all of you . . .
    Friend : BringMe2Life

    I forget who I ripped the off (its someone here - camrickr I think), but this works very well import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    class SyntaxDocument extends DefaultStyledDocument{
                         private DefaultStyledDocument doc;
                         private Element rootElement;
         private boolean multiLineComment;
         private MutableAttributeSet normal;
         private MutableAttributeSet keyword;
         private MutableAttributeSet comment;
         private MutableAttributeSet quote;
         private Hashtable keywords;
            public SyntaxDocument(){
         doc = this;
         rootElement = doc.getDefaultRootElement();
         putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
         normal = new SimpleAttributeSet();
         StyleConstants.setForeground(normal, Color.black);
         comment = new SimpleAttributeSet();
                         Color green = new Color(0, 120, 0);
         StyleConstants.setForeground(comment, green);
         StyleConstants.setItalic(comment, true);
         keyword = new SimpleAttributeSet();
                         Color blue = new Color(0, 0, 140);
         StyleConstants.setForeground(keyword, blue);
         StyleConstants.setBold(keyword, true);
         quote = new SimpleAttributeSet();
                         Color red = new Color(140,0,0);
         StyleConstants.setForeground(quote, red);
         Object dummyObject = new Object();
         keywords = new Hashtable();
         keywords.put( "abstract", dummyObject );
         keywords.put( "boolean", dummyObject );
         keywords.put( "break", dummyObject );
         keywords.put( "byte", dummyObject );
         keywords.put( "byvalue", dummyObject );
         keywords.put( "case", dummyObject );
         keywords.put( "cast", dummyObject );
         keywords.put( "catch", dummyObject );
         keywords.put( "char", dummyObject );
         keywords.put( "class", dummyObject );
         keywords.put( "continue", dummyObject );
         keywords.put( "default", dummyObject );
         keywords.put( "do", dummyObject );
         keywords.put( "double", dummyObject );
         keywords.put( "else", dummyObject );
         keywords.put( "extends", dummyObject );
         keywords.put( "false", dummyObject );
         keywords.put( "final", dummyObject );
         keywords.put( "finally", dummyObject );
         keywords.put( "float", dummyObject );
         keywords.put( "for", dummyObject );
         keywords.put( "if", dummyObject );
         keywords.put( "implements", dummyObject );
         keywords.put( "import", dummyObject );
         keywords.put( "instanceof", dummyObject );
         keywords.put( "int", dummyObject );
         keywords.put( "interface", dummyObject );
         keywords.put( "long", dummyObject );
         keywords.put( "new", dummyObject );
         keywords.put( "null", dummyObject );
         keywords.put( "package", dummyObject );
         keywords.put( "private", dummyObject );
         keywords.put( "protected", dummyObject );
         keywords.put( "public", dummyObject );
         keywords.put( "return", dummyObject );
         keywords.put( "short", dummyObject );
         keywords.put( "static", dummyObject );
         keywords.put( "super", dummyObject );
         keywords.put( "switch", dummyObject );
         keywords.put( "synchronized", dummyObject );
         keywords.put( "this", dummyObject );
         keywords.put( "throw", dummyObject );
         keywords.put( "throws", dummyObject );
         keywords.put( "transient", dummyObject );
         keywords.put( "true", dummyObject );
         keywords.put( "try", dummyObject );
         keywords.put( "void", dummyObject );
         keywords.put( "volatile", dummyObject );
         keywords.put( "while", dummyObject );
    * Override to apply syntax highlighting after the document has been updated
       public void insertString(int offset, String str, AttributeSet a) throws BadLocationException{
         if (str.equals("{"))
         str = addMatchingBrace(offset);
         super.insertString(offset, str, a);
         processChangedLines(offset, str.length());
    * Override to apply syntax highlighting after the document has been updated
       public void remove(int offset, int length) throws BadLocationException{
         super.remove(offset, length);
         processChangedLines(offset, 0);
    * Determine how many lines have been changed,
    * then apply highlighting to each line
       private void processChangedLines(int offset, int length) throws BadLocationException {
         String content = doc.getText(0, doc.getLength());
         // The lines affected by the latest document update
         int startLine = rootElement.getElementIndex( offset );
         int endLine = rootElement.getElementIndex( offset + length );
         // Make sure all comment lines prior to the start line are commented
         // and determine if the start line is still in a multi line comment
         setMultiLineComment( commentLinesBefore( content, startLine ) );
         // Do the actual highlighting
               for (int i = startLine; i <= endLine; i++) applyHighlighting(content, i);
                         // Resolve highlighting to the next end multi line delimiter
               if (isMultiLineComment())commentLinesAfter(content, endLine);
                               else highlightLinesAfter(content, endLine);
    * Highlight lines when a multi line comment is still 'open'
    * (ie. matching end delimiter has not yet been encountered)
       private boolean commentLinesBefore(String content, int line){
         int offset = rootElement.getElement( line ).getStartOffset();
         // Start of comment not found, nothing to do
         int startDelimiter = lastIndexOf( content, getStartDelimiter(), offset-2);
         if (startDelimiter < 0)return false;
         // Matching start/end of comment found, nothing to do
         int endDelimiter = indexOf( content, getEndDelimiter(), startDelimiter );
         if (endDelimiter < offset & endDelimiter != -1)return false;
         // End of comment not found, highlight the lines
         doc.setCharacterAttributes(startDelimiter, offset - startDelimiter + 1, comment, false);
         return true;
    * Highlight comment lines to matching end delimiter
       private void commentLinesAfter(String content, int line){
         int offset = rootElement.getElement( line ).getEndOffset();
         // End of comment not found, nothing to do
         int endDelimiter = indexOf( content, getEndDelimiter(), offset );
         if (endDelimiter < 0) return;
         // Matching start/end of comment found, comment the lines
         int startDelimiter = lastIndexOf( content, getStartDelimiter(), endDelimiter );
            if (startDelimiter < 0 || startDelimiter <= offset){
                doc.setCharacterAttributes(offset, endDelimiter - offset + 1, comment, false);
    * Highlight lines to start or end delimiter
       private void highlightLinesAfter(String content, int line) throws BadLocationException{
         int offset = rootElement.getElement( line ).getEndOffset();
         // Start/End delimiter not found, nothing to do
         int startDelimiter = indexOf( content, getStartDelimiter(), offset );
         int endDelimiter = indexOf( content, getEndDelimiter(), offset );
         if (startDelimiter < 0)     startDelimiter = content.length();
         if (endDelimiter < 0)endDelimiter = content.length();
         int delimiter = Math.min(startDelimiter, endDelimiter);
         if (delimiter < offset)return;
         // Start/End delimiter found, reapply highlighting
         int endLine = rootElement.getElementIndex( delimiter );
            for (int i = line + 1; i < endLine; i++){
               Element branch = rootElement.getElement( i );
               Element leaf = doc.getCharacterElement( branch.getStartOffset() );
               AttributeSet as = leaf.getAttributes();
               if ( as.isEqual(comment) )applyHighlighting(content, i);
    * Parse the line to determine the appropriate highlighting
       private void applyHighlighting(String content, int line) throws BadLocationException{
         int startOffset = rootElement.getElement( line ).getStartOffset();
         int endOffset = rootElement.getElement( line ).getEndOffset() - 1;
         int lineLength = endOffset - startOffset;
         int contentLength = content.length();
            if (endOffset >= contentLength)endOffset = contentLength - 1;
         // check for multi line comments
         // (always set the comment attribute for the entire line)
            if (endingMultiLineComment(content, startOffset, endOffset)
                                 ||isMultiLineComment()||startingMultiLineComment(content, startOffset, endOffset)){
                doc.setCharacterAttributes(startOffset, endOffset - startOffset + 1, comment, false);
                return;
         // set normal attributes for the line
         doc.setCharacterAttributes(startOffset, lineLength, normal, true);
         // check for single line comment
         int index = content.indexOf(getSingleLineDelimiter(), startOffset);
             if ( (index > -1) && (index < endOffset) ){
                 doc.setCharacterAttributes(index, endOffset - index + 1, comment, false);
                 endOffset = index - 1;
         // check for tokens
         checkForTokens(content, startOffset, endOffset);
    * Does this line contain the start delimiter
       private boolean startingMultiLineComment(String content, int startOffset, int endOffset) throws BadLocationException{
         int index = indexOf( content, getStartDelimiter(), startOffset );
         if ( (index < 0) || (index > endOffset) )return false;
         else{
             setMultiLineComment( true );
             return true;
    * Does this line contain the end delimiter
       private boolean endingMultiLineComment(String content, int startOffset, int endOffset) throws BadLocationException{
         int index = indexOf( content, getEndDelimiter(), startOffset );
         if ( (index < 0) || (index > endOffset) )return false;
         else{
             setMultiLineComment( false );
             return true;
    * We have found a start delimiter
    * and are still searching for the end delimiter
       private boolean isMultiLineComment(){
           return multiLineComment;
       private void setMultiLineComment(boolean value){
           multiLineComment = value;
    * Parse the line for tokens to highlight
       private void checkForTokens(String content, int startOffset, int endOffset){
           while (startOffset <= endOffset){
           // skip the delimiters to find the start of a new token
          while (isDelimiter(content.substring(startOffset, startOffset+1))){
              if (startOffset < endOffset)startOffset++;
              else return;
          // Extract and process the entire token
          if (isQuoteDelimiter( content.substring(startOffset, startOffset + 1)))
          startOffset = getQuoteToken(content, startOffset, endOffset);
          else startOffset = getOtherToken(content, startOffset, endOffset);
       private int getQuoteToken(String content, int startOffset, int endOffset){
         String quoteDelimiter = content.substring(startOffset, startOffset + 1);
         String escapeString = getEscapeString(quoteDelimiter);
         int index;
         int endOfQuote = startOffset;
         // skip over the escape quotes in this quote
         index = content.indexOf(escapeString, endOfQuote + 1);
         while ( (index > -1) && (index < endOffset) ){
            endOfQuote = index + 1;
            index = content.indexOf(escapeString, endOfQuote);
         // now find the matching delimiter
         index = content.indexOf(quoteDelimiter, endOfQuote + 1);
         if ( (index < 0) || (index > endOffset) )endOfQuote = endOffset;
         else endOfQuote = index;
         doc.setCharacterAttributes(startOffset, endOfQuote-startOffset+1, quote, false);
         return endOfQuote + 1;
        private int getOtherToken(String content, int startOffset, int endOffset){
         int endOfToken = startOffset + 1;
         while (endOfToken <= endOffset ){
         if (isDelimiter(content.substring(endOfToken, endOfToken+1)))break;
         endOfToken++;
        String token = content.substring(startOffset, endOfToken);
         if ( isKeyword( token ) )
         doc.setCharacterAttributes(startOffset, endOfToken-startOffset, keyword, false);
         return endOfToken + 1;
    * Assume the needle will the found at the start/end of the line
        private int indexOf(String content, String needle, int offset){
         int index;
         while ( (index = content.indexOf(needle, offset)) != -1 ){
                String text = getLine( content, index ).trim();
             if (text.startsWith(needle) || text.endsWith(needle))break;
             else offset = index + 1;
         return index;
    * Assume the needle will the found at the start/end of the line
        private int lastIndexOf(String content, String needle, int offset){
         int index;
         while ( (index = content.lastIndexOf(needle, offset)) != -1 ){
             String text = getLine( content, index ).trim();
             if (text.startsWith(needle) || text.endsWith(needle))break;
            else offset = index - 1;
         return index;
        private String getLine(String content, int offset){
         int line = rootElement.getElementIndex( offset );
         Element lineElement = rootElement.getElement( line );
         int start = lineElement.getStartOffset();
         int end = lineElement.getEndOffset();
         return content.substring(start, end - 1);
    * Override for other languages
        protected boolean isDelimiter(String character){
         String operands = ";:{}()[]+-/%<=>!&|^~*";
         if (Character.isWhitespace( character.charAt(0) ) || operands.indexOf(character)!= -1 )
                              return true;
             else return false;
    * Override for other languages
        protected boolean isQuoteDelimiter(String character){
                         String quoteDelimiters = "\"'";
         if (quoteDelimiters.indexOf(character) < 0) return false;
         else return true;
    * Override for other languages
        protected boolean isKeyword(String token){
         Object o = keywords.get( token );
         return o == null ? false : true;
    * Override for other languages
        protected String getStartDelimiter(){
         return "/*";
    * Override for other languages
        protected String getEndDelimiter(){
         return "*/";
    * Override for other languages
        protected String getSingleLineDelimiter(){
         return "//";
    * Override for other languages
        protected String getEscapeString(String quoteDelimiter){
         return "\\" + quoteDelimiter;
        protected String addMatchingBrace(int offset) throws BadLocationException{
         StringBuffer whiteSpace = new StringBuffer();
         int line = rootElement.getElementIndex( offset );
         int i = rootElement.getElement(line).getStartOffset();
         while (true){
             String temp = doc.getText(i, 1);
             if (temp.equals(" ") || temp.equals("\t")){
                 whiteSpace.append(temp);
                 i++;
             else break;
         return "{\n" + whiteSpace.toString() + whiteSpace.toString()+"\n" + whiteSpace.toString() + "}";
    }

  • How can I use LogOutComponent programatically in a Java iView?

    Hi,
    Can someone point me to the jar file(s) that I need to reference in my portal application project (Java PDK) to use LogOutComponent? Which ones do I need and where can I get them
    I got the class file 'com.sap.portal.navigation.masthead_core.jar' from the Portal server but am not sure if this file is the only one that I need to use to incorporate LogOutComponent in my code.
    Also, can somebody tell me that how can I call this component from my AbstractPortal Component to call logout programatically? I am not using JSPs and would ideally not like to redirect the response to the URL of this component but rather use the object in my Java code. Sample code to help with this would be appreciated.
    Thank you,
    - Vik.

    Hi there,
    To log a user out of the Portal I decided to go the route of: UMFactory.getAuthenticator().logout(req, res)
    Code is below.
    Thanks for your replies,
    - Vik.
    <code>
    IAuthentication Authen = UMFactory.getAuthenticator();
    HttpServletRequest req = request.getServletRequest();
    HttpServletResponse res = request.getServletResponse(true);
    //logoff user from Portal
    Authen.logout(req, res);
    </code>

  • How to use the TCP/IP in Java?Thanks!

    How to use the TCP/IP in Java?Thanks!

    Look at the java.net package, more specifically to classes ServerSocket (The server TPC conection) and Socket (the client TCP conection)
    Abraham

  • How can I use XStream to persist complicated Java Object  to XML & backward

    Dear Sir:
    I met a problem as demo in my code below when i use XTream to persist my Java Object;
    How can I use XStream to persist complicated Java Object to XML & backward??
    See
    [1] main code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    public class PhoneList {
         ArrayList<PhoneNumber> phones;
         ArrayList<Person> person;
         private PhoneList myphonelist ;
         private LocationTest location;
         private PhoneList(String name) {
         phones = new ArrayList<PhoneNumber>();
         person = new ArrayList<Person>();
         public ArrayList<PhoneNumber> getphones() {
              return phones;
         public ArrayList<Person> getperson() {
              return person;
         public void addPhoneNumber(PhoneNumber b1) {
              this.phones.add(b1);
         public void removePhoneNumber(PhoneNumber b1) {
              this.phones.remove(b1);
         public void addPerson(Person p1) {
              this.person.add(p1);
         public void removePerson(Person p1) {
              this.person.remove(p1);
         public void BuildList(){
              location = new LocationTest();
              XStream xstream = new XStream();
              myphonelist = new PhoneList("PhoneList");
              Person joe = new Person("Joe, Wallace");
              joe.setPhone(new PhoneNumber(123, "1234-456"));
              joe.setFax(new PhoneNumber(123, "9999-999"));
              Person geo= new Person("George Nixson");
              geo.setPhone(new PhoneNumber(925, "228-9999"));
              geo.getPhone().setLocationTest(location);          
              myphonelist.addPerson(joe);
              myphonelist.addPerson(geo);
         public PhoneList(){
              XStream xstream = new XStream();
              BuildList();
              saveStringToFile("C:\\temp\\test\\PhoneList.xml",convertToXML(myphonelist));
         public void saveStringToFile(String fileName, String saveString) {
              BufferedWriter bw = null;
              try {
                   bw = new BufferedWriter(
                             new FileWriter(fileName));
                   try {
                        bw.write(saveString);
                   finally {
                        bw.close();
              catch (IOException ex) {
                   ex.printStackTrace();
              //return saved;
         public String getStringFromFile(String fileName) {
              BufferedReader br = null;
              StringBuilder sb = new StringBuilder();
              try {
                   br = new BufferedReader(
                             new FileReader(fileName));
                   try {
                        String s;
                        while ((s = br.readLine()) != null) {
                             // add linefeed (\n) back since stripped by readline()
                             sb.append(s + "\n");
                   finally {
                        br.close();
              catch (Exception ex) {
                   ex.printStackTrace();
              return sb.toString();
         public  String convertToXML(PhoneList phonelist) {
              XStream xstream = new  XStream(new DomDriver());
              xstream.setMode(xstream.ID_REFERENCES) ;
              return xstream.toXML(phonelist);
         public static void main(String[] args) {
              new PhoneList();
    }[2].
    import java.io.Serializable;
    import javax.swing.JFrame;
    public class PhoneNumber implements Serializable{
           private      String      phone;
           private      String      fax;
           private      int      code;
           private      String      number;
           private      String      address;
           private      String      school;
           private      LocationTest      location;
           public PhoneNumber(int i, String str) {
                setCode(i);
                setNumber(str);
                address = "4256, Washington DC, USA";
                school = "Washington State University";
         public Object getPerson() {
              return null;
         public void setPhone(String phone) {
              this.phone = phone;
         public String getPhone() {
              return phone;
         public void setFax(String fax) {
              this.fax = fax;
         public String getFax() {
              return fax;
         public void setCode(int code) {
              this.code = code;
         public int getCode() {
              return code;
         public void setNumber(String number) {
              this.number = number;
         public String getNumber() {
              return number;
         public void setLocationTest(LocationTest bd) {
              this.location = bd;
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(location);
            f.getContentPane().add(location.getControls(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
         public LocationTest getLocationTest() {
              return location;
         }[3].
    package test.temp;
    import java.io.Serializable;
    public class Person implements Serializable{
         private String           fullname;
           @SuppressWarnings("unused")
         private PhoneNumber      phone;
           @SuppressWarnings("unused")
         private PhoneNumber      fax;
         public Person(){
         public Person(String fname){
                fullname=fname;           
         public void setPhone(PhoneNumber phoneNumber) {
              phone = phoneNumber;
         public void setFax(PhoneNumber phoneNumber) {
              fax = phoneNumber;
         public PhoneNumber getPhone() {
              return phone ;
         public PhoneNumber getFax() {
              return fax;
        public String getName() {
            return fullname ;
        public void setName(String name) {
            this.fullname      = name;
        public String toString() {
            return getName();
    }[4]. LocationTest.java
    package test.temp;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LocationTest extends JPanel implements ChangeListener
        Ellipse2D.Double ball;
        Line2D.Double    line;
        JSlider          translate;
        double           lastTheta = 0;
        public void stateChanged(ChangeEvent e)
            JSlider slider = (JSlider)e.getSource();
            String name = slider.getName();
            int value = slider.getValue();
            if(name.equals("rotation"))
                tilt(Math.toRadians(value));
            else if(name.equals("translate"))
                moveBall(value);
            repaint();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(ball == null)
                initGeom();
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.red);
            g2.fill(ball);
        private void initGeom()
            int w = getWidth();
            int h = getHeight();
            int DIA = 30;
            int padFromEnd = 5;
            line = new Line2D.Double(w/4, h*15/16, w*3/4, h*15/16);
            double x = line.x2 - padFromEnd - DIA;
            double y = line.y2 - DIA;
            ball = new Ellipse2D.Double(x, y, DIA, DIA);
            // update translate slider values
            int max = (int)line.getP1().distance(line.getP2());
            translate.setMaximum(max);
            translate.setValue(max-padFromEnd);
        private void tilt(double theta)
            // rotate line from left end
            Point2D pivot = line.getP1();
            double lineLength = pivot.distance(line.getP2());
            Point2D.Double p2 = new Point2D.Double();
            p2.x = pivot.getX() + lineLength*Math.cos(theta);
            p2.y = pivot.getY() + lineLength*Math.sin(theta);
            line.setLine(pivot, p2);
            // find angle from pivot to ball center relative to line
            // ie, ball center -> pivot -> line end
            double cx = ball.getCenterX();
            double cy = ball.getCenterY();
            double pivotToCenter = pivot.distance(cx, cy);
            // angle of ball to horizon
            double dy = cy - pivot.getY();
            double dx = cx - pivot.getX();
            // relative angle phi = ball_to_horizon - last line_to_horizon
            double phi = Math.atan2(dy, dx) - lastTheta;
            // rotate ball from pivot
            double x = pivot.getX() + pivotToCenter*Math.cos(theta+phi);
            double y = pivot.getY() + pivotToCenter*Math.sin(theta+phi);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
            lastTheta = theta;  // save theta for next time
        private void moveBall(int distance)
            Point2D pivot = line.getP1();
            // ball touches line at distance from pivot
            double contactX = pivot.getX() + distance*Math.cos(lastTheta);
            double contactY = pivot.getY() + distance*Math.sin(lastTheta);
            // find new center location of ball
            // angle lambda = lastTheta - 90 degrees (anti-clockwise)
            double lambda = lastTheta - Math.PI/2;
            double x = contactX + (ball.width/2)*Math.cos(lambda);
            double y = contactY + (ball.height/2)*Math.sin(lambda);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
        JPanel getControls()
            JSlider rotate = getSlider("rotation angle", "rotation", -90, 0, 0, 5, 15);
            translate = getSlider("distance from end",  "translate", 0, 100, 100,25, 50);
            JPanel panel = new JPanel(new GridLayout(0,1));
            panel.add(rotate);
            panel.add(translate);
            return panel;
        private JSlider getSlider(String title, String name, int min, int max,
                                  int value, int minorSpace, int majorSpace)
            JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
            slider.setBorder(BorderFactory.createTitledBorder(title));
            slider.setName(name);
            slider.setPaintTicks(true);
            slider.setMinorTickSpacing(minorSpace);
            slider.setMajorTickSpacing(majorSpace);
            slider.setPaintLabels(true);
            slider.addChangeListener(this);
            return slider;
    }OK, My questions are:
    [1]. what I generated XML by XSTream is very complicated, especially for object LocationTest, Can we make it as simple as others such as Person object??
    [2]. after I run it, LocationTest will popup and a red ball in a panel will dsiplay, after I change red ball's position, I hope to persist it to xml, then when I read it back, I hope to get same picture, ie, red ball stiil in old position, How to do that??
    Thanks a lot!!

    Positive feedback? Then please take this in a positive way: if you want to work on persisting Java objects into XML, then GUI programming is irrelevant to that goal. The 1,000 lines of code you posted there appeared to me to have a whole lot of GUI code in it. You should produce a smaller (much smaller) example of what you want to do. Calling the working code from your GUI program should come later.

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • How to Use COM Component in a Java Bean

    Dear Sir,
    How can I use a COM Component in a Java-Bean . I am having a COM Component for reading Weighment Reading on a Serial Port and want to use this Component in a Java-Bean . I would also like to call the methods of this COM Component inside my Java-Bean . COM Component is a dll file .
    Please guide me how to go ahead . If possible kindly provide some sample code for the same .
    With Thanks and Regards
    B V Mittal

    You need a Java to COM bridge like Jacob. Try searching this forum for more information, I've answered this question several times before.
    Dom.

  • Using mysql decode function in Java

    Hi everybody,
    mysql documentation says:
    DECODE(crypt_str,pass_str) -->
    Decrypts the encrypted string crypt_str using pass_str as the password. crypt_str should be a string returned from ENCODE().
    I used the above function in a Python script and had no problem, but have difficulty using the same thing in my Java code.
    I receive runtime error when tried decode() in my Java code in executeQuery("s");. As far as I know the decode() function should be compiled, I can't run the decode() in the mysql command tool and receive a response (as I compiled and ran it in my Python script).
    Has anybody ever used this function in the Java code? How? What format did you use? What I should use instead of "s" in this code?
    conn is a database connection:
    stmt = conn.createStatement();
    rs = stmt.executeQuery("s");
    I even tried PreparedStatement, but no luck.
    Any help is greatly appreciated.

    stmt.executeQuery("select blahblahblah, DECODE(fieldName, password), blahblahblah FROM blahblah...")

  • Use of 'ME' keyword in ABAP Objects?

    Hi all,
       Can any one please  use of 'ME' keyword in ABAP Objects?
    Thanks,
    Vijay.
    Moderator message: next time, please search for available information before asking.
    Edited by: Thomas Zloch on Sep 16, 2010 5:33 PM

    Hi,
    Please find the description about the ME keyword as per the SAP documentation and help.sap.com.
    Within the implementation of every instance method, an implicitly created local reference variable called me is available, which points to the instance in which the method is currently being executed. The static type of me is the class in which the instance method is implemented.
    Each class implicitly contains the reference variable me. In objects, the reference variable mealways contains a reference to the respective object itself and is therefore also referred to as the self-reference. Within a class, you can use the self-reference me to access the individual class components:
    -To access an attribute attr of your class: me->attr
    -To call a method meth of your class: CALL METHOD me->meth
    When you work with attributes of your own class in methods, you do not need to specify a reference variable. The self-reference me is implicitly set by the system. Self-references allow an object to give other objects a reference to it. You can also access attributes in methods from within an object even if they are obscured by local attributes of the method.
    Regards,
    Sagar

Maybe you are looking for

  • No thumbnails in finder/preview after exporting files as dng out of lightroom?

    Does anyone have experience sorting out the issue of no thumbnails in finder/preview after exporting files as dng out of lightroom? There are several conversations in the forum about this problem, but cant seem to find a solution. Anyone know how to

  • Cretit control area field - Customer master - mass change

    Hi Gurus: I want to use the customer master mass change program (T.code XD99) to assign a default credit control area for all the customers. However when i try to save the mass changes it does not update the credit control area, and shows an informat

  • Customer invoice upload

    Hi,      i am working with interfaces.      i have a scenerio that      Branches(defined as plants in SAP) attached with  godowns which makes sales to customers and an invoice is raised these godown are not in SAP and values of the invoices  such as

  • Installing photoshop elements 8

    i had a chat the other day as i have this programme on another defunct computer.  it was released but now i have the problem that when i am trying to install on my new laptop i get as far as the preparig to install screen and then get the message 'sy

  • Server 2012 Three Teir PKI Deployment

    Hi I've been test building this on the bench prior to deployment. I have; 1x Offline Root CA 1x Online Intermediate Subordinate Enterprise CA 2x Issuing Enterprise Subordinate Enterprise CA's 1x Issuing Enterprise Subordinate Enterprise CA (will be i