DIGIT-ARC read-only archive · snapshot: July 23, 2026

Java Queries Here..

651 posts · originally from https://geek.digit.in/community/threads/java-queries-here.94845/

furious_gamer
furious_gamer Original post #1
Aug 4, 2008 at 5:29 PM
I face a lot of issues while i m running java when i started to learn it... And i think the same issues will still alive.. If anyone find such kinda issue then please post it here instead of creating a new thread..

Yes this thread is dedicatedto Java(if u like J2EE toooo....:D)

So please drop ur queries here...
furious_gamer
Aug 9, 2008 at 12:03 PM
No Java Queries..:!:...Thats so bad...
Instead of starting a new thread for ur java doubts plz try 2 post here.. This will help for newcomers to search their queries in one stop place...:D
Plasma_Snake
Aug 14, 2008 at 8:54 PM
Check this code out:
Code:
import java.io.*;

public class FileOps {
public static void main(String args[])
{
    File file = new File(args[0]);
    try
    {
        BufferedReader in = new BufferedReader(new FileReader(file));
        String s;
        s = in.readLine();
        while(s!=null)
        {
            System.out.println("Read " + s);
            s = in.readLine();
        }
        in.close();
    }
    catch(FileNotFoundException e1)
    {
        System.err.println("File Not Found" + file);
    }
    catch(IOException e2)
    {
        e2.printStackTrace();
    }
}
}
Now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FileOps.main(FileOps.java:13)
Java Result: 1
"
What's the solution? :confused:
A
Aug 14, 2008 at 9:57 PM
Just run the programme by giving the input file name at the command prompt. Syntax java classname inputfilename . Remember that input file should exist in same directory and should preferably be a text file.
C
Aug 14, 2008 at 10:40 PM
Just run the programme by giving the input file name at the command prompt. Syntax java classname inputfilename . Remember that input file should exist in same directory and should preferably be a text file.
Just a small note. The file need not exist in the same directory from which the program is executed. In that case, the complete path (absolute path) of the files should be specified.
B
Bandu #6
Aug 14, 2008 at 10:54 PM
+1 for the above 2 comments. I think you are not using the command prompt to run your java prog. Seems that you've configured some tool - like EditPlus or such. In that case, make sure that you chose the option that allows you to input parameters (just like command line parameters) to the program being run ("Prompt for Arguments" option in Editplus).

And yes, the file need not be in the same directory, but if the file or directory contains spaces, do enclose the entire path/name in double quotes.

- Bandu.
Plasma_Snake
Aug 14, 2008 at 11:06 PM
I'm using Netbeans 6.1 and JDK 1.6
B
Bandu #8
Aug 14, 2008 at 11:18 PM
I've never used Netbeans. Lookup for some help online for you to allow Netbeans to provide you a dialog for input parameters when you run FileOps.
C
Aug 14, 2008 at 11:22 PM
Right click on your project in the Projects window and select properties.

Then select "Run" from the left and in the Arguments field type the absolute path to the file. Now whenever you run that will be passed to the program.
A
Aug 18, 2008 at 2:58 PM
I am trying to use keylistener in java. Please expalain this error....

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sudoku1 extends Frame implements ActionListener,KeyListener {
    int i,j;
    int x,y;
    Button b;
    Graphics g;
    sudoku1(String s)
    {
            super(s);
            setTitle("Sudoku");
            setSize(1000,700);
            addKeyListener(this);           
            b=new Button("New Game");
            setLayout(new BorderLayout());
            b.addActionListener(this);
            add(b,BorderLayout.SOUTH);                     
            addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});
            setVisible(true);
            g=getGraphics();        
    }
    /*public void control(KeyEvent e)
    {
            if(e.getKeyCode()==VK_ENTER)
                JOptionPane.showMessageDialog(null,"right");
    }*/
    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyCode()==VK_RIGHT)
                JOptionPane.showMessageDialog(null,"right");
    }
    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}
    public void draw()
    {                
       g.setColor(Color.BLUE);
       x=500;
       y=350;
       i=j=0;
        while(i<10) //platform of the game is printed on screen.
	{
		g.drawLine(x-270+60*i,y-270,x-270+60*i,y+270);
		g.drawLine(x-270,y-270+60*i,x+270,y-270+60*i);
		if(i==3||i==6)
		{
			g.drawLine(x-270+60*i+2,y-270,x-270+60*i+2,y+270);
			g.drawLine(x-270,y-270+60*i+2,x+270,y-270+60*i+2);
		}
		i++;
	}
   
    }       
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b)
            draw();
    }
    public static void main(String[] args) {
        // TODO code application logic here
        sudoku1 m=new sudoku1("Sudoku");
        
    }

}

error is:

can't find symbol
symbol : variable VK_RIGHT

if(e.getKeyCode()==VK_RIGHT
B
Bandu #11
Aug 18, 2008 at 3:03 PM
There's an error in the code. Use KeyEvent.VK_RIGHT instead of VK_RIGHT. Change your if condition as follows:

Code:
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
A
Aug 18, 2008 at 3:11 PM
thanks that solved it.
Plasma_Snake
Aug 18, 2008 at 4:23 PM
this not a programming query but a simple JAVA related query. My friends have been asked lot of times during Viva and Placement interview that, Why the symbol of Java is cup of Coffee? AFAIK and tell 'em cause Java is also a name for a type of coffee and is also synonymous to Coffee in some countries that's why its Java and earlier Javabeans(now Netbeans). If I'm wrong then please do correct me. *s269.photobucket.com/albums/jj44/visio159/Unismilies/102.png
B
Bandu #14
Aug 18, 2008 at 4:52 PM
Me too thinks the same.

I've heard of a couple of theories:
(1) James Gosling thought of it while having a cup of coffee.
(2) They had earlier thought of the name (and possibly the symbol) Oak, but that had some copyright issues. They then hired a consultant who interviewed the team and came up with a list of names (Silk, Java, etc.). Java was chosen as it sounds refreshing.
(3) And this, to me seems the most reasonable answer to your question:

"The letters spell out the names of the three key developers: James Gosling, Arthur Van Hoff and Andy Bechtolsheim."
gary4gar
gary4gar #15
Aug 23, 2008 at 10:03 PM
any Good IDE for java?
B
Bandu #16
Aug 23, 2008 at 10:04 PM
Get IntelliJ IDEA if you / your company can affort it. Its the best one out there.
Eclipse is one of the freely available ones and is quite good too.

- Bandu.
M
mehulved #18
Aug 23, 2008 at 10:25 PM
geany
A
aniruddhc #20
Aug 26, 2008 at 8:18 PM
Well could you guys WAP in java to print the following pattern?? (Just give the base logic using the for loop)

*
**
***
****
***
**
*

the pattern is in the center with 1 star, next line two stars then next line 3 stars ..... 4 stars then decreasing to 1 star...

thanks
B
Bandu #21
Aug 26, 2008 at 8:28 PM
^^ I hope thats not a school assignment.

Anyways, the logic is pretty simple.
(1) Have an outer loop iterate thru 0 to 4. End it with System.out.println().
(2) Have an inner loop iterate through 0 till i and print a single *.

The above steps will give you the first part of the pattern. Reverse the logic to get the lower half.

- Bandu.
P.S. There are other ways to do this and there might be more simpler ways as well.
Code:
for(int i = 0; i < 4; i++, System.out.println())
            for(int j = 0; j <= i; j++)
                System.out.print("*");

Edit: The thread subscription email that I received has a different pattern. If it is the exact opposite of whats seen in the thread, then u'll have to slightly modify the loop structures:
Code:
for(int i = 0; i < 4; i++, System.out.println())
  {
   for(int j = 4; j > i; j--)
    System.out.print(" ");
   for(int k = 0; k <= i; k++)
    System.out.print("*");
  }
furious_gamer
Aug 27, 2008 at 10:56 AM
^^ I hope thats not a school assignment.

Anyways, the logic is pretty simple.
(1) Have an outer loop iterate thru 0 to 4. End it with System.out.println().
(2) Have an inner loop iterate through 0 till i and print a single *.

The above steps will give you the first part of the pattern. Reverse the logic to get the lower half.

- Bandu.
P.S. There are other ways to do this and there might be more simpler ways as well.
Code:
for(int i = 0; i < 4; i++, System.out.println())
            for(int j = 0; j <= i; j++)
                System.out.print("*");
Edit: The thread subscription email that I received has a different pattern. If it is the exact opposite of whats seen in the thread, then u'll have to slightly modify the loop structures:
Code:
for(int i = 0; i < 4; i++, System.out.println())
  {
   for(int j = 4; j > i; j--)
    System.out.print(" ");
   for(int k = 0; k <= i; k++)
    System.out.print("*");
  }

He just ask the logic, but u provide him the code.... :rolleyes:
B
Bandu #23
Aug 27, 2008 at 1:55 PM
He just ask the logic, but u provide him the code.... :rolleyes:
I kinda disappointed Aniruddh the last time with his Electronic showroom thing, and he's really at a very early stage of learning, so I thought it might help him better this way than exchaning multitude of PM's and emails for a trivial thing as this.

- Bandu.
A
aniruddhc #24
Sep 2, 2008 at 1:05 AM
Bandu I need to make the pattern in a diamond shape... The digit forum fsoftware doesnt allow me to post it in a diamond way

i think i need 6 loops, but i am not sure...

your logic unfortunately does not work...
B
Bandu #25
Sep 2, 2008 at 1:42 PM
@Aniruddh, post your required output enclosed in [ CODE] [/ CODE].

your logic unfortunately does not work...
*i38.tinypic.com/33l2q81.jpg
D
Sep 6, 2008 at 11:22 AM
how to use java persistence api in core java?
C
Sep 6, 2008 at 1:08 PM
^^ See here.

*en.wikibooks.org/wiki/Java_Persistence/Runtime#Java_Standard_Edition
D
Sep 6, 2008 at 4:10 PM
^^ See here.

*en.wikibooks.org/wiki/Java_Persistence/Runtime#Java_Standard_Edition

that example is for ejb which require application server but i want to use jpa in core java application.
C
Sep 6, 2008 at 5:12 PM
See the section titled "Java Standard Edition".

It does work without Java EE server.
D
Sep 6, 2008 at 11:12 PM
but how to use it with core java? do u have any example?
C
Sep 6, 2008 at 11:14 PM
Core Java == Java SE.

I feel the code snippet there is good enough (if you have already worked with JPA in Java EE apps).
D
Sep 7, 2008 at 4:05 PM
i think i found the solution EntityManager can only be injected in ejb
*saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=78&t=003857

i'll try with spring
C
Sep 7, 2008 at 4:18 PM
As the URL I provided clearly says, it is not injected but rather should be created by code.
Code:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("acme");
EntityManager entityManager =  factory.createEntityManager();
...
entityManager.close();
D
Sep 7, 2008 at 8:35 PM
ah it worked thanks

PHP:
package com.ocricket.entity;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.Logger;

/**
 * 
 */
public class EntityManagerUtil {
    
    private static final EntityManagerFactory emf; 
    private static final ThreadLocal<EntityManager> threadLocal;
    Logger log = Logger.getLogger(EntityManagerUtil.class);

    
    static {
        emf = Persistence.createEntityManagerFactory("OCRICKETPU");         
        threadLocal = new ThreadLocal<EntityManager>();
        
}
        
    public static EntityManager getEntityManager() {
        EntityManager manager = threadLocal.get();        
        if (manager == null || !manager.isOpen()) {
            manager = emf.createEntityManager();
            threadLocal.set(manager);
        }
        return manager;
    }
    
     public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        threadLocal.set(null);
        if (em != null) em.close();
    }
    
    public static void beginTransaction() {
        getEntityManager().getTransaction().begin();
    }
    
    public static void commit() {
        getEntityManager().getTransaction().commit();
    }  
    
    public static void rollback() {
        getEntityManager().getTransaction().rollback();
    } 
    
    public static Query createQuery(String query) {
        return getEntityManager().createQuery(query);
    }
    

    
}

PHP:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="*java.sun.com/xml/ns/persistence"
    xmlns:xsi="*www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="*java.sun.com/xml/ns/persistence
    *java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="OCRICKETPU"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>
            <property name="hibernate.connection.driver_class"
                value="org.postgresql.Driver" />
            <property name="hibernate.connection.url"
                value="jdbc:postgresql://localhost:5432/ocricket" />
            <property name="hibernate.connection.username"
                value="postgres" />
            <property name="hibernate.connection.password"
                value="000000" />
            <property name="databasePlatform"
                value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.use_sql_comments" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="create" />


        </properties>
    </persistence-unit>

</persistence>
C
Sep 7, 2008 at 11:09 PM
You are welcome. :)

Java rocks!! :D
dashang
dashang #36
Sep 13, 2008 at 10:06 AM
I am looking for code to create login java program in which user enter pass if its correct run remaining program else terminate/ Help me guys. I am having problem with whowing '*' as display how to do it???
C
Sep 13, 2008 at 10:59 AM
You have not mentioned the type of app you are creating. So I'm suggesting for both desktop and web apps.

Desktop App:

Use the JPasswordField swing component.

Normal Web App:

Use <input type="password" />

JSF Web App:

Use <h:inputSecret />
dashang
dashang #38
Sep 13, 2008 at 1:16 PM
Hey chandru can you give of full code from importing classes till end. Just give me password match code that is code for " getting pass and matching it and showing stars in pass while writing(optional)
D
Sep 17, 2008 at 12:06 PM
do u want it for web application?

or desktop application?
C
Sep 17, 2008 at 1:10 PM
Hey chandru can you give of full code from importing classes till end. Just give me password match code that is code for " getting pass and matching it and showing stars in pass while writing(optional)
Going through the TLD docs and Java docs of the class and Tag I provided you should clarify everything for you.
Faun
Faun #41
Sep 19, 2008 at 3:35 PM
just a simple query.

How do I send a swing application to end user which will require him to just double click and start it.

I have created a jar file but then I need a bat file to start it. Ok its fine but there also starts a command prompt in background which is a turn off for me.

GOT THE ANSWER :)

Use javaw instead of java
M
Sep 19, 2008 at 3:48 PM
try executing your jar file with following command:

start javaw -jar myapp.jar

Though, command prompt will appear for a second, then it will disappear..

Or you can create a shortcut to javaw.exe and give above parameters to it, this probably won't even show you the command prompt for a second also.. but i am not sure if this will really work.. You can try it out and let us all know about its result..
Faun
Faun #43
Sep 19, 2008 at 3:50 PM
^^yup, thanks.

Btw is there any way to start the application by just clicking on jar file ?
M
Sep 19, 2008 at 3:59 PM
For that you can change the file type details in windows and make it open with javaw by default..

For more details see this
C
Sep 19, 2008 at 3:59 PM
For Windows

You can use this utility to create an executable wrapper around your JAR.

For Linux

Unlike Windows, a simple shell script will do the trick for Linux as it won't open a terminal window unless user chooses to.

Just in case you'd like a platform independent splash screen for your desktop App you can add following line to your Jar's manifest.

Code:
Splashscreen-Image: <image_path_relative_to_JAR>
Faun
Faun #46
Sep 19, 2008 at 4:13 PM
^^Hey,thanks
let me check it out, btw I have made the app in linux but the client and the company will use in windows.
ray|raven
ray|raven #47
Sep 19, 2008 at 4:25 PM
^ Or you could use the SplashScreen class , to display one.

More here : *java.sun.com/docs/books/tutorial/uiswing/misc/splashscreen.html
Faun
Faun #48
Sep 19, 2008 at 4:44 PM
^^its cool but for first iteration am wrapping it in exe (which is in priority 1 condition) and then for next iteration all graphical enhancements are slated to work upon.

One more thing:

I just logged in to XP and found that the jar created is an executable, that means I can run it by double clicking..lolz

Can someone explain me why does it working now on double clickin.

All I did yesterday was

jar cvmf manifest.stab appname.jar .

So is it wise to use it like this or make an exe too, which is a bit large in size compared to jar.
C
Sep 19, 2008 at 5:48 PM
^ Or you could use the SplashScreen class , to display one.

More here : *java.sun.com/docs/books/tutorial/uiswing/misc/splashscreen.html

Splashscreen class cannot be used to create a splash screen as such. You can use it to manipulate the splash screen only if one already exists (either given in commandline or in JAR's manifest).

One more thing:

I just logged in to XP and found that the jar created is an executable, that means I can run it by double clicking..lolz

Can someone explain me why does it working now on double clickin.

All I did yesterday was



So is it wise to use it like this or make an exe too, which is a bit large in size compared to jar.

It always works upon double-click if the .jar files are associated with "java -jar" or "javaw -jar" commands. The Windows version of JRE installer does the association automatically. On Linux (I tried on Ubuntu), this is done if you install JRE from the repos.

Using the EXE wrapper allows for more customizations to blend with the Windows environment (like creating an icon for your app's executable). It also allows you to bundle a JRE so that your app will work even if the user does not have a JRE pre-installed and .jar associations performed. If you don't bundle JRE, it can also check whether right JRE version is installed and if not will automatically open the JRE download URL. Simple JAR association gives a very unfriendly message to user in such cases.
Faun
Faun #50
Sep 19, 2008 at 5:58 PM
K so I will make exe just in case the system on which it is used is the most obsolete one to support anything :p

Thanks for all the info.
Faun
Faun #51
Sep 25, 2008 at 7:28 PM
One more query guys !

How do I catch memory leaks in my program. Any thing to watch and correct it.
C
Sep 26, 2008 at 12:00 PM
Memory leaks in Java programs are very rare. It can happen only if you code very badly.

Using appropriate scoping for variables and adhering to basic OOP is all that is needed. The rest will be taken care of by GC. :)
parthbarot
Sep 26, 2008 at 6:44 PM
no mate... for memoery u have to be carful..i mean..u should take care of things which can cause leaks and heap explodes :).

and yah,many have asked abt best IDE for java... so i m suggesting u..

as a professional java prog., u can use Eclipse or IntelliJ Idea..but idea is paid on (abt $500 :D) and eclipse is open source.. so most of corporates are using eclipse.

REGARDS.
Faun
Faun #54
Sep 26, 2008 at 7:01 PM
yeah i know GC does work automatically.

But any way to check the heap and stack for running program. I mean a graphical stat type view.
C
Sep 26, 2008 at 7:15 PM
Starting with Java 6 update 7, Visual VM is built right into JDK. It is a really good tool for monitoring your JVM instances. Visual VM can be downloaded separately for Any version of Java 6 from here.

Apache's JMeter is a highly advanced monitoring tool too.
Faun
Faun #56
Sep 26, 2008 at 7:26 PM
I'm on linux (Arch Linux). This is the output of java -version
java version "1.6.0_07"
Java(TM) SE Runtime Environment (build 1.6.0_07-b06)
Java HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)

So how do I start visual VM ?
C
Sep 26, 2008 at 7:44 PM
Just type visualvm on your terminal and rock on!

For further references, read *visualvm.dev.java.net/gettingstarted.html
Faun
Faun #58
Sep 26, 2008 at 8:15 PM
Thanks buddy, I owe you :D

But the exact command is jvisualvm.

Thanks you for all your help :)

*i269.photobucket.com/albums/jj44/visio159/Screenshot-JavaVisualVM.png
C
Sep 26, 2008 at 8:22 PM
Oops! Missed the 'J'. :D

no mate... for memoery u have to be carful..i mean..u should take care of things which can cause leaks and heap explodes :).
If all references are well scoped and proper OO principles are followed, there is no need to worry about memory management (both stack and heap). If you still feel there can be need to worrying about memory, pls give me a sample program scenarios following proper OOP principles, which can lead to OutOfMemoryError.
parthbarot
Sep 27, 2008 at 10:34 AM
thats wht i meant yaar...that u have to take care of references and conections like resources.. which can create probs :)

regards.
Pathik
Pathik #61
Oct 18, 2008 at 2:07 PM
Is there any API I can use to create apps that use Bluetooth on PCs? I am not talking of the Java ME JSR 82 API. I need something which I can use with a bluetooth dongle. Thanks.
furious_gamer
Oct 18, 2008 at 2:21 PM
Is there any API I can use to create apps that use Bluetooth on PCs? I am not talking of the Java ME JSR 82 API. I need something which I can use with a bluetooth dongle. Thanks.

AFAIK There is no such API to create apps for bluetooth except the J2ME API u mentioned.... (Correct me if i am wrong...)
C
Oct 18, 2008 at 2:38 PM
There are implementations of JSR-82 for Java SE. Have a look at bluecove project *code.google.com/p/bluecove/

Note: bluecove does not pass the TCK for JSR-82 due to deficiencies in WIDCOMM stack. *www.bluecove.org/tck/

If you are interested in commercial APIs, *www.javabluetooth.com/development_kits.html
Plasma_Snake
Nov 1, 2008 at 10:27 PM
Does SUN provides detailed help files for JAVA like MSDN? Where? Please
I don't have detailed Java knowledge, just ur ordinary n00b but I want to try my hand at Game programming in Java and got e-book "Killer Java Game Programming" I'm just on its second chapter and my head is already cartwheeling and flipping. :-?
I want to know what tools I need exactly. I've following installed:

  1. Netbeans 6.1 (full 219MB one)
  2. Java3d-1_5_1
  3. Java_ee_sdk-5_05
  4. Jdk-6u7-windows-i586-p
What more do I need? I type just following lines and get the following error:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;

import com.sun.j3d.utils.timer.J3DTimer;
In the last Import statement I get the following error "package com.sun.j3d.utils.timer does not exists"
This code I'm trying to compile and run is given as verified runnable as given and mentioned by author of the book. I'm just trying to code it again for the sake of my understanding. Please tell me whats wrong and help me please. :cry:
B
Bandu #65
Nov 1, 2008 at 10:36 PM
I am not sure how MSDN help looks like. I've this page bookmared for Java: *java.sun.com/j2se/1.4.2/docs/api/

As far as your installation goes, I think you have pretty much everything you need. For beginners, however, I still recommend starting out the harder way - using simple tools like Editplus and such so that you get a complete understanding of how things work in Java - classpaths, etc. Using IDEs (like Netbeans) make the whole thing transparent to the developer. It's important to get an understanding of such things. It would help if you start out with simpler programs before jumping into advanced topics like awt, swing, etc.

For the error, make sure that you have your classpath set correctly. You probably are missing a jar file or two in the classpath. I am not sure which, but should be some j3d.jar or some 3d.jar file. Try looking for such a file somewhere in your installations and if you find it, append its path to the CLASSPATH variable.

- Bandu.
C
Nov 2, 2008 at 12:26 AM
I'd echo Bandhu but with a link for more recent Java release ;) *java.sun.com/javase/6/docs/api/

Regarding cartwheeling and flipping, that's what is bound to happen when you try to ride a Ducati at full throttle when you haven't yet learnt to balance a two-wheeler. :p

Put aside the book you have and get "Head First Java". Once you are crystal clear with the basics of Java programming, come back to your current book. Good luck with your adventures in Java.
Plasma_Snake
Nov 2, 2008 at 1:29 AM
Well if u see earlier posts in this thread, I've done Java in my college in 5th Semester and 3 times in my local NIIT center so basic topics like Array, Inheritence, Overloading and Overidding are clear to me but things like Swings and Threads are what that need more practice and I seriously need to learn Java I/O ops and classes 'cause I personally feel that without it Java learning is useless.
C
Nov 2, 2008 at 1:46 PM
I didn't mean to be rude with the ducati example. I'm sorry if you had felt so.

Multi-threading is an absolute must for any Java programming. JVM,s extraordinary concurrency capabilities is what makes it such a valuable platform on servers. Concurrency is also mandatory for game programming. So, I'd suggest that you focus on Threading and it subtleties before going into full-fledged game programming.
Plasma_Snake
Nov 2, 2008 at 2:27 PM
I wasn't offended at all, I was just giving my history with Java so as to let u know my level of Java understanding. I PMed the mods and look, the Thread now is Sticky :)
Now the question part, as mentioned by me in my earlier post I've Java 3D installer and installed it too. Now please tell me how can I use the packages and classes of this Java3D in my Netbeans or programs that I create i.e. incorporating it in Java SDK? :confused:
if I'm not wrong, the error that I was getting in one of my earlier posted problem was mainly because Netbeans wasn't able to find the mentioned package of Java 3D in its libraries or am I still missing the point? :-?
furious_gamer
Nov 3, 2008 at 11:40 AM
@Plasma_Snake:
Netbeans wasn't able to detect Java 3D.... And AFA Swing and related stuffs, go thru some books like Swing Cook books and etc to get good knowledge on it.... Swings are not so tough as Java basics and once you get good knowledge in basics then swings is nothing to learn, except the API... And I/O, better learn from Head first and try some online tutorial...
Best way is try some examples urself and if u have any doubt post it here...
Faun
Faun #71
Nov 5, 2008 at 1:50 PM
here is one query;

Suppose I have scanned an image and want to know its lenght and breadth. Will it be possible to get the original length and breadth irrespective of the dpi at which its scanned.

I'm able to get the resolution of an image.

Guide me...if there is some way.
D
Nov 9, 2008 at 12:20 AM
youtube's comment system is now powered by java (servlet)!

Code:
*in.youtube.com/comment_servlet?all_comments&v=GvctSMHHd7g&ytsession=p9A_Dz6f8kXK5uX7c4IxRXCHB9HQut1nIGY5pSuqgGeeKrFz1pYtma0JOAMlINEJELSf9R85VAbMqGZhLjBDGw-Jg8LGV1e2C3ZTLwiHnz5f7eHpk5aIrfFVkmJksyn4pw4ur6twt4OoW7N8aRmBD58Ft-kefWBBDA3BsU4PJ7IrnfR5Jd-HXVRcOI_fnGg1GAXU8k0OCbr-I024_h6l0AL3TaaGGAFdED_egjgErjDuWe3e_-R89fqmuZ8a8-hn-wnsNIl-O5BqZT26bLzr1wCK2f4V76Z_dO7xfKe7BQQ
Faun
Faun #73
Nov 9, 2008 at 12:23 AM
mfg, good to know !
D
Nov 13, 2008 at 11:07 PM
how to read value from custom annotation?
for example if i have cuustom annotation
@Permission(name="ADMIN")

how can i read the value admin during run timer?
B
Bandu #75
Nov 14, 2008 at 12:12 AM
^Thanks to you, I learnt something new in Java 1.5 today. But, unfortunately not enough to answer your question. You might want to look into com.sun.javadoc, JSR-269 (Pluggable Annotation Processing API), and the new 1.5 reflection API.

If you do find an answer, please post a small example and solution if possible.
C
Nov 14, 2008 at 10:01 AM
@Desi

If Permission is a custom annotation defined by you, set its retention policy to RUNTIME. Here is a complete sample code.

Code:
package demo;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
	String name();
}

Code:
package demo;

public class Main {
	public static void main(String[] args) {
		Demo demo = new Demo();
		Permission permission = demo.getClass().getAnnotation(Permission.class);
		System.out.println(permission.name());
	}
}

@Permission(name = "ADMIN")
class Demo {

}
D
Nov 14, 2008 at 10:45 PM
@ chandru.in thanks a lot that is a very useful example
D
Nov 16, 2008 at 6:27 PM
hi is it possible to separate model from jsf's managed bean? in struts 2 we use ModelDriven interface to achieve that.

Struts example

Model
Code:
/**
 * User Model 
 **/
public class User {

    
    private String username;
    private String password;
    private int age;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
Struts 2 acton
Code:
/**
 * Action 
 **/
public class Login extends ActionSupport implements ModelDriven<User>{

    
    private  User user;

public User getModel() {
      
        return user;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    
    // Acton
    
    public String login (){
        return "outcome";
        
    }
    
    
}
mapping
Code:
<package name="user" extends="struts-default">
        <action name="login"
            class="com.desitek.cricket.action.Login">
            <result name="input">index.jsp</result>
            <result name="success">index.jsp</result>
            <result>index.jsp</result>
        </action>
    </package>
and jsp
Code:
 <s:actionerror/> <s:actionmessage/> 
     <s:fielderror></s:fielderror>
     
     <s:form action="login" theme="simple">
     User Name
     <s:textfield name="user.Username"></s:textfield>
     Password: <s:textfield name="user.UserPassword"></s:textfield>
      <s:submit value="login"></s:submit>
     </s:form>
C
Nov 17, 2008 at 9:02 AM
The same can be done in JSF too. However, unlike Struts JSF doesn't make you implement any interface. I guess your mapping is out of sync with your code. So my example may not exactly reflect your requirements.

For JSF, this is how your Login class would look.
Code:
public class LoginAction {

    
private  User user;

public User getModel() {
      
        return user;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    
    public String login (){
        return "outcome";
    }    
}

Managed bean and Navigation rule

Code:
<managed-bean>
		<managed-bean-name>login</managed-bean-name>
		<managed-bean-class>com.desitek.cricket.action.LoginAction</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>

	<navigation-rule>
		<from-view-id>login.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>index.jsp</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-outcome>failure</from-outcome>
			<to-view-id>login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
D
Nov 17, 2008 at 2:52 PM
i tried that but it is giving this error when i submitted the form

Code:
javax.servlet.ServletException: /login.jsp(35,2) '#{user.user.username}' Target Unreachable, 'user' returned null
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
[B]root cause[/B] 
org.apache.jasper.el.JspPropertyNotFoundException: /login.jsp(35,2) '#{user.user.username}' Target Unreachable, 'user' returned null
    org.apache.jasper.el.JspValueExpression.getType(JspValueExpression.java:61)
    com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:81)
    javax.faces.component.UIInput.getConvertedValue(UIInput.java:934)
    javax.faces.component.UIInput.validate(UIInput.java:860)
    javax.faces.component.UIInput.executeValidate(UIInput.java:1065)
    javax.faces.component.UIInput.processValidators(UIInput.java:666)
    javax.faces.component.UIForm.processValidators(UIForm.java:229)
    javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1030)
    javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:662)
    com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:100)
    com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
here is my model
Code:
package com.desitek.cricket.action;

/**
 * Action 
 **/
public class User {

    
    private String username;
    private String password;
    private String email;


    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
Code:
package com.desitek.cricket.action;

public class LoginAction {

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String login() {
        System.out.println(user.getUsername());
        return "success";
    }
}
login.jsp
Code:
<f:view>
        This is my JSF JSP page. <br>
            <h:form>
        Username
        <h:inputText value="#{user.user.username}"></h:inputText>
        Password
        <h:inputText value="#{user.user.password}"></h:inputText>
        <h:commandButton action="#{user.login}" value="submit" ></h:commandButton>

            </h:form>
        </f:view>
Code:
<managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>com.desitek.cricket.action.LoginAction</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

    <navigation-rule>
        <from-view-id>login.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>index.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>failure</from-outcome>
            <to-view-id>login.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
C
Nov 17, 2008 at 3:40 PM
Have you set the value of user within LoginAction class?
D
Nov 17, 2008 at 4:01 PM
finally i fixed the problem by creating new instance of user in properties

Code:
 package com.desitek.cricket.action;

public class LoginAction {

    private User user = new User();

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String login() {
        System.out.println(user.getUsername());
        return "success";
    }
}
C
Nov 17, 2008 at 4:47 PM
Exactly that's what I meant. :)
Plasma_Snake
Nov 18, 2008 at 7:44 PM
OK, guys here r 2 very n00bish questions from me so answer 'em like Experts ;) :D
1.Can we create or instantiate Object of a class, in a class other than main? I mean is this possible?
Code:
 class A { some code}
 class B {some code A a = new A}
 class C{
p s v main
{some code}
}
2. can we make a Static Array?
Hope u r able to understand the questions. :neutral:
B
Bandu #85
Nov 18, 2008 at 7:57 PM
1. Yes. Thats what most of the times classes are for - instantiation, unless they are private in some other package or have private constructors. You need to see topics regarding class visibility - public, default, package, etc.

2. Yes, you can. What made you think you cannot.

Example for #1:
*img48.imageshack.us/img48/5640/plasmacr2.th.png*img48.imageshack.us/images/thpix.gif

Example for #2:
*img171.imageshack.us/img171/2609/plasmasnakewh0.th.png*img171.imageshack.us/images/thpix.gif
Plasma_Snake
Nov 19, 2008 at 2:34 AM
Thanx for the screenshots, cleared the doubt like Harpic cleans the $hit from the flush. :D
In the first example u've created the object of A in constructor of B. Is it the only way or it can be done another way also? :idea:
thewisecrab
Nov 19, 2008 at 2:38 AM
OK, this is really n00bish compared to your standards, but still:
can anyone explain the "while","do while" functions (ie.loop) with an example? e-books arent helping here :|
QwertyManiac
Nov 19, 2008 at 3:49 AM
Thanx for the screenshots, cleared the doubt like Harpic cleans the $hit from the flush. :D
In the first example u've created the object of A in constructor of B. Is it the only way or it can be done another way also? :idea:
An object can be created anywhere, anytime from a class as long as its scope allows it to be. Have you not learnt OO concepts at school yet?
B
Bandu #89
Nov 19, 2008 at 7:51 PM
In the first example u've created the object of A in constructor of B. Is it the only way or it can be done another way also? :idea:

I used the constructor for the example. You can create it anywhere. Constructor is just another method + something more, which isn't the topic at the moment, so I'll refrain from writing about constructors.

OK, this is really n00bish compared to your standards, but still:
can anyone explain the "while","do while" functions (ie.loop) with an example? e-books arent helping here :|


I won't call it n00bish. Can be quite confusing even for seasoned programmers.


*img210.imageshack.us/img210/8887/twcrh5.th.png*img210.imageshack.us/images/thpix.gif

Code:
        [COLOR=SeaGreen][B]while(i < 2)[/B][/COLOR]
        {
            ...
        }

        System.out.println("\nTesting the exit controlled loop\n");
        int j = 0;
        do
        {
            ...
        } [COLOR=Red][B]while (j == 100);[/B][/COLOR]
    }
}
while loop is also called as "entry controlled" loop. With this, the code statements within the loop body are executed only if the boolean condition evaluates to true and this evaluation is carried out before entering the loop. Thats why entry controlled. The boolean condition is evaluated first before entering the loop body. Example is the green one in the above snippet.

do...while is also called as "exit controlled" loop. With this, the code statements are executed first. The control does enter the loop body and executes the statements within. At the end lies the boolean condition. Red one in the above code. If this condition evaluates to true, control loops back to the first statement in the loop body and so on... until the condition evaluates to false.

Its difficult to give an example... *searches_for_do_while_in_code* :)

Found...

I had a situation where I had to parse a line from a csv (comma separated values) file and process each part. Lets say, print each part of the token.

An example string: think,digit,rocks
Another example: digit

Both are valid csv examples. You can type in these lines in a file, save it as a .csv and open it in excel. It will work. Each token that is separated by a comma goes into a XL cell:

*img513.imageshack.us/img513/4739/csvvn0.th.png*img513.imageshack.us/images/thpix.gif

Anyways, back to the example.

The solution would be - no matter if a comma exists or not, we have to process the input - irrespective of the boolean condition (of having a comma in the string).

Note: The italicized words above is the boolean condition, and the underlined words form the loop body.

*img155.imageshack.us/img155/7893/twccsvparsefx9.th.png*img155.imageshack.us/images/thpix.gif
P.S. Refer Chandru's comment below. Do not use this as an example for CSV parsing. It's written to be an example for exit controlled loop. CSV parsing can be achieved more simply using Chandru's suggestion below.
C
Nov 19, 2008 at 9:08 PM
[OFF TOPIC]

That CSV line can parsed easily using String.split(",") method.
thewisecrab
Nov 19, 2008 at 9:13 PM
I won't call it n00bish. Can be quite confusing even for seasoned programmer......................is the boolean condition, and the underlined words form the loop body.

*img155.imageshack.us/images/thpix.gif
Thanks man. Really great explanation (although it took some time to understand use of words such as "boolean" etc. as they are not used commonly [I know what boolean means :p] )
In the end, problem solved :)
You'll here more simple questions from me in future :D
Plasma_Snake
Nov 19, 2008 at 9:15 PM
I was just comparing C# with JAVA and few of these questions just popped up in my mind so asked. :)
@QwertyM
If u r questioning my programming knowledge then I can tell u this that I've done Java 4 times in past 1 year but still ain't fully clear to me as possibilities are limitless in these Purely OOP languages. This thread is for asking questions, isn't it?
B
Bandu #93
Nov 19, 2008 at 9:20 PM
[OFF TOPIC]

That CSV line can parsed easily using String.split(",") method.

Yes, I know that. Good that you mentioned so that anyone coming to this thread does not take it as an example for csv parsing (infact I've edited my original post to mention this). But in my case, that was a legacy code. Moreover, I just modded it and simplified it to serve as an example here. The actual code has lots of other things that a String.split would not have served anyways.
C
Nov 19, 2008 at 9:38 PM
Yes, I know that. Good that you mentioned so that anyone coming to this thread does not take it as an example for csv parsing (infact I've edited my original post to mention this). But in my case, that was a legacy code. Moreover, I just modded it and simplified it to serve as an example here. The actual code has lots of other things that a String.split would not have served anyways.
I never meant to undermine your reply. :)
B
Bandu #95
Nov 19, 2008 at 9:43 PM
^^ Nopes. I did not say so either. What made you think that way? In fact, I appreciate you bringing it up.
C
Nov 19, 2008 at 9:46 PM
^^ Nopes. I did not say so either. What made you think that way? In fact, I appreciate you bringing it up.
Chill never mind. Let's stick to our cup of Java. :D
QwertyManiac
Nov 20, 2008 at 5:14 PM
@QwertyM
If u r questioning my programming knowledge then I can tell u this that I've done Java 4 times in past 1 year but still ain't fully clear to me as possibilities are limitless in these Purely OOP languages. This thread is for asking questions, isn't it?
No, its just that the doubt was too trivial. Why would I wanna doubt your programming knowledge? :\
Plasma_Snake
Nov 20, 2008 at 5:27 PM
Anyhoo, I would like to tell all of u guys that, as I'm also doing a 3 year GNIIT from my local NIIT center, besides my B.Tech in I.T, I had the option to choose an elective subject there and options were PL/SQL, ASP.NET(SOAP,WES 3.0) and J2ME. Guess what I chose??? ;) :D Classes for it will begin early next year so till then I've to get good in my Core JAVA. That I'll do by myself and with ur help and support but for J2ME, they'll give books too but can u guys recommend some good ones which are of Engineering student's level, not n00bish like NIIT's?
D
Nov 20, 2008 at 9:25 PM
niit is a worst place to learn java their gniit course sucks most of the java related course in gniit is outdated.
Plasma_Snake
Nov 20, 2008 at 9:52 PM
^^ Hey I'm just in for the certifications, I don't even read their books, only for passing their exams, for Core I've followed, Java 2 Complete Reference by Herbert Schildt, so now askin' one for J2ME
quad_master
Nov 21, 2008 at 2:43 PM
https in java

i need some basic concept how to implement https in java...do u have any reference/tutorial/links...i wanna understand it...:D
no code please...!!!
D
Nov 21, 2008 at 9:30 PM
Re: https in java

i need some basic concept how to implement https in java...do u have any reference/tutorial/links...i wanna understand it...:D
no code please...!!!
thats dependent on server not java
quad_master
Nov 25, 2008 at 1:03 PM
Re: https in java

thats dependent on server not java

i agree! but what is the process so that server starts accept https connection??

im using tomcat...plz help...
QwertyManiac
Nov 25, 2008 at 4:06 PM
Tomcat 4 - Guide to using SSL (For https connections)
sganesh
sganesh #105
Nov 30, 2008 at 11:44 AM
hi Guys,
I ve one SCJP question,pl gimme answer with explanation.
Thanks in Advance....
----------------------------------------------

public class ThreadStarter extends Thread
{
private int x= 2;
public static void main(String args[]) throws Exception
{
new ThreadStarter().makeItSo();
}
public void ThreadStarter(){
x=5;
start();
}
public void makeItSo() throws Exception {
join();
x=x- 1;
System.out.println("answer:"+x);
}
public void run() {
x*=2;
}
}
--------------------------------------------------------
C
chandru.in #106
Nov 30, 2008 at 12:08 PM
Output: Execute the code.

Hint: ThreadStarter() is an instance method.
sganesh
sganesh #107
Nov 30, 2008 at 2:43 PM
hi ,
The output of above question is 1..
I dont know how it come,,Anyone pl explain!
C
chandru.in #108
Nov 30, 2008 at 2:46 PM
As I hinted, ThreadStarter() is a method and not a constructor. Hence the default constructor which leaves x untouched is invoked. And later makeItSo() you are decrementing it and hence the output 1.
sganesh
sganesh #109
Nov 30, 2008 at 3:52 PM
Thanks a lot..
i got it!!
Plasma_Snake
Nov 30, 2008 at 4:14 PM
I didn't, care to illustrate a bit more.
C
chandru.in #111
Nov 30, 2008 at 4:19 PM
Constructors in Java should not have any return type (not even void). The moment a return type is specified, it turns into a normal method and hence not invoked during instantiation.
gary4gar
gary4gar #112
Nov 30, 2008 at 4:35 PM
I am Reading Java Series on "Core Java" by Sun MicroSystems Press. It is written by Cay S.Horstmann & Gary Cornell. Although the book is really Good and explains each aspect of java API & associated libraries.

But wonder why they are so much against C/C++:|

anyways, the Book is good read for *programmers* looking to switch to Java. as anyone learning to code first time should skip this. don't believe me check out the first HelloWorld programs given in chapter 1:p
C
chandru.in #113
Nov 30, 2008 at 5:30 PM
But wonder why they are so much against C/C++:|
Because those are the languages whose shortcomings, Java was meant to solve. Today C/C++ and Java rule entirely different territories.
as anyone learning to code first time should skip this. don't believe me check out the first HelloWorld programs given in chapter 1:p
I have never read that book. Can you post the code for us to view?
gary4gar
gary4gar #114
Nov 30, 2008 at 11:11 PM
Code:
public Welcome {
public static void main(String args[]) {

String[] greeting = new String[3]; 
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[3] = "and Gary Cornell";

for(int i = 0; i < greeting.length; i++)
System.out.println(greeting[i]);
}

}

this is a first program given in the book. the authors call Welcome program extremely simple.

Indeed its simple for programmers but for newbies its a steep learning curve, they have use concepts of arrays,loops etc right into the first program;)
C
chandru.in #115
Nov 30, 2008 at 11:13 PM
Code:
public Welcome {[INDENT]public static void main(String args[]) {[/INDENT][INDENT][INDENT]String[] greeting = new String[3]; [/INDENT][/INDENT]
this is a first program given in the book. the authors call Welcome program extremely simple.
Please check whether you typed in properly. I really don't think it would be this crappy. :confused:
gary4gar
gary4gar #116
Nov 30, 2008 at 11:14 PM
Please check whether you typed in properly. I really don't think it would be this crappy. :confused:
Boss, i was typing it.
I guess you are too fast:p
gary4gar
gary4gar #118
Nov 30, 2008 at 11:18 PM
Submitted while typing?? :p

Anyway just kidding carry on.
yaar, i was clicking on preview post button.
By mistake clicked on "POST reply" button:|
C
chandru.in #119
Nov 30, 2008 at 11:18 PM
Code:
public Welcome {
public static void main(String args[]) {

String[] greeting = new String[3]; 
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[3] = "and Gary Cornell";

for(int i = 0; i < greeting.length; i++)
System.out.println(greeting[i]);
}

}
this is a first program given in the book. the authors call Welcome program extremely simple.
Note: You missed "class" in the first line.

Ha ha ha. ROFLMAO. Thank God they did not introduce design patterns too in the same program. That's why I so love Head First series.
ravidawar
ravidawar #120
Dec 4, 2008 at 3:15 PM
i want to write a java program in which i need to call the command prompt and then run commands like ren , copy over files in a directory inside a for loop.can anyone suggest me how to do that.i tried with process and runtime but not able to achieve what i want.
C
chandru.in #121
Dec 4, 2008 at 6:54 PM
If such basic file operations are what you want to perform, have a look at the methods of the File class.

ren, dir etc are internal commands and hence Runtime.exec() will not work for them. For other external commands, Runtime.exec() will work fine.
ravidawar
ravidawar #122
Dec 5, 2008 at 8:34 PM
actually i have a folder in which i have around 100 files with name file.001, file.002 and so on.. so i need to write a java program to convert the file names to file001.rar,file002.rar and so on..thats why i need to run the commands..any other option to do that??
one thing i can do is to use a fileinputreader to read the file and then make a copy of that with a different name (all running under a for loop) but that would be a layman way of doing this thing.
B
Bandu #123
Dec 5, 2008 at 8:47 PM
^Is it only a one time rename that you have to do? If thats the case, you can do it using the ren command like option, or create a batch file to automate things. I don't see a need to write a program for such a trivial activity - unless you are looking for something that is platform independent, etc.

But, as Chandru suggested above, I don't think you will be able to do it.

If you are looking for a command based solution, then do try the following:

Code:
ren file.??? file.???.rar
That does not exactly give you the desired result, but is something you can use and enhance further to get rid of that extra dot. Heres what I did:

*i37.tinypic.com/2cz7gw0.jpg

Edit: Looking at the set of .nnn files that you have and your intended purpose to rename them as rar, I am guessing that you would like to extract the contents from a multispan rar archive. If that is the case, you need not bother about renaming and stuff, just right click and say extract here, or rename a single file from .001 to .r01 and try to extract using this file. You may also try forcefully opening one of the files in winrar and then using the Extract option.
C
chandru.in #124
Dec 5, 2008 at 10:32 PM
actually i have a folder in which i have around 100 files with name file.001, file.002 and so on.. so i need to write a java program to convert the file names to file001.rar,file002.rar and so on..thats why i need to run the commands..any other option to do that??
one thing i can do is to use a fileinputreader to read the file and then make a copy of that with a different name (all running under a for loop) but that would be a layman way of doing this thing.

If Bandhu's reply doesn't apply to you, read ahead.

Copying file by file is not only lay man way, it is also highly inefficient. If that is exactly the pattern for re-naming, you can try the code below.

Code:
package demo;

import java.io.File;

public class Main {

    public static void main(String[] args) {
        File directory = new File("/home/chandru/temp");

        for (int i = 1; i <= 2; i++) {
            String numberString = String.format("%03d", i);

            File originalFile = new File(directory, "file." + numberString);
            File targetFile = new File(directory, "file" + numberString
                    + ".rar");

            originalFile.renameTo(targetFile);
        }

        System.out.println("Rename complete.");
    }
}

Change the paths, loop condition and filename patterns as needed.
ravidawar
ravidawar #125
Dec 6, 2008 at 3:48 PM
Awsome Chandru , thanx a lot.
@Bandu if i do it by the ren command then i will have to do it 100 times.is there any way to run loop in a bat file ?
B
Bandu #126
Dec 6, 2008 at 7:04 PM
^Ravi. You don't need a loop. I've used wildcard thingy. If you notice, with one command, I renamed both my files and the same will work for any number of files.
Plasma_Snake
Dec 6, 2008 at 8:04 PM
Well for a change lets have this too ;) :D
Q. What is the difference between an Abstract class and Interface?
A. Terms are different ... Nothing more

Q. What is JFC ?
A. Jilebi, Fanta & Coffee

Q. Explain 2 tier and 3 -tier Architecture ?
A. Two wheelers like scooters will have 2 tyres and autorickshaws will have 3 tyres.

Q. I want to store more than 10 objects in a remote server ? Which methodology will follow ?
A. Send it through courier.

Q. Can I modify an object in CORBA ?
A. As you wish , I do not have any objections.

Q. How to communicate 2 threads each other ?
A. Non living things can't communicate.

Q. What is meant by flickering ?
A. Closing and opening of eyes.

Q. Explain RMI Architecture?
A. I am a computer professional not an architect student.

Q. What is the use of Servlets ?
A. In hotels, they can replace servers.

Q. What is the difference between Process and Threads ?
A. Threads are small ropes. Make a rope from threads is an example for process.

Q. When is update method called ?
A. Who is update method?

Q. What is JAR file ?
A. File that can be kept inside a jar.

Q. What is JINI ?
A. A ghost which was Aladdin's friend.

Q. How will you call an Applet from a Java Script?
A. I will give invitation.

Q. How you can know about drivers and database information ?
A. I will go and inquire in the bus dep to.

Q. What is serialization ?
A. Arranging one after the other from left to right.

Q. What is bean ? Where it can be used ?
A. A kind of vegetable. In kitchens for cooking they can be used.

Q. Write down how will you create a binary Tree ?
A. When we sow a binary seed , a binary tree will grow.

Q. What is the exact difference between Unicast and Multicast object ?
A. If in a society, if there is only one caste, then it is Unicast, else it is multicast
Faun
Faun #128
Dec 6, 2008 at 8:54 PM
lol
thewisecrab
Dec 6, 2008 at 11:52 PM
@Plasma Snake
LOL :D
Great one liners :lol:
Quiz_Master
Dec 7, 2008 at 1:40 AM
LOLOL Plasma Snake... Even after reading 1st few, I was thinking of REAL answers.
Though its a bit different of what is popular among us BCA students.

Q. What is serialization ?
A. Something Ekta Kapoor does.

Q. What is bean ? Where it can be used ?
A. Mr. Bean is a funnu show! It can be used to mock Sharma Sir . (Sharma sir in my college, he looks like Mr. Bean :p )

Q. When is update method called ?
A. Raat 12 baje baad. Local Calls free :p

There is more..like that related to VB, SQL and C++ :p


Its a "Forward as Email to all teachers" material. :p (and I already Fwd it :D )
Plasma_Snake
Dec 7, 2008 at 3:42 AM
I'm glad everybody likes it. BTW don't go spamming with this ;) :D Otherwise will have to issue a RPC via RMI to stop it all :D
D
Dec 12, 2008 at 1:55 PM
can any body suggest any good book on JMS java messaging services
C
chandru.in #133
Dec 12, 2008 at 4:08 PM
Sun's tutorial. *java.sun.com/javaee/5/docs/tutorial/doc/bncdq.html
nitish_mythology
Dec 30, 2008 at 5:49 PM
Here is my query.......

/* A sample class to clear basic concepts of inheritance....
@Author Nitish Upreti
*/

class parent
{
protected char var;
protected int var2;

public void setMe()
{
var='p';
var2=11;
}

}


class child extends parent
{

protected char var;
protected int vars;

public void setMe()
{
var='c';
vars=22;
}

}

public class god
{

private int x; //An inst var

public static void main(String args[])
{

//Trying to use the instant var in a static 'main' method

// x=12 GENERATES ERROR!! PROOVED!!


//parent p=new parent();
//child c=new child();


parent p2=new child();

//p.setMe();
//c.setMe();
p2.setMe();

//System.out.println(p.var);
//System.out.println(c.var);
System.out.println(p2.var);

}
}

The output is a blank line.... why?????????
It should either be 'p' or 'c' !!
C
chandru.in #135
Dec 30, 2008 at 7:38 PM
While inheriting and providing same name/signature for members in sub-class, methods are overriden, but variables are not.

Now when you invoke setMe() on p2, it invokes child object's setMe() (methods are overridden) thus setting child's var. When you print you are printing parents var (variables are not overridden) which is not yet set.
nitish_mythology
Dec 30, 2008 at 8:07 PM
So the output is supposed to be the default value of character i.e '/u0000' right?? is it a blank???
C
chandru.in #137
Dec 30, 2008 at 8:21 PM
Yes that is the default value. However, how it is displayed upon execution depends on the terminal and platform on which program executes.
nitish_mythology
Dec 31, 2008 at 9:53 AM
Hmm...
I am on Vector Linux! :)

Another Ques
what do we get from interfaces??? we could simply create an abstract class with all abstract methods n' all attributes public static and final...

That will be equivalent to creating an interface!!
C
chandru.in #139
Dec 31, 2008 at 10:06 AM
A class can implement multiple interfaces, but cannot extend multiple classes (even if abstract).
nitish_mythology
Dec 31, 2008 at 10:35 AM
I am aware of this fact...
I read tht interfaces save u from Deadly diamond of death..hows that??
U could have used multiple inheritance(if it was allowed) n used purely abstract classes...
WHy did java designers go 4 interfaces??
C
chandru.in #141
Dec 31, 2008 at 10:50 PM
If you have worked with multiple inheritance in C++, you'd know about ambiguities caused by allowing multiple inheritance when more than one base class have members with same name.

As you suggested, this can be prevented by ensuring all methods are abstract (which is what an interface does). Abstract classes by definition are allowed to have concrete methods and instance fields. Determining whether multiple inheritance is allowed on not only based on the fact that a class has all abstract methods and has only non instance variables will add to the complexity of the language and create more confusion.
A
ambika #142
Jan 2, 2009 at 8:23 AM
Can someone simply explain the different platforms .......editions of java ??
What are the career path with each of them ??
C
chandru.in #143
Jan 2, 2009 at 9:10 AM
Can someone simply explain the different platforms .......editions of java ??
What are the career path with each of them ??
Java Micro Edition - Smallest and meant for devices with limited processing power.
Java Standard Edition - The core language and APIs. Used for desktop apps mainly.
Java Enterprise Edition - The largest of the three. Built on top of Java SE and filled with more Enterprise APIs for things like EJBs, JMS, etc.

There are rich career opportunities in all three of them.
D
Jan 2, 2009 at 5:31 PM
there is another one JCP java card plateform
*java.sun.com/javacard/

used in set top box, mobile as sim, smart card etc
A
ambika #145
Jan 2, 2009 at 7:25 PM
Java Micro Edition - Smallest and meant for devices with limited processing power.
Java Standard Edition - The core language and APIs. Used for desktop apps mainly.
Java Enterprise Edition - The largest of the three. Built on top of Java SE and filled with more Enterprise APIs for things like EJBs, JMS, etc.

There are rich career opportunities in all three of them.

U had leaved one JCP??..........i know rich opportunities .....but i want simply some details .
C
chandru.in #146
Jan 2, 2009 at 7:55 PM
U had leaved one JCP??..........i know rich opportunities .....but i want simply some details .
Oh yeah, I had left out Java card. It is the smallest Java platform. Even smaller than Java ME.

Note: JCP as mentioned by Desi, is not to be confused with Java Community Process.

You can be desktop/enterprise/Mobile application developer. An application server admin. Admin of several other Java based middleware like message queues.
A
ambika #147
Jan 2, 2009 at 8:17 PM
Oh yeah, I had left out Java card. It is the smallest Java platform. Even smaller than Java ME.

Note: JCP as mentioned by Desi, is not to be confused with Java Community Process.

You can be desktop/enterprise/Mobile application developer. An application server admin. Admin of several other Java based middleware like message queues.

Its nice if u asign me a link for that ............that gives details.
C
chandru.in #148
Jan 2, 2009 at 9:10 PM
*java.sun.com/developer/onlineTraining/
K
Jan 4, 2009 at 9:18 PM
Hello man....
i m new to java....I want to upload an image along with other data like...
username,password ,email etc.....but when i click submit image gets uploaded but all other parameters are null.....and if i remove the image uploading option from the form...everything works fine....
i searched the net and found that jsp could not handle multipart requests nd we require some libraries for that....
jakarta commons...was one of them....i m so confused....did not understand a bit...
could u pls pls help me...
C
chandru.in #152
Jan 5, 2009 at 12:18 AM
i searched the net and found that jsp could not handle multipart requests nd we require some libraries for that....
JSP and Servlet can definitely handle multi-part request. But the catch is that writing code for parsing and using multi-part requests is tedious that it is better to get the job done with a library. Commons FileUpload is one such API. Commons FileUpload as a dependency needs Commons IO. Once you have both in your web-app's classpath, here is a sample code for uploading files using Commons FileUpload.

Main JSP
Code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"*www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Upload Page</title>
    </head>
    <body>
        <form action="UploadServlet" method="post" enctype="multipart/form-data">
            User Name:
            <input name="username" type="text" />
            <br>
            File to Upload: <input name="uploadFile" type="file"/>
            <br>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
Upload Handling Servlet
Code:
package demo;

public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            FileUpload upload = new FileUpload(factory);
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
            for (FileItem item : items)
                if (item.isFormField())
                    System.out.println(item.getFieldName() + " " + item.getString());
                else {
                    File uploadedFile = new File("/home/chandru/demo.png");
                    item.write(uploadedFile);
                }

            RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}
Note: Import Statements removed to keep code short. Add a simple result.jsp to show upload results.
S
sankha #153
Jan 9, 2009 at 12:26 PM
Thank you all for all such quality information. If I were to code a website where the database resides in another server, so can you just help me out for the inter-connectivity?








_________________________________
secure file deletion
Plasma_Snake
Jan 9, 2009 at 8:53 PM
Just another n00by question from me.
Is it possible to create a non-static class containing main like this:
public static class A
{
---code--
class B
{
void main(String Args[])
--code here--
}
}
If it is possible then program would be saved by which class's name, A or B ?
C
chandru.in #155
Jan 10, 2009 at 12:00 AM
Just another n00by question from me.
Is it possible to create a non-static class containing main like this:
public static class A
{
---code--
class B
{
void main(String Args[])
--code here--
}
}
If it is possible then program would be saved by which class's name, A or B ?
An outer class cannot be declared static. Inner classes can be. Here, B is an inner class.

Compiler will generate two class files in this case. A.class and A$B.class. But why didn't you pull out the compiler and try this?
Plasma_Snake
Jan 10, 2009 at 2:11 AM
One word, EXAMS! Have opted for J2ME, so will have to brush up my Core Java so watch out for a lot more stupid questions from me. ;)
Faun
Faun #157
Jan 10, 2009 at 5:32 AM
lol
K
Jan 10, 2009 at 11:49 PM
hello sir..
i have this jsp page ...which i want to use for image upload of a user...
i wannt to post the user no as id here along with the image file to another page where it will be saved in DB and on the server as well..

<%@ page language="java" import="java.sql.*,java.util.*,java.io.*" %>
<html>
<body bgcolor="#FFFFFF" leftmargin="0" rightmargin="0" marginheight="0" marginwidth="0">
<jsp:include page="header.jsp" flush="true" />
<%
String n = request.getParameter("id");
//out.println(n);
%>
<table align="center" border="0">
<form action="insertuserpic.jsp" method="post" enctype="multipart/form-data">
<tr><th>Select your picture :</th></tr>
<tr><td><input type="file" name="image"></td></tr>
<tr><td><input type="submit" name="submit" value="upload"></td></tr>
<input type="hidden" name="id" value="<%= n %>">
</form>
</table>
</body>
</html>

now insertuserpic.jsp is here:

<%@ page
import="java.sql.*,java.util.*,java.io.*" %>

<%

String n=request.getParameter("id");
out.println(n);

String contentType = request.getContentType();

out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
out.println("content length is"+formDataLength+"\n");

byte dataBytes[] = new byte[formDataLength];
out.println("databytes :"+dataBytes+"\n");

int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}

String file = new String(dataBytes);
out.println("file : "+file);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

//out.print(dataBytes);

int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//out.println(boundary);
int pos;
pos = file.indexOf("filename=\"");

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", pos) + 1;


int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

FileOutputStream fileOut = new FileOutputStream("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/project/userpics/" + saveFile);


//fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

out.println("File saved as " +saveFile);

}

file gets uploaded all well...but m not able to get the ID ...it comes null..
i have downloaded the com.oreilly.servlet.multipart library..
but i dont know how to use it..
could anyone just provide the exact code to get the id as well as the image...
i found the above code also on net....
can anyone help please...
C
chandru.in #159
Jan 11, 2009 at 12:08 AM
Haven't I already provided a working code above using Commons FileUpload? :mad: :mad: :mad:
Plasma_Snake
Jan 11, 2009 at 12:40 AM
Pingu getting Hot, need some ice here, pronto ;)
C
chandru.in #161
Jan 11, 2009 at 12:42 AM
Why will I answer same question again within the same page? If he can't read others' reply why post? :D
D
Jan 12, 2009 at 10:08 AM
does any body have any tutorial regarding ajax push? using comet in java?
C
chandru.in #163
Jan 16, 2009 at 11:36 PM
I have never used Comet, but if you are using JSF by any chance, both Richfaces and IceFaces provide push capabilities. Icefaces uses long living connections while Richfaces uses a lightweight polling mechanism to simulate a push.
G
gopi_vbboy #164
Jan 17, 2009 at 12:05 AM
Is it possible to run sony erricson java games (jar) in nokia
furious_gamer
Jan 17, 2009 at 9:50 AM
No way.. Nokia was only able to play the sis files for games
Plasma_Snake
Jan 17, 2009 at 11:59 AM
^^ SO wrong mate, .jar games or Java games can be played on any Java enabled phone, that's the beauty of it. I myself played the Gameloft's Chess game on my E51, a S60v3 phone, which I earlier used to play on my 5200, a S40v3 phone. I haven't tried playing same Java game on any SE phone but I'm pretty sure that it will work.
G
gopi_vbboy #167
Jan 17, 2009 at 1:33 PM
actaully i have a bluetooth game-Planet riders which im unable to play with ma freinds havinf nokia xpress music phone n n73.....but working on sony phones perfectly....

in nokia n73 after installing game from jar file...when i open i doesnt do anything...jus stand atill..doesn hang but sometimes say apllication error....n doesn work at all
Plasma_Snake
Jan 17, 2009 at 2:18 PM
What's ur phone's firmware? Update it and see if solves the problem.
S
silent008 #169
Jan 23, 2009 at 3:00 PM
Consider the following structure

class A{
//something valid
}
class B
{
int id;
A abc[];
b()
{abc=new A[10];}
}

let A temp=new A();
and is initialized
and
B xyz[]=new B[10];
now when i try this

for(i=0;i<10;i++)
for(j=0;j<10;j++)
xyz.abc[j]=temp;

I get java.lang.nullpointer exception


Please Help me!!!! I am new to java
B
Bandu #170
Jan 23, 2009 at 4:06 PM
^Your xyz array is only "declared" to be of type B and size 10. You haven't initialized it yet. So, when you try to use it, you face a nullpointer exception. I guess at the very first iteration of the loop (when i = 0). Assign 10 B objects to each of the xyz array elements and you should be fine.

Code:
for(int i=0;i<10;i++)
    for(int j=0;j<10;j++)
    {
        xyz[i] = new B();
        xyz[i].abc[j]=temp;
    }
S
silent008 #171
Jan 23, 2009 at 11:28 PM
^Your xyz array is only "declared" to be of type B and size 10. You haven't initialized it yet. So, when you try to use it, you face a nullpointer exception. I guess at the very first iteration of the loop (when i = 0). Assign 10 B objects to each of the xyz array elements and you should be fine.

Code:
for(int i=0;i<10;i++)
    for(int j=0;j<10;j++)
    {
        xyz[i] = new B();
        xyz[i].abc[j]=temp;
    }
Thanks Bandu,
That worked

And sorry for the noobie question. As I am new to Java I got confused. I thought B xyz[]=new B[10] is enough to initialize

Thanks Again!!!!
B
Bandu #172
Jan 23, 2009 at 11:40 PM
^No probs. Glad I could help. You really don't need to be sorry n all that.
C
c2tarun #173
Jan 25, 2009 at 10:51 AM
i just gone through wrapper classes
Integer, Byte, and etc are wrapper classes.
they do have some functions and there objects can be created simply like other classes...

WHAT I DONT UNDERSTAND ABOUT KEYWORD 'int' IS WHAT XACTLY IS THE MEANING, USE AND ITS RELATION TO INTEGER CLASS....
THANK YOU
vamsi360
vamsi360 #174
Jan 25, 2009 at 12:44 PM
i just gone through wrapper classes
Integer, Byte, and etc are wrapper classes.
they do have some functions and there objects can be created simply like other classes...

WHAT I DONT UNDERSTAND ABOUT KEYWORD 'int' IS WHAT XACTLY IS THE MEANING, USE AND ITS RELATION TO INTEGER CLASS....
please reply and if u do have any notes about this plz send it to me at c2tarun@gmail.col
THANK YOU

int is a primitive data type and Integer is a class i Java. All numeric primitive types are sub in Integer class. So if you are using Generics there you got to use Integer to create a generic variable than to use int type which gives an error.

For even detailed explanation read Generics chapter in Complete Reference book.

As I have learned in this forum.......DONT post your email id publicly , avoid spam.
C
c2tarun #175
Jan 26, 2009 at 5:25 PM
THANX this helps me a lot.....
i will read more from ur recommended chapter
C
c2tarun #176
Jan 28, 2009 at 4:58 PM
hi everybody
can anyone plz tell me is there a function of method in java to clear console screen.
like 'clrscr()' in c++;
C
chandru.in #177
Jan 28, 2009 at 5:36 PM
clrscr() is a proprietary Turbo C function. It is not even a standard C/C++ function.

Also, the use of Java for developing pure console application is very rare. Java rules the middleware space and quite popular in enterprise web and desktop applications. These rarely need console output.
nitish_mythology
Feb 16, 2009 at 6:45 PM
The Code prints diff hashCodes for the two objects..
Still the objects are reported to be equal!! Why is that so??

class Hs
{

int x;

public Hs()
{
x=11;
}


public boolean equals (Object o)
{
Hs rf=(Hs) o;

if(this.x==rf.x)
return true;
else
return false;
}

}

class TryMe
{
public static void main(String args[])
{
TryMe tm=new TryMe();
TryMe tm2=new TryMe();


System.out.println(tm.hashCode());
System.out.println(tm2.hashCode());

//Here two hashcodes were shown diff
if(tm.equals(tm2))
System.out.println("Equal");
else
System.out.println("NOT EQUAL");

}

}
B
Bandu #180
Feb 17, 2009 at 12:56 AM
Just verified. NOT EQUAL.
vamsi360
vamsi360 #181
Feb 19, 2009 at 2:33 PM
Implement Round Robin algorithm in Java with recursion ..
thewisecrab
Feb 20, 2009 at 7:02 PM
Could someone explain the loop structure in an array? (both single and double dimensional)
Even link would do (or a page no./chapter no. on Shildt's Java Reference book :|)
mailraj_9999
Feb 21, 2009 at 11:48 AM
I have one PROBLEM ! ! !

Ya I can combine two c files together.

But now i want to combine Java and C files togther

So How can i do that?

Can anyone Help Me?

contact

yahoo: mailraj_9999@yahoo.com
A
ambika #184
Feb 24, 2009 at 11:37 PM
A really good thread i encounter in programming subforum for C and C++ started by Gigacore .....
Can any one provide me similar thread for java .....or a external links .....
I am really new to java .
Please help me guys .
vamsi360
vamsi360 #185
Feb 25, 2009 at 1:06 PM
Could someone explain the loop structure in an array? (both single and double dimensional)
Even link would do (or a page no./chapter no. on Shildt's Java Reference book :|)

loop structure ? please be more clear

Using for each loop :

Code:
int x[][]=new int[4][4];
for(int i: x[]) {
   for(int j :x) {
        ------
        ------
   }
}
S
Mar 5, 2009 at 11:22 AM
the modified program is........
import java.io.*;
public class FileOps {
public static void main(String args[])throws IOException
{
File file = new File(args[0]);
try
{
BufferedReader in = new BufferedReader(new

FileReader(file));
String s;
s = in.readLine();
while(s!=null)
{
System.out.println("Read " + s);
s = in.readLine();
}
in.close();
}
catch(FileNotFoundException e1)
{
System.err.println("File Not Found" + file);
}
catch(IOException e2)
{
e2.printStackTrace();
}
}
}
A
Mar 10, 2009 at 11:32 AM
I want to control a 16 bit program's input output through java. i.e. the actual processing is to be done by the 16 bit program itself, but its input and output are to be controlled by the gui developed in java. can it be done? if yes how? please provide an example if possible.
thewisecrab
Mar 11, 2009 at 6:43 PM
Could someone explain this line to me?
The body of a "while" loop can be empty. This is because the null statement, consisting of a semicolon, is valid in Java.
How can a while loop not have a body? I couldnt get that. :|
Liverpool_fan
Mar 11, 2009 at 7:08 PM
^ ^ ^
(Assuming the while loop in Java is similar to C/C++)

You generally have while loop like this:
while(condition)
{
//your code
}

But without a body you can as well:
while(condition);

See the semicolon in bold, it acts as the null character and the while loop doesn't require a body (i.e. the single line below while loop or the code in braces)
You should however wait for confirmation from Java experts whether I'm right or wrong.
thewisecrab
Mar 11, 2009 at 7:25 PM
^ ^ ^
(Assuming the while loop in Java is similar to C/C++)

You generally have while loop like this:
while(condition)
{
//your code
}

But without a body you can as well:
while(condition);

See the semicolon in bold, it acts as the null character and the while loop doesn't require a body (i.e. the single line below while loop or the code in braces)
You should however wait for confirmation from Java experts whether I'm right or wrong.
Agreed
But if there is nothing in the body, what will be executed in the loop?
Or more importantly, how can the loop exist without the body?
vamsi360
vamsi360 #191
Mar 11, 2009 at 8:00 PM
Could someone explain this line to me?

How can a while loop not have a body? I couldnt get that. :|

it means that body for a loop is not necessary. The loop will iterate itself for the specified no of times without executing any statements. These are mostly used for infinite loops, time delay loops.
Code:
//infinite for loop
for( ; ; );
A
Mar 11, 2009 at 8:25 PM
now, i successfully executed programs as i wanted to, but if try to execute 16 bit programs it gives error as 'error in setting up environment' in message box. What does it mean? how can this error be overcome? I didn't find conclusive answer to this after googling. so please help me..
Liverpool_fan
Mar 11, 2009 at 8:29 PM
Agreed
But if there is nothing in the body, what will be executed in the loop?
Or more importantly, how can the loop exist without the body?
Well actually "nothing" is executed for each iteration of the loop...:mrgreen:
No I am not joking...
As for the use...I don't really know..The post above mine suggests something worthwhile but I'll rather use a library function for time delay...
I guess it's importance is iits semantics in these languages rather than any functionality...
P
PoWeR #194
Mar 11, 2009 at 8:49 PM
wht is autoboxing & unboxing???
M
mrintech #195
Mar 11, 2009 at 9:29 PM
wht is autoboxing & unboxing???
Visit following Links:

* *tclab.kaist.ac.kr/~otfried/cs206/notes/autoboxing.pdf

* *java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

* *www.eclipse.org/aspectj/doc/released/adk15notebook/autoboxing.html

* *www.google.com/search?hl=en&num=10...d=1&q=what+is+auto+boxing+&+unboxing?&spell=1

;)
S
Mar 12, 2009 at 5:29 PM
DefaultTableModel doubt

In a DefaultTableModel after doing an addrow …how to make certain texts within the rows BOLD?
nitish_mythology
Mar 19, 2009 at 9:23 AM
Earlier I had posted a ques regarding hashCode n' equals..
But the code was incorrect...
So here is the correct code n the question follows...

[/QUOTE]
/* Testing some ambiguous equals n' hashcode concepts
@Author Nitish Upreti
*/

class Car
{

private String model;
private char type;
private int carno; //The core attribute for deciding if two car objects are equal

public Car()
{
model="Merc";
type='S';
carno=95361;
}

public Car(int no)
{
model="Merc";
type='M';
carno=95361;
}

public boolean equals(Object o)
{
Car c=new Car();

if(o instanceof Car)
c=(Car)o;

/*
System.out.println("c hashCode()--- "+c.hashCode());
System.out.println("Current Object's hashCode()--- "+this.hashCode());
*/

if(c.carno==this.carno)
return true;
else
return false;
}

public int hashcode()
{
return type;
}

public static void main(String args[])
{

Car c=new Car();
Car c2=new Car(13458);

System.out.println("In main() c hashCode()--- "+c.hashCode());
System.out.println("In main() c hashCode()--- "+c2.hashCode());

if(c.equals(c2))
System.out.println("Same Car---Number is same dude :p");
else
System.out.println("Different Cars----Nameplate check kar :p");

}
}

[/QUOTE]

The hashCodes() are reported to b unequal...still the objects are equals!!
Why is it so??
I read in books that for two objects to b equal they must be logically equal n' also have the same hashcode
S
Mar 23, 2009 at 6:11 PM
Re: DefaultTableModel doubt

In a DefaultTableModel after doing an addrow …how to make certain texts within the rows BOLD?
I need to make only certain texts within a cell to be bold
Example:
If the text at 'x'th row and 'y'th column contains the word "abc def" then make ONLY the letters "abc def" in that cell BOLD rest all will remain default
M
multicoder #199
Mar 27, 2009 at 11:55 AM
hi,
I have installed jdek6 and i was quite happy with it,after few days i installed netbeans latest version!And then the problem started.I could only compile my files when using with command prompt and could not run.But could run applets.
I tried alot and then later I to solve this i unstalled netbeans and uninstalled jdk too.
But now nothing is giving me the result.I can only compile the file .when trying to run the file I am getting class not found exception at java.lang.classloader, at ...,at .. an d so on...
Even whn applets running show in their status window 'Applet not started'.
What is the reason behind this.Please help me to sort out this.
Thnaks.
vamsi360
vamsi360 #200
Mar 28, 2009 at 6:21 PM
hi,
I have installed jdek6 and i was quite happy with it,after few days i installed netbeans latest version!And then the problem started.I could only compile my files when using with command prompt and could not run.But could run applets.
I tried alot and then later I to solve this i unstalled netbeans and uninstalled jdk too.
But now nothing is giving me the result.I can only compile the file .when trying to run the file I am getting class not found exception at java.lang.classloader, at ...,at .. an d so on...
Even whn applets running show in their status window 'Applet not started'.
What is the reason behind this.Please help me to sort out this.
Thnaks.
remove multiple path variables to jdks and update the only path variable to newer jdk 1.6 update version
S
Mar 31, 2009 at 6:50 PM
Java Queries Here.. Regular expression

String str0 = "ABC def: xyz12-1/2,2/1,1/3"
String str1 = "AAA def: xyz12-1/2,2/1,1/3"
String str2 = "ABC def: xyz12-,2/1,1/3"
String str3 = "ABC def: xyz12-,1/0,2/1,1/3"

Now i need to check if the String contains "ABC def:<anything>2/1<anything>"
Only str0,str2,str3 satisfies this condition

What should be the regular expression for this?
Y
Apr 1, 2009 at 11:19 PM
Can any body help me regarding learning netbeans plz its imp
C
c2tarun #203
Apr 4, 2009 at 6:14 PM
i just studied the chapter on streams and buffer but not able to visualize them correctly.....

plz help me

either explain it here (that will be beneficial for all new comers)
or give me a link for it
thanx in advance
Champachikla
Apr 6, 2009 at 8:34 PM
great thread,
i really appriciate this.
Plasma_Snake
Apr 6, 2009 at 9:14 PM
Hi, my first post here after a long time and more will come as I've started J2ME recently, so watch out, coz some of my questions will be pure mindphuck coz of their stupidity! :D
For starters, what all tools will I need for J2ME development, gimme a detailed lowdown.:cool:
A
Apr 10, 2009 at 7:06 AM
I want to change the coffee cup java icon from Frame....I want my own icon over there....
How can I do that?
Plz help me....
After a lot of search in google I got the followimg code...But it is not changing the icon at the titlebar of the frame. The samr icon is still there...Plz make necessary correction to have desired output.

import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Image;
public class Test
{
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("D:/icon")));
frame.pack();
frame.setVisible(true);
}
}
-----------------------------------------
Posted again:
-----------------------------------------
I am using Java 6.
I want to access the build-in Class and Packages of Java. But going to this path
(C:\Program Files\Java\jdk1.6.0\javax\swing ) I saw only some text file and that is written in some other font. I can not understand those.
Please help me out.
vamsi360
vamsi360 #207
Apr 13, 2009 at 8:36 PM
i just studied the chapter on streams and buffer but not able to visualize them correctly.....

plz help me

either explain it here (that will be beneficial for all new comers)
or give me a link for it
thanx in advance

read Complete Reference or Thinking in Java man. read completely and see whether you understand or not..
B
Bandu #208
Apr 23, 2009 at 9:31 PM
I want to change the coffee cup java icon from Frame....I want my own icon over there....
How can I do that?
Plz help me....
After a lot of search in google I got the followimg code...But it is not changing the icon at the titlebar of the frame. The samr icon is still there...Plz make necessary correction to have desired output.

You cannot have absolute path in your code (ex. D:\xyz). Add the desired directory in the classpath and use the resource (your image in this case) directly without any path references; or have your image file in the same directory (or a sub-directory) as your programs directory and access it accordingly. Moreover, you have to specify the correct resource name including the file extension.

I could make your program work with slight modifications as follows:
Code:
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Image;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Test tt = new Test();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try
        {
            frame.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(tt.getClass().getResource("icon-mercedes.png")));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        frame.pack();
        frame.setVisible(true);
    }
}

I had the icon-mercedes.png file in the same directory where the Test.class was.
Hope this helps.
S
Saroja Jim #210
Apr 25, 2009 at 10:40 PM
I am facing a problem, when i have created 4 objects with the same name then tried it to use in other class then it will not accessible there. So it is possible to set object null?

MLM Leads
vamsi360
vamsi360 #211
May 5, 2009 at 11:53 PM
can anyone please give me the link to netbeans IDE 6.5 book so that I could easily develop my swing apps rather than coding in Notepad++
Nawab
Nawab #212
May 16, 2009 at 2:38 PM
i dont think direct link will be allowed here
btw
alternatively search "Netbeans 6.5" @ Google and 1st link will have sub-links including 1 for download and install Netbeans & install
you could also try Eclipse's Java IDE its lightweight n better :razz:
adatapost
adatapost #213
Jul 5, 2009 at 1:10 PM
I face a lot of issues while i m running java when i started to learn it... And i think the same issues will still alive.. If anyone find such kinda issue then please post it here instead of creating a new thread..

Yes this thread is dedicatedto Java(if u like J2EE toooo....:D)

So please drop ur queries here...

I think you have different views or misconception on java & jJ2EE.
P
pravesh250 #214
Jul 14, 2009 at 11:07 PM
Pls help
I have a java code as follows i would like to embed it in an HTML file can u pls explain how to do.
JAVA code


import java.io.*;
public class angle{
public static void main(String [] args) throws IOException{
BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
float a;
double s;
int c;
System.out.println("Hai welcome to the trignometric calculator");
System.out.println("Select from the following options");
System.out.println("1: Sine");
System.out.println("2: Cosine");
System.out.println("3: Tan");
System.out.println("4: Cosine");
System.out.println("5: Cosec");
System.out.println("6: Cot");
System.out.println("Enter an option: ");
System.out.flush();
c=Integer.parseInt (stdin.readLine());

switch ( c ){
case 1 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Sine "+a+" = " +(Math.sin(s)));
break;
}
case 2 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cosine "+a+" = " +(Math.cos(s)));
break;
}
case 3 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Tan "+a+" = " +(Math.tan(s)));
break;
}
case 4: {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cosec "+a+" = " +(1/(Math.sin(s))));
break;
}
case 5 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Sec "+a+" = " +(1/(Math.cos(s))));
break;
}
case 6 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cot "+a+" = " +(1/(Math.tan(s))));
break;
}
default : System.out.println("Ok good bye..............");
break;
}
}
}



Please help me in this matter
C
charybdis #215
Aug 25, 2009 at 12:59 AM
has anybody played with weblogic?
J
Sep 30, 2009 at 8:50 AM
please example for me?
nithinks
nithinks #217
Oct 6, 2009 at 1:20 PM
Can you explain what exactly you are planning to do?
I have developed a similar application using JavaBeans / JSP

May be I can give some inputs
Plasma_Snake
Oct 7, 2009 at 4:53 PM
I want the Javascript code to shutdown the system. Can anybody gimme? :lol:
nithinks
nithinks #219
Oct 8, 2009 at 4:49 PM
I want the Javascript code to shutdown the system. Can anybody gimme? :lol:

Check this

*livedocs.adobe.com/director/mx2004...X_2004_Documentation&file=07_me412.htm#191023
S
sp66619 #220
Oct 8, 2009 at 9:03 PM
Check this
i want to learn java script. so u can give better java e books on my id.and give me advise for learn java. :lol:
*livedocs.adobe.com/director/mx2004...X_2004_Documentation&file=07_me412.htm#191023
P
petricnout #221
Oct 22, 2009 at 2:33 PM
Hey Rajkumar.
Myself Petricnout and I read your entire posting. If i have any quiries about java thread, I will definitely paste that quiries here. Visit regularly on this website, give suggestions, give your future preferences, etc. to us. Anyways thanks for posting it .Stay connected.
sxyadii
sxyadii #222
Oct 23, 2009 at 10:18 AM
Swing Demo
----------------


Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class swingdemo extends Frame implements ActionListener
{
	JFrame frm;
	JMenuBar mb;
	JMenu mFile,mTransaction;
	JMenuItem itmLogin,itmQuitApp,itmCashDeposit,itmChequeDeposit;
	JLabel lblName;
	JTextField txtName;
	public swingdemo()
	{
		frm = new JFrame("Bank Management System");
		frm.setLayout(null);	
		frm.setSize(600,500);
		frm.setVisible(true);

		//Menu Coding
		mb = new JMenuBar();
		mFile = new JMenu("File");
		itmLogin = new JMenuItem("Login");
		itmQuitApp = new JMenuItem("Quit Application");
		mFile.add(itmLogin);
		mFile.add(itmQuitApp);

		mTransaction = new JMenu("Transaction");
		itmCashDeposit = new JMenuItem("Cash Deposit");
		itmChequeDeposit = new JMenuItem("Cheque Deposit");
		mTransaction.add(itmCashDeposit);
		mTransaction.add(itmChequeDeposit);

		itmCashDeposit.addActionListener(this);

		mb.add(mFile);
		mb.add(mTransaction);
		frm.setJMenuBar(mb);

		//Label
		lblName = new JLabel("Name");
		lblName.setBounds(70,20,200,50);
		frm.add(lblName);

		txtName = new JTextField(25);
		txtName.setBounds(140,20,150,20);
		frm.add(txtName);
		
		
	}
	
	public void actionPerformed(ActionEvent e)
	{
		Object o = e.getSource();
		if(o==itmCashDeposit)
		{
			
		}
	}

	public static void main(String args[])
	{

		swingdemo s = new swingdemo();
	}
}
-----------------------------------------
Posted again:
-----------------------------------------
Simple Frame

Code:
import javax.swing.*;

class SimpleFrame extends JFrame
{
	public SimpleFrame()
	{
		this.setSize(200,200);
		this.setLocation(200,200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public void showIt()
	{
		this.setVisible(true);
	}
	
	public void showIt(String title)
	{
		this.setTitle(title);
		this.setVisible(true);
	}
	public void showIt(String title,int x,int y)
	{
		this.setTitle(title);
		this.setLocation(x,y);
		this.setVisible(true);
	}
	public static void main(String args[])
	{
		SimpleFrame f = new SimpleFrame();
		f.showIt();
	}
}
layzee
layzee #223
Nov 28, 2009 at 10:07 AM
You cannot have absolute path in your code (ex. D:\xyz). Add the desired directory in the classpath and use the resource (your image in this case) directly without any path references; or have your image file in the same directory (or a sub-directory) as your programs directory and access it accordingly. Moreover, you have to specify the correct resource name including the file extension.

I could make your program work with slight modifications as follows:
Code:
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Image;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Test tt = new Test();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try
        {
            frame.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(tt.getClass().getResource("icon-mercedes.png")));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        frame.pack();
        frame.setVisible(true);
    }
}

I had the icon-mercedes.png file in the same directory where the Test.class was.
Hope this helps.

This solution should work fine...
There is no other way I guess than to use the setIconImage function.
To use the icon you must place the image in the same path as that of the class.
Nawab
Nawab #224
Dec 17, 2009 at 6:57 PM
look to embed this code in HTML you will have to develop a JSP WebPage instead of HTML, or you could use this as a Servlet for your WebPagic Code Logic
Pls help
I have a java code as follows i would like to embed it in an HTML file can u pls explain how to do.
JAVA code


import java.io.*;
public class angle{
public static void main(String [] args) throws IOException{
BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
float a;
double s;
int c;
System.out.println("Hai welcome to the trignometric calculator");
System.out.println("Select from the following options");
System.out.println("1: Sine");
System.out.println("2: Cosine");
System.out.println("3: Tan");
System.out.println("4: Cosine");
System.out.println("5: Cosec");
System.out.println("6: Cot");
System.out.println("Enter an option: ");
System.out.flush();
c=Integer.parseInt (stdin.readLine());

switch ( c ){
case 1 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Sine "+a+" = " +(Math.sin(s)));
break;
}
case 2 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cosine "+a+" = " +(Math.cos(s)));
break;
}
case 3 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Tan "+a+" = " +(Math.tan(s)));
break;
}
case 4: {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cosec "+a+" = " +(1/(Math.sin(s))));
break;
}
case 5 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Sec "+a+" = " +(1/(Math.cos(s))));
break;
}
case 6 : {
System.out.println("Enter an angle in degrees : ");
a = Float.parseFloat(stdin.readLine());
s = Math.toRadians(a);
System.out.println("Cot "+a+" = " +(1/(Math.tan(s))));
break;
}
default : System.out.println("Ok good bye..............");
break;
}
}
}



Please help me in this matter
layzee
layzee #225
Jan 1, 2010 at 10:14 PM
look to embed this code in HTML you will have to develop a JSP WebPage instead of HTML, or you could use this as a Servlet for your WebPagic Code Logic

You can create an applet and embed it in your web page using the APPLET tag
A
alton #226
Jan 5, 2010 at 2:48 PM
can anyone please give me the link to netbeans IDE 6.5 book so that I could easily develop my swing apps rather than coding in Notepad++


For netbeans you should try
netbeans. org as well
java2s. com for java based examples.
C
c2tarun #227
Feb 16, 2010 at 4:14 PM
Help for my project!!!

hi folks
i want to make a complete windows log recorder in JAVA as my BTech mini project.
The only problem i am facing is how to record clicks and activities on windows using JAVA Listeners.
PLEASE HELP ME OUT!!!!
If possible recommend me any book, or link for theories and concepts.
THANX IN ADVANCE
N
Mar 12, 2010 at 1:33 PM
Need some help here, this is my HTML source-code (this is the code from April-2009 digit fast track)

<html>
<head>
<title>My Favorite Movies</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" language="javaScript">
function addmovie(nameid,listid){
moviename=document.getElementById('nameid').value;
document.getElementById('nameid').value='';
document.getElementById('listid').innerHTML +='<li><a href="#">'+moviename+'</a></li>';
}
</script>
<noscript>
<p> scripting is not supported </p>
</noscript>
</head>
<body>
<h1>A List of my Favorite Movies</h1>
<h2>Movie Series:</h2>
<ul id="sermovies">
<li><a href="#">The Matrix Series</a></li>
<li><a href="#">The Lord of the Rings Series</a></li>
<li><a href="#">Star Wars Series</a></li>
</ul>
<input id="newseries" type="text" />
<input type="button" onclick="addmovie('newseries','sermovies')" value="Add Series"/>
<h2>Individual Movies:</h2>
<ul id="indmovies">
<li><a href="#">Memento</a></li>
<li><a href="#">Batman Begins</a></li>
<li><a href="#">The Dark Knight</a></li>
<li><a href="#">Gattaca</a></li>
<li><a href="#">Shawshank Redemption</a></li>
</ul>
<input id="newmovie" type="text" />
<input type="button" onclick="addmovie('newmovie','indmovies')" value="Add Movie"/>
<p></p>
<div class="footer">
<a href="*www.google.com/">To get your other favorite movies search here </a>
</div>
</body>
</html>

here i am trying add movie name to innetHTML by clicking on button, but that is not happing.
prttal
prttal #229
Jun 9, 2010 at 12:11 PM
I was thinking of creating a new thread for my java problem when I found this. Now can anybody tell me how do I get the mouse pointer's position(x,y) even after it has gone out of the frame. What class does it use? It should be something like this:

import javax.swing.*;

public class abc
{
public static void main(string arg[])
{
JFrame f=new JFrame("Mouse");
JPanel p=new JPanel();
JLabel l=new JLabel(Name_of_variable_storing _the_value of_xy_coordinates_here);
}
}
Garbage
Garbage #230
Jun 9, 2010 at 12:42 PM
hi folks
i want to make a complete windows log recorder in JAVA as my BTech mini project.
The only problem i am facing is how to record clicks and activities on windows using JAVA Listeners.
PLEASE HELP ME OUT!!!!
If possible recommend me any book, or link for theories and concepts.
THANX IN ADVANCE

I was thinking of creating a new thread for my java problem when I found this. Now can anybody tell me how do I get the mouse pointer's position(x,y) even after it has gone out of the frame. What class does it use? It should be something like this:

import javax.swing.*;

public class abc
{
public static void main(string arg[])
{
JFrame f=new JFrame("Mouse");
JPanel p=new JPanel();
JLabel l=new JLabel(Name_of_variable_storing _the_value of_xy_coordinates_here);
}
}

Please have a look at Robot class.
G
gopi_vbboy #231
Jun 9, 2010 at 4:53 PM
i actually want to actually extract data of all results from a webpage

its a php page it ask to enter roll no and i get a result page with Name,Subject and marks

i have to read the contents of the online page and store in file...
in this way i have to do 60 times for all students


how can i automate this task...like i jus give range of roll no ...it shud give a print data collected with the range of result...


thanks in advance

is it possible to do with java

---------- Post added at 03:35 PM ---------- Previous post was at 03:22 PM ----------

---------


one more doubt


how can i distrube a java application i made....do i have to ask the user to everytime run java filename.class everytime?

jar is a solution....but how to make a exe

---------- Post added at 04:53 PM ---------- Previous post was at 03:35 PM ----------

any idea pls?
Faun
Faun #232
Jun 9, 2010 at 5:09 PM
^^launch4j
M
Jun 18, 2010 at 7:09 PM
Hi Plasma_Snake,
I am not quite sure about your solution. But i will tell what i think.

File file = new File(args[0]);
Because of this statement u should pass the file name or file name with path during running
i.e,
java FileOps c:\1.txt
u can do it manually by running the same class file at jdk bin folder.It worked for me.
i think there should be some option in netbeans for this. I dont know about it.


or pass a string (file name)as an argument like this
String s1;
read the string (file name)from terminal.
pass it as
File file = new File("s1");
Garbage
Garbage #234
Jun 18, 2010 at 7:40 PM
@manu somasekhar

You might be interested in reading this and/or this before posting. :|
G
gopi_vbboy #235
Jun 18, 2010 at 9:43 PM
i actually want to actually extract data of all results from a webpage

its a php page it ask to enter roll no and i get a result page with Name,Subject and marks

i have to read the contents of the online page and store in file...
in this way i have to do 60 times for all students


how can i automate this task...like i jus give range of roll no ...it shud give a print data collected with the range of result...
Garbage
Garbage #236
Jun 19, 2010 at 10:07 PM
@gopi_vbboy
Its Java queries thread. If you have a problem which needs a PHP solution, please create another thread.
furious_gamer
Jun 20, 2010 at 11:22 AM
@gopi_vbboy
So that means you can access that page using a Web Service. Does they gave access to that?
Then just use the URL class to pass the input data to that php page and fetch the whole page as the string and parse it. I hope i understand what you said and gave the solution accordingly.
G
gopi_vbboy #238
Jun 20, 2010 at 1:42 PM
the page doesnt support GET method of posting....

---------- Post added at 01:42 PM ---------- Previous post was at 01:40 PM ----------

@gopi_vbboy
Its Java queries thread. If you have a problem which needs a PHP solution, please create another thread.

ok

atleast tell me wat to use to do such web page automation

php or python?

---------- Post added at 01:42 PM ---------- Previous post was at 01:42 PM ----------

also i have to pase a webpage....
Garbage
Garbage #239
Jun 20, 2010 at 1:46 PM
@gopi_vbboy

You can do it in Java too. Use the URL class to make the connection to the URL, pass the data.
Take the response in a String (StringBuffer) and then parse it.
G
gopi_vbboy #240
Jun 21, 2010 at 9:15 AM
^^ k thanks...is there a HTML parser in java
furious_gamer
Jun 21, 2010 at 12:14 PM
@gopi_vbboy

You can do it in Java too. Use the URL class to make the connection to the URL, pass the data.
Take the response in a String (StringBuffer) and then parse it.

Exactly what i said.....

gopi_vbboy said:
ok

atleast tell me wat to use to do such web page automation

php or python?

You can do that in Java too, and read the links given by Garbage, if you want to do it in PHP means, you can.
S
SUNANDAN #243
Jun 21, 2010 at 12:26 PM
Check this code out:
Code:
import java.io.*;
 
public class FileOps {
public static void main(String args[])
{
    File file = new File(args[0]);
    try
    {
        BufferedReader in = new BufferedReader(new FileReader(file));
        String s;
        s = in.readLine();
        while(s!=null)
        {
            System.out.println("Read " + s);
            s = in.readLine();
        }
        in.close();
    }
    catch(FileNotFoundException e1)
    {
        System.err.println("File Not Found" + file);
    }
    catch(IOException e2)
    {
        e2.printStackTrace();
    }
}
}
Now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FileOps.main(FileOps.java:13)
Java Result: 1
"
What's the solution? :confused:
create a new func and call it from main,then it will solve.
mailraj_9999
Jun 29, 2010 at 9:06 PM
Regarding SCJP

Hi

I am preparing for SCJP certification 6
I want the demo exam CD can anyone help?
furious_gamer
Jun 30, 2010 at 10:35 AM
Re: Regarding SCJP

^^
Go get it in a certified SCJP Centres...... :D
vineetrok
vineetrok #246
Jul 22, 2010 at 9:37 PM
I am a newebie in javascript, need some help in the following program!
<html>
<head>
<script type="text/javascript">
function timedText()
{
var i=1000;

for(i=1000;i<=20000;i=i+1000){
var t1=setTimeout("document.getElementById('txt').value = i",i);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed text!" onClick="timedText()">
<input type="text" id="txt">
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>


This is supposed to display time past(in seconds) in a textbox but It's not working.........can someone help??
Garbage
Garbage #247
Jul 22, 2010 at 11:56 PM
Though its not a JavaScript thread, here is the solution.
Code:
<html>
<head>
	<script type="text/javascript">
		function timedText(){
			var i=1000;
			for(i=1000;i<=20000;i=i+1000){
				setTimeout("document.getElementById('txt').value="+i,i);
			}
		}
	</script>
</head>
<body>
	<form>
		<input type="button" value="Display timed text!" onClick="timedText()">
		<input type="text" id="txt">
	</form>
	<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>

Please post the question in right section from next time.
A_n_k_i_t
A_n_k_i_t #248
Jul 23, 2010 at 12:15 AM
I am a newebie in javascript, need some help in the following program!
<html>
<head>
<script type="text/javascript">
function timedText()
{
var i=1000;

for(i=1000;i<=20000;i=i+1000){
var t1=setTimeout("document.getElementById('txt').value = i",i);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed text!" onClick="timedText()">
<input type="text" id="txt">
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>


This is supposed to display time past(in seconds) in a textbox but It's not working.........can someone help??



Here is the modified code

<html>
<head>
<script type="text/javascript">
function timedText()
{
var i;

for(i=1000;i<=20000;i=i+1000){
mytime.txt.value=setTimeout("document.getElementById('txt').value="+i,i);
}
}
</script>
</head>

<body>
<form name="mytime" >
<input type="button" value="Display timed text!" onClick="timedText()">
<input type="text" id="txt">
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>

the o/p im getting is 21, 41, 61, when i click...i think there is a logical error in the code. because when i am changing the value of the for loop

for(i=0;i<=20000;i=i+10000)

i am getting odd values...do check it out for that...

If you are a beginner in javascript...
do check out this book its really nice:John Wiley & Sons - JavaScript in 10 Steps or Less

hope this helps....
Garbage
Garbage #249
Jul 23, 2010 at 9:26 AM
the o/p im getting is 21, 41, 61, when i click...i think there is a logical error in the code. because when i am changing the value of the for loop

for(i=0;i<=20000;i=i+10000)

i am getting odd values...do check it out for that...

Thats because the setTimeout() returns the ID, which can be used for clearTimeout() function, and not the value which you want to setup.
Please check the code which I provided in above post.
A_n_k_i_t
A_n_k_i_t #250
Jul 23, 2010 at 1:02 PM
Thats because the setTimeout() returns the ID, which can be used for clearTimeout() function, and not the value which you want to setup.
Please check the code which I provided in above post.


yup, clearTimeout() can be used...but not necessary...ya checked your code...
thanks for the tip...
Garbage
Garbage #251
Jul 23, 2010 at 6:20 PM
^^ You welcome. :)
furious_gamer
Jul 23, 2010 at 6:29 PM
Javascript doesnt comes under Java. So please stop posting Scripting queries from now on. If you wish, just start a new thread for that and post your questions there.
vineetrok
vineetrok #253
Jul 23, 2010 at 9:20 PM
@garbage and @ankit: thanks for the response
@rajkumar_pb : will take care from now on!!
prateek007391
Dec 20, 2010 at 6:22 PM
Okay, it has been 2 days I have started to Learn JAVA, after having read the book, I found that I need to change the environment variable to run JAVA program In CMD.

However after changing Environment variable i found that my basic CMD commands are not functioning well, then I had to reset the environment variable.

Now I am using NETBEANS to create and run program.
Plzz help what wrong am I doing
B
Bandu #255
Dec 20, 2010 at 6:33 PM
Okay, it has been 2 days I have started to Learn JAVA, after having read the book, I found that I need to change the environment variable to run JAVA program In CMD.

However after changing Environment variable i found that my basic CMD commands are not functioning well, then I had to reset the environment variable.

Now I am using NETBEANS to create and run program.
Plzz help what wrong am I doing

You probably did set PATH=<something something>

Instead do set PATH=%PATH%;<something something>
prateek007391
Dec 20, 2010 at 6:38 PM
You probably did set PATH=<something something>

Instead do set PATH=%PATH%;<something something>

I set PATH = C:\Program Files\Java\jdk1.6.0_20\bin

How should I set it.
B
Bandu #257
Dec 20, 2010 at 6:41 PM
Code:
set PATH = %PATH%;"C:\Program Files\Java\jdk1.6.0_20\bin"
prateek007391
Dec 20, 2010 at 6:44 PM
Code:
set PATH = %PATH%;C:\Program Files\Java\jdk1.6.0_20\bin

No, Not working
After setting it as path, when I try to use cmd commands like
ping xxx.xxx.xxx.xxx
it says
'ping' is not recognized as internal command
B
Bandu #259
Dec 20, 2010 at 6:55 PM
No, Not working
After setting it as path, when I try to use cmd commands like
ping xxx.xxx.xxx.xxx
it says
'ping' is not recognized as internal command

There's a small correction. It actually is:

Code:
set PATH = %PATH%;"C:\Program Files\Java\jdk1.6.0_20\bin"

And as far as your ping not working: it maybe because you haven't done this in a new cmd window. Close your current window, do the set PATH thing again in a new window and then try the ping command.

And if still does not work, then tell me the outputs of the following command in a new cmd window, before and after setting the PATH:

Code:
echo %PATH%
prateek007391
Dec 20, 2010 at 6:56 PM
No, Not working
After setting it as path, when I try to use cmd commands like
ping xxx.xxx.xxx.xxx
it says
'ping' is not recognized as internal command


Oh Yes!!!!!!!!!
Finally I figured It Out, Thanks for helping.

Instead of %PATH% I wrote %systemroot%\system32;C:\Program Files\Java\jdk1.6.0_20\bin

and now all is working fine.
Faun
Faun #261
Dec 20, 2010 at 6:57 PM
^^Because what you have done can't be undone now without getting the original path string.
Do this and check if it works:

set PATH = %PATH%;%SystemRoot%\system32;%SystemRoot%
prateek007391
Dec 20, 2010 at 6:59 PM
Also I would like to know, is there any difference when I create JAVA files in NETBEANS or simple notepad. What is better for me.

^^Because what you have done can't be undone now without getting the original path string.
Do this and check if it works:

Should I add the java environment variable path here too, this thing is functioning fine

Now the path environment variable has been sorted out quiet well, now please tell me how to remove this error

Exception in thread "main" java.lang.NoClassDefFoundError:
B
Bandu #263
Dec 20, 2010 at 7:40 PM
Code:
set PATH = %PATH%;"C:\Program Files\Java\jdk1.6.0_20\bin"[B];.[/B]
Liverpool_fan
Dec 20, 2010 at 7:54 PM
Use a text editor and not an IDE if you are beginning. I can gather you are using Windows, I suggest Notepad++, stay away from the crappy notepad bundled in Windows.
prateek007391
Dec 20, 2010 at 7:58 PM
Code:
set PATH = %PATH%;"C:\Program Files\Java\jdk1.6.0_20\bin"[B];.[/B]

I think, I am wrong from Starting,
It would be very kind If You can assist me from setting all this up from Starting
The book I am reading just dont provide any good about it, what ever it says is just not working.
Liverpool_fan
Dec 20, 2010 at 8:27 PM
Right click, My Computer, then
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png
in the Variable Value entry, add entries for your Java directory, C:\Program Files\Java\jdk1.6.0_20\bin, the delimiter is ;. Do not delete the previous entry, just add the new try.

And oh while executing, use java program not java program.class
prateek007391
Dec 20, 2010 at 8:53 PM
Right click, My Computer, then
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png
in the Variable Value entry, add entries for your Java directory, C:\Program Files\Java\jdk1.6.0_20\bin, the delimiter is ;. Do not delete the previous entry, just add the new try.

And oh while executing, use java program not java program.class

Electricity out here, but I will try this one soon.
also as I have messed around too much in environment variable, can I know what are its default values. I am running win xp sp3.




*************
Posted via HTC

Right click, My Computer, then
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png
in the Variable Value entry, add entries for your Java directory, C:\Program Files\Java\jdk1.6.0_20\bin, the delimiter is ;. Do not delete the previous entry, just add the new try.

And oh while executing, use java program not java program.class

Electricity out here, but I will try this one soon.
also as I have messed around too much in environment variable, can I know what are its default values. I am running win xp sp3.




*************
Posted via HTC
prateek007391
Dec 21, 2010 at 7:08 PM
Right click, My Computer, then
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png
in the Variable Value entry, add entries for your Java directory, C:\Program Files\Java\jdk1.6.0_20\bin, the delimiter is ;. Do not delete the previous entry, just add the new try.

And oh while executing, use java program not java program.class

This is the error I am getting.

I have also Attached the way I am writting in Environment Variable Path.
Liverpool_fan
Dec 21, 2010 at 7:17 PM
Er you don't write %PATH% , in that dialog box :/
Try to search and get the default path used in Windows and append your java directory.
Paste this: %systemroot%\system32;%systemroot%;%systemroot%\system32\wbem;%PROGRAMFILES%\Java\jdk1.6.0_20\bin

Also Post the source code of the program to know the context of the error.
prateek007391
Dec 21, 2010 at 8:45 PM
Er you don't write %PATH% , in that dialog box :/
Try to search and get the default path used in Windows and append your java directory.
Paste this: %systemroot%\system32;%systemroot%;%systemroot%\system32\wbem;%PROGRAMFILES%\Java\jdk1.6.0_20\bin

Also Post the source code of the program to know the context of the error.

Code:
class HelloWorldApp{
	public static void main(String[] arg) {
		System.out.println("Hello World");
	}
}

still not working. Here Is what I am trying to run.
Liverpool_fan
Dec 22, 2010 at 10:42 AM
Either name your file as HelloWorldApp.java or name the class as class HelloWorld.
abhidev
abhidev #272
Dec 22, 2010 at 11:17 AM
Code:
class HelloWorldApp{
	public static void main(String[] arg) {
		System.out.println("Hello World");
	}
}

Make sure your class name and the file name is same....
Piyush
Piyush #273
Dec 22, 2010 at 10:27 PM
is it necessary for one to have a thorough knowledge in C and C++ before jumping onto java?
furious_gamer
Dec 23, 2010 at 10:54 AM
is it necessary for one to have a thorough knowledge in C and C++ before jumping onto java?

Nope. If you know OOPS concept, it is easy to start with Java. But one must know procedural language before they start any language. So C is a basic, but it is not mandatory to start with.
abhidev
abhidev #275
Dec 23, 2010 at 11:00 AM
is it necessary for one to have a thorough knowledge in C and C++ before jumping onto java?

Learning C and C++ will make you comfortable in adopting any other programming language.
prateek007391
Dec 23, 2010 at 11:02 AM
I have been working for a few Weeks with Python, Python is a good Language for Non Programmer to get through with concepts. But I was keenly intrested in Java, so I skipped Python after Basics and Started reading JAVA, but I am unable to run the most basic program, though I tired running the program in Netbeans IDE and there most of programs works so easily.


I tried renaming my file, but its still not working giving out the same error.
furious_gamer
Dec 23, 2010 at 11:28 AM
I have been working for a few Weeks with Python, Python is a good Language for Non Programmer to get through with concepts. But I was keenly intrested in Java, so I skipped Python after Basics and Started reading JAVA, but I am unable to run the most basic program, though I tired running the program in Netbeans IDE and there most of programs works so easily.

You still not able to execute a java program? With Netbeans you can?
prateek007391
Dec 23, 2010 at 11:49 AM
Yes Just write the program codes in NETBEANS IDE and Press Run Button, and It gives me the right output.
furious_gamer
Dec 23, 2010 at 12:47 PM
Yes Just write the program codes in NETBEANS IDE and Press Run Button, and It gives me the right output.

As it always. But for a beginner, using IDE is not a good practice. Then you might possibly loose the chance to know, how to setup classpath etc. So just d/l the latest jdk , install it, use Edit Plus or Notepad++ to write code, run it in command prompt.

And after u get a grip in Java, go for Eclipse IDE.
prateek007391
Dec 23, 2010 at 2:20 PM
As it always. But for a beginner, using IDE is not a good practice. Then you might possibly loose the chance to know, how to setup classpath etc. So just d/l the latest jdk , install it, use Edit Plus or Notepad++ to write code, run it in command prompt.

And after u get a grip in Java, go for Eclipse IDE.

Okay, as Instructed,

I am removing NetBeans IDE

Also I upgraded my Java SDK from 20 to 23

But the problem is still there, after searching the web I found this link which shows exactly what the problem is, however on following the steps, The problem is still not resolved.

Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError

Finally


I Got It


As said in above given Link

I tried java -classpath . HelloWorld

and the program worked.

Thanks everyone for support.
furious_gamer
Dec 23, 2010 at 3:08 PM
@prateek007391

Finally you got it work...:D

BTW I prefer Eclipse over NetBeans. NB Simply reduces all of your work of structuring a project folder and similar works. Use Eclipse 3.5 Galileo or Ganymade.
Piyush
Piyush #282
Dec 23, 2010 at 10:19 PM
thanks abhidev and furious gamer for ya help
Jaskanwar Singh
Feb 12, 2011 at 9:39 AM
help on programs in netbeans please -
how to make a program that tells whether a number is prime or not.
and how to print fabonacci series (0112358..)
furious_gamer
Feb 12, 2011 at 11:01 AM
help on programs in netbeans please -
how to make a program that tells whether a number is prime or not.
and how to print fabonacci series (0112358..)

Is it you school assignment, anyhow it's very basic program

The logic is :

First get till what limit you want the series to be continued.
1. Add first two number.
2. Put it in a variable.
3. Iterate till u reach the given limit.
4. Each time when u iterate add the numbers.
5. Inside the loop swap ur numbers.

For Prime Number :

A prime number is a whole number that is divisible only by one and itself. 3 can is divisible by 1 and 3, and is prime. 6 is divisible by 1, 2, 3, and 6, and is not prime. 1 is not counted as prime, making 2 the first prime number, and the only even prime number.

So, if you understand this logic, it is easy to do the code.
Jaskanwar Singh
Feb 14, 2011 at 6:14 PM
i tried but couldnt do that. so some more code help please
Liverpool_fan
Feb 14, 2011 at 6:42 PM
I'll recommend you to use the recursive algorithm for fibonacci series. Iterative algorithm isn't quite natural enough to code.

0, 1, 1, 2, 3, 5, 8 is patter like f(n) = f(n-1) + f(n-2), so just recursively call f(n-1) and f(n-2), and terminate by returning 1 when you get 1 as input.

And for prime numbers, use boolean flags for flagging whether the number the prime or not.
Jaskanwar Singh
Feb 14, 2011 at 7:05 PM
actually liverpool fan i am just a beginner. :-D. dont know recursive algorithm.
nims11
nims11 #288
Feb 14, 2011 at 9:33 PM
Its simple. It will help you make your programs shorter.
arpanmukherjee1
Feb 15, 2011 at 9:23 AM
actually liverpool fan i am just a beginner. :-D. dont know recursive algorithm.

that is not a problem. there r tons of tutorials on the net.

here is the one which i used. bit lengthy but sure it covers every possiblity from analysis to designing algo.

gave GATE yesterday and it had 2 2-marks ques on recursion. so recursion can become confusing if taught incorrectly. better if u r prepared.
sanithkk81
sanithkk81 #290
Feb 15, 2011 at 10:03 AM
I want to use multi page editor in my java eclipse plug in project. I'm having a wizard. I want to navigate to the multi page editor the moment I press "Finish" button. I've finished the gui design of both editor and wizard. But when I run the program after displaying the product splash screen it shows launch error and terminates the application. In error log it shows product file and editors bundle are not present. Help me out to remove the error
Jaskanwar Singh
Feb 15, 2011 at 2:18 PM
thanks nims and arpanmukherjee. will try that out.
RBX
RBX #292
Feb 20, 2011 at 10:53 AM
What is the difference in 'i = i + x' and 'i += x' ?

Code:
int i = 1;
i = i + 1.2;

produces compile time error (possible loss of precision), while
Code:
int i = 1;
i += 1.2;
doesn't.

I think it has something to do with type promotion but I couldn't understand when exactly would it be applied.
Q
QSilver #293
Feb 20, 2011 at 6:21 PM
Create a class Book having field bookno , title , status(whether available or not) , author , last issue date and price.Create constructor and method to create an instance of a book.Create method issue(),received() ,is available() %get issue date().

Test the application with objects
arpanmukherjee1
Feb 20, 2011 at 7:02 PM
What is the difference in 'i = i + x' and 'i += x' ?

Code:
int i = 1;
i = i + 1.2;

produces compile time error (possible loss of precision), while
Code:
int i = 1;
i += 1.2;
doesn't.

I think it has something to do with type promotion but I couldn't understand when exactly would it be applied.

implicit calculation is int type. compilation error is due to mismatch type. the proper casting could be :
Code:
int i = 1;
i = i + (int)1.2;
or
Code:
int i = 1;
 i = (int)((float)i + 1.2);

in your second code 1.2 is implicitly coverted to int i.e the value is 1

hoping u get the concept :smile:
RBX
RBX #295
Feb 20, 2011 at 10:26 PM
^^ I'm beginner at Java but my concepts say that Java has only safe implicit conversion that avoid truncations but i += double return int for some reason.

Only implicit conversion known to me is String + something = String.

---------- Post added at 10:26 PM ---------- Previous post was at 08:17 PM ----------

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

from: Expressions
Garbage
Garbage #296
Feb 20, 2011 at 11:53 PM
Make sure your class name and the file name is same....

That is necessary only if the class is public. Otherwise filename can be different than class name.
Liverpool_fan
Feb 21, 2011 at 7:27 AM
^ Isn't it also needed if the class has a main method?
Garbage
Garbage #298
Feb 21, 2011 at 3:45 PM
^ Isn't it also needed if the class has a main method?

No! Its not necessary even if your class has main method, though doing that doesn't make much sense.
arpanmukherjee1
Feb 23, 2011 at 7:44 PM
^^ I'm beginner at Java but my concepts say that Java has only safe implicit conversion that avoid truncations but i += double return int for some reason.

Only implicit conversion known to me is String + something = String.

---------- Post added at 10:26 PM ---------- Previous post was at 08:17 PM ----------

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

from: Expressions

JavaDocs r never wrong. i like them more than MSDN.

your compilation error occurs not due to compound statement but operation on different datatypes, one int and other float.

u cannot place float value in int, without truncation.

and String + something = String is not implicit conversion, i repeat, not implicit conversion, + operator is overloaded in case of String for concatenation.
Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

safe implicit conversion does not mean that datatypes of binary operands can be different
see: Expressions
Garbage
Garbage #300
Apr 1, 2011 at 2:10 PM
and String + something = String is not implicit conversion, i repeat, not implicit conversion, + operator is overloaded in case of String for concatenation.
Can you please elaborate on this? I think I didn't get you. What do you mean by not implicit?

By implicit I understand JDK/JRE automatically converts it, you don't have to do it manually (invoking any method).
arpanmukherjee1
Apr 1, 2011 at 10:47 PM
Can you please elaborate on this? I think I didn't get you. What do you mean by not implicit?

By implicit I understand JDK/JRE automatically converts it, you don't have to do it manually (invoking any method).

did u open the link just after that line??
this :: Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

implicit conversion = Widening Primitive Conversion
explicit conversion = Narrowing Primitive Conversions

i will now quote fragment from this page :: Conversions and Promotions
the important thing are in bold
5.1.2 Widening Primitive Conversion
The following 19 specific conversions on primitive types are called the widening primitive conversions:

* byte to short, int, long, float, or double
* short to int, long, float, or double
* char to int, long, float, or double
* int to long, float, or double
* long to float or double
* float to double

Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type and from float to double do not lose any information at all; the numeric value is preserved exactly. Conversions widening from float to double in strictfp expressions also preserve the numeric value exactly; however, such conversions that are not strictfp may lose information about the overall magnitude of the converted value.

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format. A widening conversion of a character to an integral type T zero-extends the representation of the character value to fill the wider format.

Despite the fact that loss of precision may occur, widening conversions among primitive types never result in a run-time exception (§11).

Here is an example of a widening conversion that loses precision:

Code:
   class Test {
    	public static void main(String[] args) {
    		int big = 1234567890;
    		float approx = big;
    		System.out.println(big - (int)approx);
    	}
    }

which prints:

-46

thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.

5.1.3 Narrowing Primitive Conversions
The following 23 specific conversions on primitive types are called the narrowing primitive conversions:

* byte to char
* short to byte or char
* char to byte or short
* int to byte, short, or char
* long to byte, short, char, or int
* float to byte, short, char, int, or long
* double to byte, short, char, int, long, or float

Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision.

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

A narrowing conversion of a character to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though characters represent 16-bit unsigned integer values.

The example:

Code:
  class Test {
    	public static void main(String[] args) {
    		float fmin = Float.NEGATIVE_INFINITY;
    		float fmax = Float.POSITIVE_INFINITY;
    		System.out.println("long: " + (long)fmin +
    						".." + (long)fmax);
    		System.out.println("int: " + (int)fmin +
    						".." + (int)fmax);
    		System.out.println("short: " + (short)fmin +
    						".." + (short)fmax);
    		System.out.println("char: " + (int)(char)fmin +
    						".." + (int)(char)fmax);
    		System.out.println("byte: " + (byte)fmin +
    						".." + (byte)fmax);
    	}
    }
produces the output:

long: -9223372036854775808..9223372036854775807
int: -2147483648..2147483647
short: 0..-1
char: 0..65535
byte: 0..-1

The results for char, int, and long are unsurprising, producing the minimum and maximum representable values of the type.

The results for byte and short lose information about the sign and magnitude of the numeric values and also lose precision. The results can be understood by examining the low order bits of the minimum and maximum int. The minimum int is, in hexadecimal, 0x80000000, and the maximum int is 0x7fffffff. This explains the short results, which are the low 16 bits of these values, namely, 0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of these values, namely, '\u0000' and '\uffff'; and it explains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff. Despite the fact that overflow, underflow, or other loss of information may occur, narrowing conversions among primitive types never result in a run-time exception (§11).


the whole concept can be actually explained in one line ::
if result takes more memory then implicit conversion. otherwise explicit conversion or compiler error
Garbage
Garbage #302
Apr 2, 2011 at 4:54 PM
Err.. Seems you didn't get my point. What you are talking about is primitive data types. And String is an object.

Correct me if you are still talking about String + <something> conversion and given link / explanation applies to that.
iamharish15
Apr 27, 2011 at 2:12 AM
I want to make a major project in Java Se. Can anybody suggest me the ideas for the project and the slight overview of the project you would suggest.
Garbage
Garbage #304
Apr 27, 2011 at 2:57 PM
I want to make a major project in Java Se. Can anybody suggest me the ideas for the project and the slight overview of the project you would suggest.

:|

How much time do you have?
How much years of experience you have?
How many people will be doing the project?
What are your interest areas about programming / software?
Are you ready to buy services needed (ex. product hosting site, etc.)
iamharish15
Apr 28, 2011 at 12:02 AM
I have about 1 to 2 months
I have just 8-9 months of experience in programming in Java SE in minor individual projects like contact management project etc..
Atmost 2 or 3 people will be working on the project
Well I'm not sure about my interest areas, but any project that can run without much knowledge of database would be fine
No, I would not prefer not to buy such services.

Now can you suggest any project that fits in my requirements and eligibility.
dead.night7
Apr 29, 2011 at 12:36 PM
Guys is there a compiler to run java, so as that the c++ compilers. Is it inbuilt into windows or any other please tell me direct link preferred. Anybody thanks :)
arpanmukherjee1
Apr 29, 2011 at 3:03 PM
^^ follow the steps ::

step 1.> download JDK

step 2. > read this for windows

else download netbeans
iamharish15
Apr 30, 2011 at 1:53 AM
I would like to know more options. I just wanted some suggestions and overviews about some innovative java projects.
Piyush
Piyush #309
May 29, 2011 at 3:31 PM
i'm gonna buy a book on java programming
it should cover all topics:from basics to expertise concepts

any good recommendation?
i would be ordering from flipkart most probably
S
sakumar79 #310
May 29, 2011 at 5:21 PM
I found Java How to Program by Dietel and Dietel publishers a very good book... Another option is Thinking in Java by Bruce Eckel (available as free ebook) which is also good. TiJ may not be suited for novices - if you have a basic idea of OOP it will be very good...

Arun
Liverpool_fan
May 29, 2011 at 8:39 PM
i'm gonna buy a book on java programming
it should cover all topics:from basics to expertise concepts

any good recommendation?
i would be ordering from flipkart most probably

Head First Java (Designed for Java SE)
Piyush
Piyush #312
May 30, 2011 at 9:04 AM
will this one be available easily?
furious_gamer
May 30, 2011 at 10:17 AM
^^ Yes. you can get it even at roadside shops or any major book shops, easily.
Piyush
Piyush #314
May 30, 2011 at 6:44 PM
Is this the one?
Flipkart.com: Head First Java: Kathy Sierra (9788173666025)

there is one more but cost a fortune
Flipkart.com: Head First Java: Kathy Sierra, Bert Bates (9780596009205)

whats the difference?
furious_gamer
May 30, 2011 at 6:48 PM
The one for 358. Might be a mistake at their side. If it costs 2000 bucks, i'd rather add 2500 and get HD5670.... :D
Piyush
Piyush #316
May 30, 2011 at 6:57 PM
The one for 358. Might be a mistake at their side. If it costs 2000 bucks, i'd rather add 2500 and get HD5670.... :D

:lol:

anyways I'll be needing one book for computer networks also
I've a vague idea about it, but the book should cover all relevant topics which comes in computer networks
Liverpool_fan
May 30, 2011 at 7:18 PM
:lol:

anyways I'll be needing one book for computer networks also
I've a vague idea about it, but the book should cover all relevant topics which comes in computer networks

Not all topics, but Head First Networking will really build your basics very well.

The one for 358. Might be a mistake at their side. If it costs 2000 bucks, i'd rather add 2500 and get HD5670.... :D

The 2k one is imported edition. Not quite worth it though.
bijay_ps
bijay_ps #318
May 31, 2011 at 8:20 AM
thread creation & "this" keyword doubt

what is the use of "this" keyword in thread creation in java? And check out this program:
Code:
[CODE]class NewThread implements Runnable{
	Thread t;
	NewThread(){
		t=new Thread(this,"Demo Thread");
		System.out.println("Child Thread: " + t);
		t.start();
	}
public void run(){
	try{
		for(int i=5;i>0;i--){
			System.out.println("Child Thread: " + i);
			Thread.sleep(500);
		}
	}catch(InterruptedException e){
		System.out.println("Child interrupted.");
		}
        System.out.println("Exiting child thread.");
		}
}
class ThreadDemo {
	public static void main(String args[]){
		new NewThread();
		try{
			for(int i=5;i>0;i--){
				System.out.println("Main Thread: " + i);
				Thread.sleep(1000);
			}
		}catch(InterruptedException e){
			System.out.println("Main thread interruoted.");
		}
	System.out.println("Main thread exiting.");
	}
}
[/CODE]
In this program if instead of keyword "this" i use only "t", I get output but only for main thread and not for child thread. Why the output differs? If "this" keyword only refer to the instance of the class from its method then why can't we use that instance directly?
Garbage
Garbage #319
May 31, 2011 at 8:52 AM
:lol:

anyways I'll be needing one book for computer networks also
I've a vague idea about it, but the book should cover all relevant topics which comes in computer networks

This is THE book for learning all about Computer Networks
Amazon.com: Computer Networks (9780133499452): Andrew S. Tanenbaum: Books
arpanmukherjee1
May 31, 2011 at 9:28 AM
anyways I'll be needing one book for computer networks also
I've a vague idea about it, but the book should cover all relevant topics which comes in computer networks

java:
beg: head first / complete reference
adv: Kathy Sierra / Khalid Mughal

networking :
beg: head first
med: computer networks by Tanenbaum
adv: CCNA course material (Vol 1 + Vol 2)
bijay_ps
bijay_ps #321
May 31, 2011 at 10:02 AM
can anyone tell me what is the most effective way of learning JAVA, I am reading Complete reference for it....... but there is alot of thing given inside it and due to which I get confuse sometime :-(
So suggest me something
furious_gamer
May 31, 2011 at 10:08 AM
^^ Get Head First Java. A fun way to learn effective Java. Use Complete Reference once you are good enough at basics.

For your previous post, read this link... (Regd "this" keyword)

Java "this" Keyword - Java Forums

Simply, "this refers to current object on which method is executing".
Piyush
Piyush #323
May 31, 2011 at 8:40 PM
what the heck

yesterday the cost of java head first was 328/--
and today it is 413!!!!

should i wait for the prices to fall again?

seriously life is pain
furious_gamer
Jun 1, 2011 at 11:26 AM
what the heck

yesterday the cost of java head first was 328/--
and today it is 413!!!!

should i wait for the prices to fall again?

seriously life is pain

Go get in shops like Odyssey, higgin bothams and buy it...
047
047 #325
Jun 8, 2011 at 11:42 AM
Hi all,

I am developing an application using Java Swing. I am stuck somewhere. I need to display a date in a textbox and that date is fetched from MsAccess table, i am able to display that date in textbox but the format is not which i want. Date displayed is in the form e.g "2011-12-25 00:00:00" but i want it to be as "25/12/2011". the date in the table is in form "25/12/2011" with date type.

If anyone know this please help me.
furious_gamer
Jun 8, 2011 at 12:03 PM
Hi all,

I am developing an application using Java Swing. I am stuck somewhere. I need to display a date in a textbox and that date is fetched from MsAccess table, i am able to display that date in textbox but the format is not which i want. Date displayed is in the form e.g "2011-12-25 00:00:00" but i want it to be as "25/12/2011". the date in the table is in form "25/12/2011" with date type.

If anyone know this please help me.

Use SimpleDateFormat method to format the date as you wish.

like

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formateDB = new SimpleDateFormat("yyyy-MM-dd");
String your_date = "2011-12-25 00:00:00";
System.out.println(sdf.format(formateDB.parse(your_date)));

I am not sure about the above code, but IIRC it is what i did in exact same case.
P
Jun 8, 2011 at 8:01 PM
There a number of IDE for development in Java SE. These include JCreator, BlueJ, NetBeans and various others. If you are a beginner then use BlueJ for its simplicity and if you can code to a fairly good amount then use JCreator. My personal preference is Notepad, and then compiling the files manually via the console.
furious_gamer
Jun 9, 2011 at 10:04 AM
^^
???? To whom you are replying?
prateek007391
Jun 9, 2011 at 11:36 AM
I have used Python a bit and there is a nice feature that you can easily control Strings like

Hello * 3 = HelloHelloHello

however how to do so in Java.

Plzz Help!!!
Liverpool_fan
Jun 9, 2011 at 11:52 AM
I have used Python a bit and there is a nice feature that you can easily control Strings like

Hello * 3 = HelloHelloHello

however how to do so in Java.

Plzz Help!!!

Er just because you do it in Python, doesn't mean you can do it in Java. If you like Python and want to leverage its power in the Java Platform, check out Jython.

And I doubt that's even possible, because as far as my limited knowledge in Java, there's no operator overloading so that I could create a string like class and add the operator to it. And certainly you can't use strign literals with such an operator.
prateek007391
Jun 10, 2011 at 10:38 PM
Seems most of the problems are getting sorted out.

However Plzz any one tell me how to clear screen in Java

Right now I am learning to create simple Apps, working in CMD

so what syntax I can use to clear screen.
Garbage
Garbage #332
Jun 11, 2011 at 8:26 AM
^^ why don't you use DOS command prompt command "cls" to clear the screen?
prateek007391
Jun 14, 2011 at 12:41 PM
I know its Cls to clear screen in CMD

What about in Java.

is there any command in Java so that it can clear the screen of command prompt.

Something like

import java.OS. something something
Garbage
Garbage #334
Jun 14, 2011 at 1:57 PM
^^ Java don't directly have access to command promp AFAIK.
If you want to execute a system command you might want to check Java exec - execute system processes with Java ProcessBuilder and Process (part 1) | devdaily.com
furious_gamer
Jun 14, 2011 at 2:24 PM
^^ Please be clear with your question? In java?

AFAIK this is what you looking for

System.out.println(((char) 27)+"[2J");
deathwish
deathwish #336
Jun 20, 2011 at 5:09 PM
I want to learn Java and have gotten down to it already. I would like to know which IDE to use. I downloaded Eclipse. Is that appropriate for my level or should I rather download something more basic?

I know C/C++ so the logic behind the programs isn't too difficult for me to grasp, if that is any help at all. :p
Liverpool_fan
Jun 20, 2011 at 5:10 PM
Don't use an IDE. Simply use an advanced text editor.
furious_gamer
Jun 20, 2011 at 5:16 PM
EditPlus or similar one. I forgot one, it ends with ++, like Editpad++.
Liverpool_fan
Jun 20, 2011 at 5:19 PM
Assuming that you are using Windows OS, then install Notepad++. And yeah make sure when you install JDK, configure the paths.
And then you can save your code in Notepad++ and use javac and java commands in your command prompt. The reason I recommend this is for better understanding of the classpath et al.
After a while, if you find these steps too long, use Geany, will have all ease of use of an IDE with simplicity of a text editor.
deathwish
deathwish #341
Jun 20, 2011 at 5:26 PM
Thank you. I think I'll work on this for now. I'll be back. :)
tuxybuzz
tuxybuzz #342
Jun 23, 2011 at 11:48 PM
notepad/textpad on windows.
vim on linux.
While starting off with a text editor is always good. I do suggest you move onto a full fledged IDE(Netbeans, Eclipse etc.) once you have considerable command over the language.
F
funstreak #343
Jul 2, 2011 at 9:28 PM
I'm creating a java code and getting an error.

Prog is I have to rotate a string in Applets.
Suppose a String is "HELLO".
I can rotate this string as :

HELLO -> HELLO -> HELLO

i.e. running on x axis.

Now Where exactly i'm getting the error is when i'm trying to rotate its characters. Means I want output like this :

HELLO
OHELL
LOHEL
LLOHE
ELLOH
HELLO

Rotating like this.
Tell me what to do now? I'm using a concept of substring in it.
Code:
String r = s.charAt(s.length()-1) + s.substring(0, s.length()-1);
Garbage
Garbage #344
Jul 2, 2011 at 9:35 PM
Actually, you should be changing the x co-ordinates of the JLabel and not the characters of string.
F
funstreak #345
Jul 2, 2011 at 9:45 PM
Sorry but i had not learn about java labels as i am beginner in it. and learn java upto io packages. now m learning applets.
RBX
RBX #346
Jul 7, 2011 at 10:38 AM
I'm creating a java code and getting an error.

What error ? I think I've seen same example in Herbert Schildt's Complete Reference to Java. If you've used exact same code, then there might be other reasons behind the failure of applet.



Posts being merged is a real pain

Here is a problem I was unable to solve on my own. My path variable contains D:\Program Files\Java\jdk1.7.0\bin but running java from cmd starts build 1.7.0-b127 whereas the one installed at specified path is 1.7.0-b147

D:\Documents and Settings\Tushar>"D:\Program Files\Java\jdk1.7.0\bin\java.exe" -version
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)

D:\Documents and Settings\Tushar>java -version
java version "1.7.0-ea"
Java(TM) SE Runtime Environment (build 1.7.0-ea-b127)
Java HotSpot(TM) Client VM (build 20.0-b06, mixed mode, sharing)
A
amit dutt #347
Jul 8, 2011 at 1:59 PM
which IDE for Java is better?

Eclipse or NetBeans ?
Garbage
Garbage #348
Jul 8, 2011 at 2:42 PM
Here is a problem I was unable to solve on my own. My path variable contains D:\Program Files\Java\jdk1.7.0\bin but running java from cmd starts build 1.7.0-b127 whereas the one installed at specified path is 1.7.0-b147

D:\Documents and Settings\Tushar>"D:\Program Files\Java\jdk1.7.0\bin\java.exe" -version
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)

D:\Documents and Settings\Tushar>java -version
java version "1.7.0-ea"
Java(TM) SE Runtime Environment (build 1.7.0-ea-b127)
Java HotSpot(TM) Client VM (build 20.0-b06, mixed mode, sharing)

This is because you have 2 JRE/JDKs in your Window's PATH variable. And in that semi-colon separated PATH variable, entry for 1.7.0-ea is first.
Edit your PATH environmental variable. It will solve your problem.
A
Jul 8, 2011 at 4:03 PM
A pleasant experience with this book!

I am almost through reading head first java and it is a awesome book.It is not one of those books which is like THEORY ,CODE, THEORY, CODE.The book is funny at many instances.there are exercises at the end which are thought provoking.9.5/10!!!
iamharish15
Jul 8, 2011 at 11:57 PM
which IDE for Java is better?

Eclipse or NetBeans ?
Though both are good, you can choose any but eclipse has better user interface and easy to use!
I personally use Netbeans 6.9.1 and I am more comfortable using it than eclipse but most programmers now choose eclipse over Netbeans due to its easier interface and some new features that Netbeans don't have!
Final Suggestion: go for Eclipse and master it! as it trending now-a-days!
iamharish15
Aug 4, 2011 at 12:47 AM
How To Design Pages in JSP using 'Drag n Drop'

I have recently been learning J2EE. I don't have much knowledge of HTML.
I want to design the pages using drag n drop. I am using Netbeans 7.
Actually our teacher is not teaching us this thing as he wants us to master the designing in coding way first but that requires the knowledge of HTML also.
So can anybody tell me how to design the web pages in JSP using drag n drop through Netbeans 7.
furious_gamer
Aug 4, 2011 at 10:44 AM
^^ Dude, use Dreamweaver to design pages. It is by far the easiest IDE to create HTML pages, as you said, by drag-n-drop.
Liverpool_fan
Aug 4, 2011 at 11:53 AM
Re: How To Design Pages in JSP using 'Drag n Drop'

I have recently been learning J2EE. I don't have much knowledge of HTML.
I want to design the pages using drag n drop. I am using Netbeans 7.
Actually our teacher is not teaching us this thing as he wants us to master the designing in coding way first but that requires the knowledge of HTML also.
So can anybody tell me how to design the web pages in JSP using drag n drop through Netbeans 7.

Not willing to learn HTML? That's massive fail. No offense. Just get a copy of Head First XHTML and CSS, it would only take a week for god sake.
furious_gamer
Aug 4, 2011 at 12:04 PM
^^ Sh1t, i missed that part, but i doubt how he will work with JSP if he don't have knowledge of HTML?
iamharish15
Aug 4, 2011 at 6:50 PM
^^ Sh1t, i missed that part, but i doubt how he will work with JSP if he don't have knowledge of HTML?

Its not that I don't know HTML at all. I have the basic knowledge and I can create a page containing forms, buttons, radio buttons, text area, tables etc etc..
But I meant to say that I am not an expert in HTML, I won't be able to create the page designs as good as I want! That's why I asked about it here.

Anyways You Suggested Dreamweaver, But Can't I design the web pages in Netbeans IDE through Drag n Drop??? like Visual Studio....
Liverpool_fan
Aug 4, 2011 at 9:04 PM
You want this?

Easy Web Site Creation in the NetBeans IDE
furious_gamer
Aug 5, 2011 at 10:35 AM
Its not that I don't know HTML at all. I have the basic knowledge and I can create a page containing forms, buttons, radio buttons, text area, tables etc etc..
But I meant to say that I am not an expert in HTML, I won't be able to create the page designs as good as I want! That's why I asked about it here.

Anyways You Suggested Dreamweaver, But Can't I design the web pages in Netbeans IDE through Drag n Drop??? like Visual Studio....

You can do that with Netbeans, but it would be not that much comfortable compared to Dreamweaver. Though if you insist, you can go for Netbeans itself, but i prefer Dreamweaver any day.
iamharish15
Aug 9, 2011 at 1:47 AM
actually my question was not to ask which IDE should I use. I wanted to know how can I use the drag n drop features(if any) to easily design the pages in jsp. And that question is still waiting for the satisfying answer!!!
I was asking like Visual Studio or Dreamweaver, can jsp pages also be designed without having to write code for each segment!
Garbage
Garbage #359
Aug 9, 2011 at 9:56 AM
actually my question was not to ask which IDE should I use. I wanted to know how can I use the drag n drop features(if any) to easily design the pages in jsp. And that question is still waiting for the satisfying answer!!!
I was asking like Visual Studio or Dreamweaver, can jsp pages also be designed without having to write code for each segment!

*www.myeclipseide.com/module-htmlpages-display-pid-12.html

asp.net - Drap and Drop in Eclipse for Web Projects - Stack Overflow
iamharish15
Aug 9, 2011 at 10:50 PM
*www.myeclipseide.com/module-htmlpages-display-pid-12.html

asp.net - Drap and Drop in Eclipse for Web Projects - Stack Overflow
Thanks for the links, but I have been working on Netbeans, so can you please provide the same info for Netbeans...
Piyush
Piyush #361
Aug 20, 2011 at 9:52 PM
are the both following codes do same work?

Code:
dog[] pets;
pets= new dog[7];

Code:
dog[] pets=new dog[7];

also
I need a good description about get and set methods
Garbage
Garbage #362
Aug 22, 2011 at 3:03 PM
are the both following codes do same work?

Code:
dog[] pets;
pets= new dog[7];

Code:
dog[] pets=new dog[7];

Yes, these both do the same work.

also
I need a good description about get and set methods

You might find following post useful - PaulBarry.com - Why to use Getters/Setters instead of public fields
Piyush
Piyush #363
Aug 22, 2011 at 3:27 PM
@garbage
thanks ....will go through the article asap

one more query

consider the following
code1:
Code:
dog d1=new dog();
code2:
Code:
dog[] d=new dog[7];
dog[0]=new dog();
dog[1]=new dog();
//...and so on

what is happening in the 2 code snippets?
AFAIK
In code 1:we have created a new dog object and named it d1

In code 2:we have created an array of dog objects and assigned them the place in dog array

Is it true?Am I missing anything else?And is there any fault in the concept?
Garbage
Garbage #364
Aug 23, 2011 at 3:14 PM
Code:
dog[] d=new dog[7];
dog[0]=new dog();
dog[1]=new dog();
//...and so on
This is wrong.

The correct code is:
Code:
dog[] d=new dog[7];
[B]d[0][/B]=new dog();
[B]d[1][/B]=new dog();
//...and so on
Other than that, you are absolutely right.

In first code, you can always access the object of Dog directly. However in second code, You can't access any Dog object directly (as you don't have their reference in a separate variable). So you will have to access the array first and then access the object (using it's index).

If you are confused by above explanation, consider, you have a bark() method in Dog class.
Now in first code, you can invoke the bark() using:
Code:
d1.bark();

while in second code, lets assume you want to invoke bark() on second object of Dog, you have to use following:
Code:
d[0].bark();
Piyush
Piyush #365
Aug 27, 2011 at 11:56 AM
thanks garbage
I wanted to ask something on interfaces and polymorphism
will post as soon as I get an appropriate code
Garbage
Garbage #366
Aug 31, 2011 at 10:08 AM
thanks garbage
I wanted to ask something on interfaces and polymorphism
will post as soon as I get an appropriate code

Sure. Bring it on. I would be glad to help. :)
Piyush
Piyush #367
Aug 31, 2011 at 7:54 PM
Code:
[B]class animal[/B]
{
eat();
sleep();
noise();
}

[B]class dog extends animal[/B]
{
eat()
{
//statements
}
noise()
{
//statements
}
}

[B]class lion extends animal[/B]
{
eat()
{
//statements
}
noise()
{
//statements
}
}

[B]class hippo extends animal[/B]
{
eat()
{
//statements
}
noise()
{
//statements
}
}
[B]class vet(animal a)[/B]
{
cure()
{
//statements
}
}

[B]class wildlife[/B]
{
public static void main(String[] args)
{
dog d=new dog();
lion l=new lion();
hippo h=new hippo;
vet v=new vet();
[COLOR="Red"]//what is happening after this line?[/COLOR]
v.cure(d);
v.cure(h);
}
}

and is the above code an example of polymorphism?If yes,how?
Neo
Neo #368
Sep 19, 2011 at 9:31 PM
i want to learn JAVA, Where do i learn it from?
furious_gamer
Sep 19, 2011 at 9:57 PM
^^ Some good book like Head First Java.
Prime_Coder
Sep 20, 2011 at 12:31 AM
My suggestion would be the book: Core Java. Volume I, Fundamentals by Cay S. Horstmann & Gary Cornell.
Read the next volume after that.
Simultaneously looking at tutorials on the web will also help a lot.
Neo
Neo #371
Sep 20, 2011 at 10:10 AM
should i learn it from an institute or i can do this at home?

PS:I know only C++,and that too not properly. Will that do?
Garbage
Garbage #372
Sep 20, 2011 at 10:15 AM
should i learn it from an institute or i can do this at home?

PS:I know only C++,and that too not properly. Will that do?

I don't think you need to go to any institution to learn Java. Only thing you MUST do to learn Java at home is to WRITE LOTS OF CODE! :)
Prime_Coder
Sep 21, 2011 at 12:12 AM
should i learn it from an institute or i can do this at home?

PS:I know only C++,and that too not properly. Will that do?

You can learn it from home, very well.

Don't get bothered about C++ knowledge. If you know OOP concepts from C++, it will be advantage for you(or easy, you can say).
dashing.sujay
Sep 21, 2011 at 12:27 AM
You can learn it from home, very well.

Don't get bothered about C++ knowledge. If you know OOP concepts from C++, it will be advantage for you(or easy, you can say).

PS:I know only C++,and that too not properly. Will that do?

Well if anybody doesn't knows C++ well, you can't expect him to have clear concepts of OOP either. And if anybody has confused concepts of OOP, java will be a tough task for him as Java has much better implication of OOP than C++.
A
Oct 2, 2011 at 7:17 AM
I learnt a lot of java from head first java.It is one of those of books which keeps you interested and relaxed in the topics.It looks like a casual book but does explain stuff very well.I bought it on flipkart...
masterkd
masterkd #377
Oct 17, 2011 at 8:55 PM
head first java is only for beginners. if you really want to know java study SCJP by Kathy Sierra..that's the best I can find but its not for beginners!!
Ksquare
Ksquare #378
Oct 24, 2011 at 3:31 PM
I have written a code to find the 10001st prime number(Project Euler, problem 7). But it refuses to work. Can someone please help?

Code:
class testing
{
 public static int testprime(int num)
 {
  int flag=0;
  for(int i=1;i<=num;i++)
     {
      if(num%i==0)
        {
         flag++;
        }
	 }   	
      if(flag>2)
         return 0;
      else
         return 1;
 }		 
 public static void main(String args[])
 {
  int i,n=0,flag=0,t,x;
  int p=2;
  while(n<=10001)
       {
	    x=n;
        t=testprime(p);
        if(t==1)
          {
           p++;
           n++;
          }
        else
          {
		   p++;
		   n=x;
		  } 
       }	
 }
}
N
Nov 1, 2011 at 1:50 PM
Re: programming

wap to display in java based on the user input string where the input string is LAKSHMI
L
A A
K K K
S S S S
H H H
M M
I
Garbage
Garbage #380
Nov 1, 2011 at 3:00 PM
Re: programming

wap to display in java based on the user input string where the input string is LAKSHMI
L
A A
K K K
S S S S
H H H
M M
I

First, you can post these programs in this thread:
*www.thinkdigit.com/forum/programming/71499-post-ur-java-queries-here.html


Secondly, please attempt to write program yourself. If it has some problems, then post it here so that we can suggest corrections. Don't expect members to write whole program for you without you trying to write it first. This is for your own good. :)
A
arnab.d287 #381
Nov 13, 2011 at 10:14 AM
I wanted to create a game like the 15puzzle
15puzzle
Code:
import java.io.*;
class puzzle
{
    int a[][]={{8,2,7,4},{1,11,0,10},{15,3,12,5},{14,6,13,9}};
    int n; int r=0; int c=0;
    public void main()throws IOException
    {
        display();
        
        do
        {         
            input();
            swapping(a, r, c);
            checkForCompletion();
            display();
        }while(true);
    }
    public void input()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the number to move");
        System.out.println("Enter 0 to exit");
        n=Integer.parseInt(br.readLine());
        
        int flag=0;
        int c=0,r=0;
        
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(n==a[i][j])
                {
                    r=i;
                    c=j;
                    flag=1;
                    break;
                }
            }
        if(n<1&&n>15)
            System.out.println("Invalid Input");
        else if (flag!=1)
            System.out.println("Invalid Input");
        else if(n==0)
            System.exit(0);
    }
    public void swapping(int a[][], int r, int c)
    {
        int fl=0;
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(r!=3||a[r+1][c]==0)
                {
                    a[r+1][c]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=0||a[r-1][c]==0)
                {
                    a[r-1][c]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=0||a[r][c-1]==0)
                {
                    a[r][c-1]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=3||a[r][c+1]==0)
                {
                    a[r][c+1]=n;fl=1;
                    a[r][c]=0;
                }
                
            }
        if(fl!=1)
            System.out.println("Cannot be moved");
        
    }
    public void checkForCompletion()
    {
        int c=1;int fl=0;
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(i!=4&&j!=4)
                {
                    if(a[i][j]!=c++)
                        fl=1;
                }
            }
        if (fl==0)
        {
            System.out.println("Completed");
            System.exit(0);
        }
        
    }
   
    public void display()
    {
        for (int i=0;i<4;i++)
        {
            for(int j=0;j<4;j++)
            {
                System.out.print(a[i][j]+"  ");
            }
            System.out.println();
        }
    }
}
I used the blank space as 0(zero) for the game
but it is not running as it should be.. Can anyone tell whats wrong?
Garbage
Garbage #382
Nov 15, 2011 at 11:53 AM
^^ Sorry if it's the spoiler for you, but I found the program pretty interesting and wrote a solution for that.

Here is the code: *pastie.org/2865669

Code:
import java.io.*;

/**
 * A puzzle game
 * @author Shirish Padalkar
 *
 */
public class Puzzle {
	
	/**
	 * Reader to read numbers from standard input
	 */
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	/**
	 * Main method which handles the puzzle. The flow of the puzzle is as following:
	 * <ol>
	 * 	<li>Display the current state of puzzle</li>
	 *  <li>If puzzle is not completed, ask for a number to move.</li>
	 *  <li>Check if the number is in valid input range.</li>
	 *  <li>Check if the number can be moved. If yes, then move the number, else show error message. Go to step 2.</li>
	 *  <li>Move the number.</li>
	 *  <li>Go to step 1</li>
	 * </ol>
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		
		/**
		 * Array to hold the numbers of the puzzle.
		 */
		int[][] array = { 
				{ 8, 2, 7, 4 },
				{ 1, 11, 0, 10 },
				{ 15, 3, 12, 5 },
				{ 14, 6, 13, 9 }
			};
		
		/*int[][] array = { 
				{ 1, 2, 3, 4 },
				{ 5, 6, 7, 8 },
				{ 9, 10, 11, 12 },
				{ 13, 14, 0, 15 }
			};*/
		
		boolean completed = false, validInput = false;
		int number;
		
		System.out.println("Welcome to Puzzle. Please enter 0 to exit.");
		display(array);

		while (!completed){
			number = input();
			if (number == 0){
				System.exit(0);
			}
			
			validInput = isValidInput(array, number);
			if (!validInput){
				System.err.println("Invalid Input");
				continue; // Skip the swapping. Ask for input again.
			}
			
			// A number must be swapped by now. If not, then throw error.
			if (!swap(array, number)){
				System.err.println("The number you entered can't be moved.");
			}
			
			display(array);
			
			completed = checkForCompletion(array);
		}
		
		System.out.println("Congratulations! You have successfully completed the puzzle. :)");
	}

	/**
	 * A method to display the puzzle current state
	 * @param array Current state of the puzzle
	 */
	private static void display(final int[][] array) {
		System.out.println("---------------------");
		for (int i = 0; i < 4; i++) {
			System.out.print("| ");
			for (int j = 0; j < 4; j++) {
				System.out.print((array[i][j] == 0?"  ":(array[i][j]<10?" "+array[i][j]:array[i][j])) + " | ");
			}
			System.out.println("\n---------------------");
		}
	}
	
	/**
	 * A method to get a number to move in the puzzle
	 * @return number accepted. 0 in case of invalid input (Exception)
	 */
	private static int input(){
		System.out.print("Enter the number to move : ");
		int num = 0;
		try{
			num = Integer.parseInt(br.readLine());
		} catch(IOException e){
			System.err.println("Invalid input. Not a number!");
		}
		return num;
	}
	
	/**
	 * A method to check if user input number is valid
	 * @param array current state of the puzzle
	 * @param number number to check if present in the puzzle
	 * @return
	 */
	private static boolean isValidInput(final int[][] array, int number){
		if (number < 1 && number > 15)
			return false;

		// Check if the number is present in the puzzle, so that we can move
		for (int i = 0; i < 4; i++){
			for (int j = 0; j < 4; j++) {
				if (number == array[i][j]) {
					return true;
				}
			}
		}
		return false;
	}

	
	/**
	 * A method to swap the number with empty column
	 * @param array Current state of the puzzle
	 * @param number number to swap with
	 * @return true if number is swapped. false if can't be swapped
	 */
	private static boolean swap(final int[][] array, int number) {
		// Determine the position of the "number to be swapped" in the matrix
		int row=0, column=0;
		boolean found = false;
		for (row=0; !found && row<4; row++){
			for (column=0; !found && column<4; column++){
				if(array[row][column] == number){
					found = true;
					//System.out.println("Found number at position "+row+"["+column+"]");
					break;
				}
			}
		}
		row--; //decremented row because once we broke from inner loop, program did row++ and then check the condition !found && row<4
		if (!found){
			System.err.println("Invalid number");
			return false;
		}
		
		boolean swapped = false;
		// row[column] now holds the number, check if any adjacent value is 0 so that we can swap
		// A number can be swapped only if any of left/right/top/bottom value is 0
		if (column > 0){ // Can check left
			//System.out.println("row: "+row+", column: "+column+", checking left");
			if (array[row][column-1] == 0){ // Got empty at left. Can swap
				array[row][column-1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && column < 3){ // Can check right
			//System.out.println("row: "+row+", column: "+column+", checking right");
			if (array[row][column+1] == 0){ // Got empty at left. Can swap
				array[row][column+1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row > 0){ // Can check top
			//System.out.println("row: "+row+", column: "+column+", checking top");
			if (array[row-1][column] == 0){ // Got empty at left. Can swap
				array[row-1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row < 3){ // Can check bottom
			System.out.println("row: "+row+", column: "+column+", checking bottom");
			if (array[row+1][column] == 0){ // Got empty at left. Can swap
				array[row+1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		return swapped;
	}

	
	/**
	 * A method to check if the puzzle is completed
	 * @param array current state of the puzzle
	 * @return true if puzzle is completed. false otherwise
	 */
	private static boolean checkForCompletion(final int[][] array) {
		
		//System.out.println("Checking for completion.");
		int counter = 1;
		
		for (int row = 0; row < 4; row++){
			for (int column = 0; column < 4 && counter < 16; column++, counter++) {
				if (array[row][column] != counter){
					//System.out.println("Not completed because value of puzzle["+row+"]["+column+"] is "+array[row][column]+", not "+counter);
					return false;
				}
			}
		}
		return true; // Control will come here only if everything is fine.
	}
}
A
arnab.d287 #383
Nov 15, 2011 at 1:25 PM
^^ Sorry if it's the spoiler for you, but I found the program pretty interesting and wrote a solution for that.

Here is the code: #2865669 - Pastie

Code:
import java.io.*;

/**
 * A puzzle game
 * @author Shirish Padalkar
 *
 */
public class Puzzle {
	
	/**
	 * Reader to read numbers from standard input
	 */
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	/**
	 * Main method which handles the puzzle. The flow of the puzzle is as following:
	 * <ol>
	 * 	<li>Display the current state of puzzle</li>
	 *  <li>If puzzle is not completed, ask for a number to move.</li>
	 *  <li>Check if the number is in valid input range.</li>
	 *  <li>Check if the number can be moved. If yes, then move the number, else show error message. Go to step 2.</li>
	 *  <li>Move the number.</li>
	 *  <li>Go to step 1</li>
	 * </ol>
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		
		/**
		 * Array to hold the numbers of the puzzle.
		 */
		int[][] array = { 
				{ 8, 2, 7, 4 },
				{ 1, 11, 0, 10 },
				{ 15, 3, 12, 5 },
				{ 14, 6, 13, 9 }
			};
		
		/*int[][] array = { 
				{ 1, 2, 3, 4 },
				{ 5, 6, 7, 8 },
				{ 9, 10, 11, 12 },
				{ 13, 14, 0, 15 }
			};*/
		
		boolean completed = false, validInput = false;
		int number;
		
		System.out.println("Welcome to Puzzle. Please enter 0 to exit.");
		display(array);

		while (!completed){
			number = input();
			if (number == 0){
				System.exit(0);
			}
			
			validInput = isValidInput(array, number);
			if (!validInput){
				System.err.println("Invalid Input");
				continue; // Skip the swapping. Ask for input again.
			}
			
			// A number must be swapped by now. If not, then throw error.
			if (!swap(array, number)){
				System.err.println("The number you entered can't be moved.");
			}
			
			display(array);
			
			completed = checkForCompletion(array);
		}
		
		System.out.println("Congratulations! You have successfully completed the puzzle. :)");
	}

	/**
	 * A method to display the puzzle current state
	 * @param array Current state of the puzzle
	 */
	private static void display(final int[][] array) {
		System.out.println("---------------------");
		for (int i = 0; i < 4; i++) {
			System.out.print("| ");
			for (int j = 0; j < 4; j++) {
				System.out.print((array[i][j] == 0?"  ":(array[i][j]<10?" "+array[i][j]:array[i][j])) + " | ");
			}
			System.out.println("\n---------------------");
		}
	}
	
	/**
	 * A method to get a number to move in the puzzle
	 * @return number accepted. 0 in case of invalid input (Exception)
	 */
	private static int input(){
		System.out.print("Enter the number to move : ");
		int num = 0;
		try{
			num = Integer.parseInt(br.readLine());
		} catch(IOException e){
			System.err.println("Invalid input. Not a number!");
		}
		return num;
	}
	
	/**
	 * A method to check if user input number is valid
	 * @param array current state of the puzzle
	 * @param number number to check if present in the puzzle
	 * @return
	 */
	private static boolean isValidInput(final int[][] array, int number){
		if (number < 1 && number > 15)
			return false;

		// Check if the number is present in the puzzle, so that we can move
		for (int i = 0; i < 4; i++){
			for (int j = 0; j < 4; j++) {
				if (number == array[i][j]) {
					return true;
				}
			}
		}
		return false;
	}

	
	/**
	 * A method to swap the number with empty column
	 * @param array Current state of the puzzle
	 * @param number number to swap with
	 * @return true if number is swapped. false if can't be swapped
	 */
	private static boolean swap(final int[][] array, int number) {
		// Determine the position of the "number to be swapped" in the matrix
		int row=0, column=0;
		boolean found = false;
		for (row=0; !found && row<4; row++){
			for (column=0; !found && column<4; column++){
				if(array[row][column] == number){
					found = true;
					//System.out.println("Found number at position "+row+"["+column+"]");
					break;
				}
			}
		}
		row--; //decremented row because once we broke from inner loop, program did row++ and then check the condition !found && row<4
		if (!found){
			System.err.println("Invalid number");
			return false;
		}
		
		boolean swapped = false;
		// row[column] now holds the number, check if any adjacent value is 0 so that we can swap
		// A number can be swapped only if any of left/right/top/bottom value is 0
		if (column > 0){ // Can check left
			//System.out.println("row: "+row+", column: "+column+", checking left");
			if (array[row][column-1] == 0){ // Got empty at left. Can swap
				array[row][column-1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && column < 3){ // Can check right
			//System.out.println("row: "+row+", column: "+column+", checking right");
			if (array[row][column+1] == 0){ // Got empty at left. Can swap
				array[row][column+1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row > 0){ // Can check top
			//System.out.println("row: "+row+", column: "+column+", checking top");
			if (array[row-1][column] == 0){ // Got empty at left. Can swap
				array[row-1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row < 3){ // Can check bottom
			System.out.println("row: "+row+", column: "+column+", checking bottom");
			if (array[row+1][column] == 0){ // Got empty at left. Can swap
				array[row+1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		return swapped;
	}

	
	/**
	 * A method to check if the puzzle is completed
	 * @param array current state of the puzzle
	 * @return true if puzzle is completed. false otherwise
	 */
	private static boolean checkForCompletion(final int[][] array) {
		
		//System.out.println("Checking for completion.");
		int counter = 1;
		
		for (int row = 0; row < 4; row++){
			for (int column = 0; column < 4 && counter < 16; column++, counter++) {
				if (array[row][column] != counter){
					//System.out.println("Not completed because value of puzzle["+row+"]["+column+"] is "+array[row][column]+", not "+counter);
					return false;
				}
			}
		}
		return true; // Control will come here only if everything is fine.
	}
}


Thanks.. I found out the missing link..

Thanks Garbage...
R
Dec 17, 2011 at 7:24 PM
Java Code retrieving from DB

Guys can someone help me with Java code that can be used to connect to a DB and retrieve from the DB.
Scenario-->
1) A user interface where it asks the user to enter an item (say chocolates, veggies etc..)
2) After user input, it checks the DB (which already has some predefined list of items) and if an item match occurs, it must display in an alert box that the item match is found.

I am a newbie in Java. So kindly provide me the full code if possible.
Garbage
Garbage #386
Dec 20, 2011 at 3:24 PM
^^ To access database using Java, please read following tutorial:
Trail: JDBC(TM) Database Access (The Java™ Tutorials)
R
Dec 20, 2011 at 3:40 PM
To access database using Java, please read following tutorial:


Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?
Piyush
Piyush #388
Dec 20, 2011 at 8:40 PM
Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?
well you need something to "follow" your instruction
thats what button object is doing there
rest of all is the concept of JDBC
Garbage
Garbage #389
Dec 21, 2011 at 2:02 PM
Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?

After a click of button, create an instance of the your connection class and use it for your database activities.
A
arnab.d287 #390
Dec 22, 2011 at 8:50 AM
Can anyone give me some programs to work on?? I have limited knowledge to Inheritance, Linked list, string, array.. I have only used io package in my progs.. So according to it some progs to test my skill will be welcome.. I have practiced all textbook programs. Any suggestion..?? I need the question only.. Thanks in advance
Liverpool_fan
Dec 22, 2011 at 7:55 PM
Can anyone give me some programs to work on?? I have limited knowledge to Inheritance, Linked list, string, array.. I have only used io package in my progs.. So according to it some progs to test my skill will be welcome.. I have practiced all textbook programs. Any suggestion..?? I need the question only.. Thanks in advance

Project Euler
Piyush
Piyush #393
Dec 31, 2011 at 9:12 PM
need books recommendation for:
Java Advanced
Java SCJP
Prime_Coder
Dec 31, 2011 at 10:57 PM
@ Piyush
The revised edition of the classic "Core Java: Volume II–Advanced Features" , covers advanced user-interface programming and the enterprise features of the Java SE platform.

For SCJP preparation, the best book in my opinion is "SCJP Sun Certified Programmer for Java" by Kathy Sierra and Bert Bates, but don't know how much it will be relevant for the next exam version (Java 7).
Another better option would be "A Programmer's Guide to Java Preparation" by Khalid Mughal and Rolf Rasmussen.
Hope this helps you.
buddyram
buddyram #395
Jan 4, 2012 at 3:42 PM
My java program gets compiled but while running the program i get to see the below error message:


Error Message:
C:\>cd jdk/bin

C:\jdk\bin>javac boxarea.java

C:\jdk\bin>java boxarea
Exception in thread "main" java.lang.NoClassDefFoundError: boxarea (wrong name:
Boxarea)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
2)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

Code:
import java.io.*;

class Box {

double width;

double height;

double length;

void getdata( double x,double y, double z) {

width = x;

height = y;

length = z;

}

double volume( ) {

return(width*height*length);

}

}

class Boxarea {

public static void main(String args[ ]) {

double v1,v2;

Box b1= new Box( );

Box b2 = new Box( );

b1.width=2;

b1.height=4;

b1.length=8;

b2.getdata(5,10,15);

v1=b1.volume();

v2=b2.volume();

System.out.println("The volume1 is = " +v1);

System.out.println("The volume2 is= " +v2);

}

}

I haven't set any path
i am running the program from c:\jdk\bin
S
sakumar79 #396
Jan 4, 2012 at 4:36 PM
I havent touched java programming in years (not a programmer by profession) but dont the variables of a class take private behaviour unless defined specifically as public? Try adding public to length, width and height variable declaration in box class...

Arun
buddyram
buddyram #397
Jan 4, 2012 at 4:44 PM
those variables are accessed by the objects of that particular, so i don't think the access modifiers should be made public.
the problem is in setting the path for the class files, i googled and checked but

set CLASSPATH=.;C:\;
checked the above command but nothing changed!

. . . and moreover if that was the error then it should have shown at compile time
S
sakumar79 #398
Jan 4, 2012 at 9:55 PM
But you are setting b1's variables from outside the Box class (b1.width=2, etc). You can try and see if it helps...

Anyway, its long since I programmed with java, so I will let others more conversant help you out...

Arun
Prime_Coder
Jan 4, 2012 at 10:16 PM
My java program gets compiled but while running the program i get to see the below error message:


Error Message:
C:\>cd jdk/bin

C:\jdk\bin>javac boxarea.java

C:\jdk\bin>java boxarea
Exception in thread "main" java.lang.NoClassDefFoundError: boxarea (wrong name:
Boxarea)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
2)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

Code:
import java.io.*;

class Box {

double width;

double height;

double length;

void getdata( double x,double y, double z) {

width = x;

height = y;

length = z;

}

double volume( ) {

return(width*height*length);

}

}

class Boxarea {

public static void main(String args[ ]) {

double v1,v2;

Box b1= new Box( );

Box b2 = new Box( );

b1.width=2;

b1.height=4;

b1.length=8;

b2.getdata(5,10,15);

v1=b1.volume();

v2=b2.volume();

System.out.println("The volume1 is = " +v1);

System.out.println("The volume2 is= " +v2);

}

}

I haven't set any path
i am running the program from c:\jdk\bin

The program code works well on my system. :razz:
I'm still figuring out what might be the problem at your side.
buddyram
buddyram #400
Jan 4, 2012 at 11:22 PM
@Prime_Coder:
now the program is working fine
OMG, the filename and the classname were not of the same CASE!

after a long time i was working on java, so i couldn't notice this!
one of my friend helped me in sorting out this bug

thanks for your support
Jaskanwar Singh
Feb 5, 2012 at 10:51 PM
why wont this print any value?

Code:
    public static void main(String[] args) {
        // TODO code application logic here
      
        int a = 5, b = 10;
        
        if(a>5)
            if(b>5) {
                System.out.println("b is "+b);
                
            }
        else
                System.out.println("a is "+a);
    }
Liverpool_fan
Feb 5, 2012 at 10:57 PM
Because a = 5 which is not > 5. the Else is rendered as the else of the inside if. Fix your braces.
Jaskanwar Singh
Feb 5, 2012 at 11:11 PM
^braces are like this only in question paper. i ran it in netbeans and it showed this -
run:
BUILD SUCCESSFUL (total time: 1 second)


another question -
answer of p and q -

Code:
 public static void main(String[] args) {
        // TODO code application logic here
      int p,q = 10;
      for(p=1; p<=5; ++p)
       q = p++;
        --q;
    }
dashing.sujay
Feb 5, 2012 at 11:12 PM
why wont this print any value?

Code:
    public static void main(String[] args) {
        // TODO code application logic here
      
        int a = 5, b = 10;
        
        if(a>5)
            if(b>5) {
                System.out.println("b is "+b);
                
            }
        else
                System.out.println("a is "+a);
    }

It is a logical error where compiler is confused about 2nd else.

Write like this- (bold are changes). Now the program prints as expected.


Code:
    public static void main(String[] args) {
        // TODO code application logic here
      
        int a = 5, b = 10;
        
        if(a>5)
[b]{[/b]
            if(b>5) {
                System.out.println("b is "+b);
                
            }
[b]}[/b]
        else
                System.out.println("a is "+a);
    }
Jaskanwar Singh
Feb 5, 2012 at 11:18 PM
thanks sujay, and second question?

@Liverpool_fan
got your point now after reading sujay's post, i was confused, thanks buddy :oops:
vickybat
vickybat #406
Feb 5, 2012 at 11:25 PM
^^ It will only print "a" as a=5 and the logic shows that if (a>5). It will only print the last else statement as the first and 2nd if's are skipped and only else is executed.
dashing.sujay
Feb 5, 2012 at 11:48 PM
thanks sujay, and second question?

@Liverpool_fan
got your point now after reading sujay's post, i was confused, thanks buddy :oops:

p=7 , q=4 , correct?

^^ It will only print "a" as a=5 and the logic shows that if (a>5). It will only print the last else statement as the first and 2nd if's are skipped and only else is executed.

Its isn't printing anything, just compiling. (original code)
dashing.sujay
Feb 6, 2012 at 12:01 AM
Step by step value increment/decrement.

p q

Garbage - 10
1 - 1
2 - do
3 - 3
4 - do
5 - 5
6 - do
7 - 4

If you don't understand any step, then ask. :)
vickybat
vickybat #410
Feb 6, 2012 at 12:15 AM
^^ When p> 5, loop should end right? How did it get to 7??
Jaskanwar Singh
Feb 6, 2012 at 12:16 AM
@dashing.sujay
i didnt understand, how you wrote?
dashing.sujay
Feb 6, 2012 at 12:58 AM
I think you guys are confusing in pre-increment and post-increment operators. Let me explain.
q=p++ means-
=> q=p;
p=p+1;


But if the code would have been-

q=++p

Then it'd work like this-

=> p=p+1;
=> q=p;

TIP: Pre-increment/decrement and post-increment/decrement operators work exactly same when used "stand alone", but not when used with some other parameters, like here.

I'll make you guys understand it by use of while loop, its much easier.

We can convert the given code into while loop as-
Code:
p=1;
while(p<=5)
{
q=p;        //first step of q=p++
p=p+1;    //2nd step of q=p++
++p;
}

Now, see the tracing-

p q

1 1 (initialisation)
3 3 (first iteration)
5 5 (2nd iteration)
7 - (loop ends here by running last line ++p)

Then --q makes q=4 and p=7 already.

Hope this helps :).
vickybat
vickybat #414
Feb 6, 2012 at 9:48 AM
Yup sujay that's correct. I got confused in the last iteration a bit. Yes value of p will increase in the last iteration to 7 and when it again goes into the loop the condition breaks and loop ends.

Yes its, 7 & 4.:)
dashing.sujay
Feb 7, 2012 at 10:39 PM
why wont this print any value?

Code:
    public static void main(String[] args) {
        // TODO code application logic here
      
        int a = 5, b = 10;
        
        if(a>5)
            if(b>5) {
                System.out.println("b is "+b);
                
            }
        else
                System.out.println("a is "+a);
    }

First of all Jas, I'm sorry for my previous answer for the above query, as it was wrong. :oops: I had a feeling that something was missing. Now I got it :).

See, for this I'll explain you behaviour of if.

If, if is used without the braces, it has a behaviour of considering the next line as its body. Now, since the first if in your code is always false, and 2nd if is written just below it, so the first if considers it as its body. The point here to notice is that, a body of a if is considered from first brace to closing brace of else. So, since the first if is false, it ignores the whole part of 2nd if.

The virtual code which appears to compiler- (notice the bold braces)

Code:
    public static void main(String[] args) {
        // TODO code application logic here
      
        int a = 5, b = 10;
        
        if(a>5)
[b]{[/b]                                       //body of first [b]if[/b] starts from here
            if(b>5) {
                System.out.println("b is "+b);
                
            }
        else
                System.out.println("a is "+a);
    }
[b]}[/b]                                     //till here

You can see how 2nd if is ignored completely along with else.

I hope I'm very clear this time. :)
A
Mar 24, 2012 at 9:08 AM
I want a detailed guide on Java right from basics....
My concepts in Cpp are pretty strong...
Suggest a SDK, for both Java n Cpp.
Separate or both in one!!!!
akshaykapoor_3
Mar 24, 2012 at 10:26 AM
I want a detailed guide on Java right from basics....
My concepts in Cpp are pretty strong...
Suggest a SDK, for both Java n Cpp.
Separate or both in one!!!!

For digging deeper into java starting from the basics, I would suggest this book by Cay Horstmann. I have read it and it helps a lot with the fundamentals Java is build upon.

SDK for both Java and Cpp..?? Probably you are asking for a common Integrated Development Environment (IDE). Eclipse will help you with both the platforms (Although, I am not sure if you can handle both the platforms in one installation of Eclipse). Eclipse comes in various variants. For Java, you may go with Eclipse - Helios. Avoid Eclipse Europa and other previous builds.

If you have not setup Java on your machine yet, then you can proceed with Java SDK6 from Sun Microsystem's site. SDK7 has been released but contains lot of bugs. Hope this helps !
coderunknown
Mar 26, 2012 at 3:29 AM
encountering error designing a simple server client program.

original code:
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

class Client extends JFrame implements ActionListener {

    private JTextField txtFile;

    public static void main(String args[]){

        /* Create and display the client form */

        Client clientForm = new Client();
        clientForm.Display();
    }

    public void Display(){

        JFrame frame = new JFrame();
        frame.setTitle("Client");

        FlowLayout layout = new FlowLayout();
        layout.setAlignment(FlowLayout.LEFT);

        JLabel lblFile = new JLabel("Filename:");

        txtFile = new JTextField();
        txtFile.setPreferredSize(new Dimension(150,30));

        JButton btnTransfer = new JButton("Transfer");
        btnTransfer.addActionListener(this);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(layout);
        mainPanel.add(lblFile);
        mainPanel.add(txtFile);
        mainPanel.add(btnTransfer);

        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        /* File Open Dialog box allows the user to select a file */

        JFileChooser fileDlg = new JFileChooser();
        fileDlg.showOpenDialog(this);
        String filename = fileDlg.getSelectedFile().getAbsolutePath();
        txtFile.setText(filename);

        try{

            /* Try to connect to the server on localhost, port 5555 */

            Socket sk = new Socket("192.168.0.11", 5555);
            OutputStream output = sk.getOutputStream();

            /* Send filename to server */

            OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream());
            outputStream.write(fileDlg.getSelectedFile().getName() + "\n");
            outputStream.flush();

            /* Get reponse from server */

            BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));

            String serverStatus = inReader.readLine(); // Read the first line

            /* If server is ready, send the file */

            if ( serverStatus.equals("READY") ){

                FileInputStream file = new FileInputStream(filename);

                byte[] buffer = new byte[sk.getSendBufferSize()];

                int bytesRead = 0;
                long t= System.currentTimeMillis();
                while((bytesRead = file.read(buffer))>0)
                {
                    output.write(buffer,0,bytesRead);

                }
                //long n=System.currentTimeMillis();
                //long d=n-t;


                output.close();
                file.close();
                sk.close();

                //JOptionPane.showMessageDialog(this, "Transfer complete \n Time taken "+d+" Mili-seconds");

            }
        }
        catch (Exception ex){
            /* Catch any errors */
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }
}

modified code:
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

class Tester extends JFrame implements ActionListener
{
	private JTextField txtFile;
	
	public static void main (String[] args)
	{
		Tester mytester = new Tester();
		mytester.display();
	}
	
	public void display()
	{
		JFrame frame = new JFrame();
		frame.setTitle("Download Tester");
	
		FlowLayout layout = new FlowLayout();
		layout.setAlignment(FlowLayout.LEFT);
	
		JLabel lblFile = new JLabel("File:");
	
		txtFile = new JTextField();
		txtFile.setPreferredSize(new Dimension(150,30));
	
		JButton selectbutton = new JButton("Select");
		selectbutton.addActionListener(this);
		
		JButton sendbutton = new JButton("Send");  
		sendbutton.addActionListener(this);
	
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(layout);
		mainPanel.add(lblFile);
		mainPanel.add(txtFile);
		mainPanel.add(selectbutton);
		mainPanel.add(sendbutton);	

		frame.getContentPane().add(mainPanel);
		frame.pack();
		frame.setVisible(true);
	}
	
	public void actionPerformed(ActionEvent event) 
	{
		if(event.getSource()==selectbutton)
		{
			JFileChooser fileDlg = new JFileChooser();
			fileDlg.showOpenDialog(this);
			String filename = fileDlg.getSelectedFile().getAbsolutePath();
			txtFile.setText(filename);
		}
		else
		{
			try
			{
				Socket sk = new Socket("192.168.0.11", 5555);
				OutputStream output = sk.getOutputStream();
			
				OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream());
				outputStream.write(fileDlg.getSelectedFile().getName() + "\n");
				outputStream.flush();
			
				BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
				String serverStatus = inReader.readLine();
			
				if ( serverStatus.equals("READY") )
				{
					FileInputStream file = new FileInputStream(filename);
					byte[] buffer = new byte[sk.getSendBufferSize()];

					int bytesRead = 0;
					long t= System.currentTimeMillis();
					while((bytesRead = file.read(buffer))>0)
					{
						output.write(buffer,0,bytesRead);
					}
					output.close();
					file.close();
					sk.close();
					JOptionPane.showMessageDialog(this, "Transfer complete");
				}
			}
			catch (Exception ex)
			{
				JOptionPane.showMessageDialog(this, ex.getMessage());
			}
		}
	}
}

all i want to do is add a separate SEND button to the uploader. i have placed the file selection and the rest (connect to server, read the file, etc) under an if else condition. so is it limiting the scope?

any help will be highly appreciated.
F
fz8975 #419
Mar 27, 2012 at 12:10 AM
Query :
I want to make a custom exception that will be thrown when an divide by zero is encountered in a 'for' loop which is dividing a variable(initialized by a number) by a random variable (produced by Math.Random()) ??

I declared my exception

class RandomException extends Exception
{

public RandomException(String message) {
super(message);

}
}
But how do i tell the exception that when it is to be thrown ??
akshaykapoor_3
Mar 27, 2012 at 8:50 AM
Query :
I want to make a custom exception that will be thrown when an divide by zero is encountered in a 'for' loop which is dividing a variable(initialized by a number) by a random variable (produced by Math.Random()) ??

May I know why you want to perform this..? Default ArithmeticException doesnt do the job ??

Secondly,

you have used the parent 'Exception' class for extension in order to define your CustomException. However, this is not a good approach as this code will trigger your custom exception for all A-Z exceptions in Java. Instead you should extend only the exception which you want to extend i.e. Arithmetic Exception

But how do i tell the exception that when it is to be thrown ??

For this you can use the 'throw' keyword in Java which will help you invoke a exception as and when you want.


Code:
public class Trial {
	public static void main(String args[]) throws CustomException{
		try{
			//Code that generates Arithmetic division by zero exception
		}
		catch(ArithmeticException e){
			throw new CustomException();
		}
	}
}


class CustomException extends ArithmeticException{
	@Override
	public String getMessage() {
		// return custom message
		return "Division by zero was attempted !! ";
	}
}
F
fz8975 #421
Mar 27, 2012 at 2:50 PM
yes i finally got it last night....
thanks
prateek007391
Mar 29, 2012 at 9:24 PM
Sorry, What a Stupid Mistake I am making
coderunknown
Mar 30, 2012 at 4:07 AM
is there a way to pass a value back to a class or function from an Action Listener?
Neo
Neo #424
Mar 30, 2012 at 9:14 AM
^^can you please explain in detail?
coderunknown
Mar 31, 2012 at 1:03 AM
^^ will PM you soon.
prateek007391
Apr 17, 2012 at 5:41 PM
Please check these codes :

public class Card {

private String face;
private String suit;

public Card(String cardFace, String cardSuit){

cardFace = face;
cardSuit = suit;

}

public String toString(){

return face + " of " + suit;
}
}

Code:
import java.util.Random;

public class DeckOfCards {

	private Card deck[];
	private int currentCard;
	private final int NUMBER_OF_CARDS = 52;
	private Random randomNumber;
	
	public DeckOfCards(){
		
		String faces[] = {"ACE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING"};
		String suits[] = {"HEARTS", "DIMOND", "SPADES", "CLUBS"};
		
		deck = new Card[NUMBER_OF_CARDS];
		
		currentCard = 0;
		randomNumber = new Random();
		
		for(int count = 0; count<deck.length; count++){
			
			deck[ count ] = new Card(faces[ count % 13 ], suits[ count / 13 ]);
		}
		
	}
	
	public void shuffle(){
		
		currentCard = 0;
		
		for(int first = 0; first<deck.length; first++){
			
			int second = randomNumber.nextInt(NUMBER_OF_CARDS);
			
			Card temp = deck[first];
			deck[first] = deck[second];
			deck[second] = temp;
			
		}
	}
	public Card dealCard(){
		
		if(currentCard < deck.length )
			return deck[ currentCard++ ];
		else
			return null;
		}
}

Code:
public class DeckOfCardTest {

	
	public static void main(String[] args) {
		
		DeckOfCards myDeckOfCards = new DeckOfCards();
		myDeckOfCards.shuffle();
		
		
		for(int i = 0; i<13; i++ ){
			
			System.out.printf("%-20s%-20s%-20s%-20s\n", myDeckOfCards.dealCard(), myDeckOfCards.dealCard(),myDeckOfCards.dealCard(),myDeckOfCards.dealCard());
		}
	}

}

The Output must be Different cards but instead I get null of null 53 times.

Please help me, let me know whats wrong.

Sorry, got things Working.

Such a small Mistake and everything messes up.
Faun
Faun #427
Apr 17, 2012 at 8:52 PM
public class Card {

private String face;
private String suit;

public Card(String cardFace, String cardSuit){

cardFace = face;
cardSuit = suit;


}

public String toString(){

return face + " of " + suit;
}
}

highlighted
braindead
braindead #429
May 1, 2012 at 12:30 PM
I just started using netbeans and dont know much about java either.
For the following code it shows "package com.amazonaws does not exist ...."
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
......
i think i have to add libraries or something like that. I have already downloaded aws-java-sdk-1.3.8. how do i add now? help !
Faun
Faun #430
May 1, 2012 at 12:35 PM
^^Should be able to add the jar files into the project
braindead
braindead #431
May 1, 2012 at 11:10 PM
arre batao kaise karein!
masterkd
masterkd #432
May 2, 2012 at 1:32 PM
Download proper .jar file(sorry, don't know which one you need here)..right click on your project..go to properties->java build path->add external jar->select the .jar file->click open and you're done!!
braindead
braindead #433
May 3, 2012 at 1:39 PM
I got the jar files. just don't know how to add.
Properties attached.
Using NetBeans 7.11
G
gopi_vbboy #434
May 3, 2012 at 2:16 PM
What is static branch in a class mean? Like below-



Code:
public class BarcodeEAN128 extends Barcode {

      //some variables decalration

       
         static {              
        final Map m = new HashMap();
         //some processing
           }

}
masterkd
masterkd #435
May 3, 2012 at 4:41 PM
@braindead,
sorry..previous one i posted for eclipse
for netbeans, project properties->libreries->add jar

What is static branch in a class mean? Like below-



Code:
public class BarcodeEAN128 extends Barcode {

      //some variables decalration

       
         static {              
        final Map m = new HashMap();
         //some processing
           }

}

this is static block..codes inside this block will get executed first when the class is loaded!!
braindead
braindead #436
May 5, 2012 at 3:56 AM
^^ tried that , doesnt seem to work.

Now im desperate. Could someone please help me from the start.
Have a bunch of java programs already written in n++.
How do i import all these as a single project to either netbeans or eclipse or any other IDE?
And also add .jar file after that?
Garbage
Garbage #437
May 6, 2012 at 11:10 PM
Including external JARs in a JAR using Netbeans | one.more
utkarsh73
utkarsh73 #438
Jun 11, 2012 at 12:40 PM
I just had an overview of Java and I wanted to learn it thoroughly. So I started with Thinking in Java-3rd Edition HTML version but it is only for upto JDK 1.4. Will it pose any problems if I learn with this book or is it recommended to learn from a book updated with latest JDK??
masterkd
masterkd #439
Jun 12, 2012 at 8:15 AM
start with head first java
then you can go through SCJP kathy sierra
vickybat
vickybat #440
Jun 19, 2012 at 5:24 PM
Guys having trouble providing keyboard input as arguments to a function especially when passing more than 1 argument. Written a java code i procedural style ( without any use of objects) to show if a triangle can be formed when we provide three integer inputs.

The code works flawlessly when manually providing arguments to the method isTriangle.

But when using providing inputs through keyboard , it throws error. Providing the code below:


Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class triangleFormation {
public static boolean isTriangle (int a, int b, int c){
	if (c>a+b || a>b+c || b>a+c ){
		return false;
	} else{
		return true;
	}
}

public static void main (String [] args)throws IOException {
	
   BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	String t = bufferedreader.readLine();
	
    int m = Integer.parseInt(s);
    int n = Integer.parseInt(r);
    int o = Integer.parseInt(t);
	
	
	
	System.out.println("the triangle is " + isTriangle (m,n,o));
}
}

I don't know if the process of providing keyboard input is correct or not. Only thing i found that its a hassle i java or i don't know some basic concepts. Providing inputs was so easy in c++.

Please throw some light into it guys. :)
nbaztec
nbaztec #441
Jun 19, 2012 at 5:45 PM
Guys having trouble providing keyboard input as arguments to a function especially when passing more than 1 argument. Written a java code i procedural style ( without any use of objects) to show if a triangle can be formed when we provide three integer inputs.

The code works flawlessly when manually providing arguments to the method isTriangle.

But when using providing inputs through keyboard , it throws error. Providing the code below:


Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class triangleFormation {
public static boolean isTriangle (int a, int b, int c){
	if (c>a+b || a>b+c || b>a+c ){
		return true;
	} else{
		return false;
	}
}

public static void main (String [] args)throws IOException {
	
   BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	String t = bufferedreader.readLine();
	
    int m = Integer.parseInt(s);
    int n = Integer.parseInt(r);
    int o = Integer.parseInt(t);
	
	
	
	System.out.println("the triangle is " + isTriangle (m,n,o));
}
}

I don't know if the process of providing keyboard input is correct or not. Only thing i found that its a hassle i java or i don't know some basic concepts. Providing inputs was so easy in c++.

Please throw some light into it guys. :)
The code is valid although logic is flawed. You should be returning `false` if `c>a+b || a>b+c || b>a+c`.

How exactly are you providing input? You should input on separate lines.
And catch the exception within main itself. Ignoring it and letting the runtime deal with it (or rather not) is a bad practice.
vickybat
vickybat #442
Jun 19, 2012 at 6:09 PM
The code is valid although logic is flawed. You should be returning `false` if `c>a+b || a>b+c || b>a+c`.

How exactly are you providing input? You should input on separate lines.
And catch the exception within main itself. Ignoring it and letting the runtime deal with it (or rather not) is a bad practice.



If any of the above conditions are satisfied, true should be returned and if not, then false. Code is tested and is working correctly now. Just asking how to enter input values manually through console i.e keyboard input. :neutral:

I didn't get the bold part . Can you plz be a bit clear on that part mate? Besides i'm not much into handling exceptions yet in java. Just want to know how to successfully input through keyboard when passing more than one argument.
nbaztec
nbaztec #443
Jun 19, 2012 at 6:15 PM
Nope mate the logic isn't flawed. See a,b and c are three sides of a triangle and atleast one side should be greater than the sum of the other two sides for a triangle to form.

If any of the above conditions are satisfied, true should be returned and if not, then false. Code is tested and is working correctly. Just asking how to enter input values manually through console i.e keyboard input. :neutral:

I didn't get the bold part . Can you plz be a bit clear on that part mate?

You got it wrong. For a Triangle, the sum of 2 sides is always greater or equal to the 3rd side,
A + B >= C
1,1,10 is not a triangle. Your code says it is.

You just have to input the value on 3 separate lines:
Code:
1 
1
10

and not:
Code:
1 1 10
vickybat
vickybat #444
Jun 19, 2012 at 6:24 PM
^^ Oh got it and fixed the code. Ya i messed up the logic a bit.

But still how to provide the keyboard input. Actually i mean how to directly pass values through keyboard as arguments to the method isTriangle??

Lets say i want to pass 4,6 9. How do i pass that through keyboard to that method?

The above process works for a single argument but not more than that. Am i missing something here? Can you plz show it mate?
skeletor
skeletor #445
Jun 19, 2012 at 6:26 PM
Nope mate the logic isn't flawed. See a,b and c are three sides of a triangle and atleast one side should be greater than the sum of the other two sides for a triangle to form.
nope.

/_______________________\
vickybat
vickybat #446
Jun 19, 2012 at 6:29 PM
^^ Yup i know and its fixed now. :)
nbaztec
nbaztec #447
Jun 19, 2012 at 6:30 PM
^^ Oh got it and fixed the code. Ya i messed up the logic a bit.

But still how to provide the keyboard input. Actually i mean how to directly pass values through keyboard as arguments to the method isTriangle??

Lets say i want to pass 4,6 9. How do i pass that through keyboard to that method?

The above process works for a single argument but not more than that. Am i missing something here? Can you plz show it mate?
Just a bit? Lol :p


As for the input, the code is fine. You just have to run the darn thing and:
input [Enter]
input [Enter]
input [Enter]
[Output]


P.S. On a side note it's a practice to name Classes as a capitalized string.
vickybat
vickybat #448
Jun 19, 2012 at 6:39 PM
Just a bit? Lol :p

My head was screwed up a bit. :grin: Thanks for pointing that out man or i would have been a joke for all elementary school students. :p



As for the input, the code is fine. You just have to run the darn thing and:
input [Enter]
input [Enter]
input [Enter]
[Output]


P.S. On a side note it's a practice to name Classes as a capitalized string.

Buddy this is what i don't understand. In java i guess we can't input like that or atleast i think i don't know how to.

See when you input a single value , java takes only strings and invokes a readline method through a bufferreader object. Then that string has to be converted into an integer and those integers are passed as arguments for a respective method.

It works for a single argument but not for 3 in this case. I'm totally confused.
Can you please show me with proper java syntax?
nbaztec
nbaztec #449
Jun 19, 2012 at 6:42 PM
My head was screwed up a bit. :grin: Thanks for pointing that out man or i would have been a joke for all elementary school students. :p





Buddy this is what i don't understand. In java i guess we can't input like that or atleast i think i don't know how to.

See when you input a single value , java takes only strings and invokes a readline method through a bufferreader object. Then that string has to be converted into an integer and those integers are passed as arguments for a respective method.

It works for a single argument but not for 3 in this case. I'm totally confused.
Can you please show me with proper java syntax?
How are you running the program?
vickybat
vickybat #450
Jun 19, 2012 at 6:51 PM
^^ Hey got it man. I guess you meant to provide one input per line in the console of the ide. Yeah did that and its working. I misunderstood your post a bit.

Thanks a lot mate. I'm using eclipse.

*i.imgur.com/mpZeA.png

I will rename the classes with capitalized strings in my codes.

Following thinkingapjava by Allen B. downy and finding his approach amazing in terms of building codes. Its a free ebook. Heard of him?
nbaztec
nbaztec #451
Jun 19, 2012 at 6:54 PM
^^ Hey got it man. I guess you meant to provide one input per line in the console of the ide. Yeah did that and its working. I misunderstood your post a bit.

Thanks a lot mate. I'm using eclipse.

*i.imgur.com/mpZeA.png

I will rename the classes with capitalized strings in my codes.

Following thinkinginjava by Allen B. downy and finding his approach amazing in terms of building codes. Its a free ebook. Heard of him?

I've never followed any book on anything. So nope.
vickybat
vickybat #452
Jun 21, 2012 at 4:33 PM
Is this method efficient??

Question-Write a recursive method called power that takes a double x
and an integer n and that returns x^n.
Hint: a recursive denition of this operation is x^n = x*x^n-1. Also, remember
that anything raised to the zeroeth power is 1.

Optional challenge: you can make this method more efficient, when n is even,
using x^n = (x^n/2)^2.

My code:

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Power {
public static double power(double x ,int n){
	if (n==0){
		return 1;
	} if (n%2==0){
		double b =Math.pow(n, x);
		return b;
	}else{
		
	 double recurse = power(x,n-1);
	
	return x*recurse;
	}
	}


public static void main (String [] args) throws IOException{
	BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	
	double m = Double.parseDouble(s);
	int p = Integer.parseInt(r);
	
	System.out.println (power (m,p));
}
}

Writing recursive code to compute x^n is easy. But the optional challenge is confusing. Is it okay to provide math methods in the conditional statement or it can be done recursively?

In the above code, if n is even, it invokes the Math.pow method and if odd, invokes power method recursively to get the result. Code is working but is it efficient.

Please provide some comments guys.
nbaztec
nbaztec #453
Jun 21, 2012 at 5:36 PM
Code:
public double power(double x, int n)
{
  if(n == 0)
     return 1;
  else if(n%2 == 0)
    return power(x, n/2)*power(x, n/2);
  else
    return x*power(x,n-1);
}

System.out.println(power(5,6));
vickybat
vickybat #454
Jun 22, 2012 at 2:43 AM
Code:
public double power(double x, int n)
{
  if(n == 0)
     return 1;
  else if(n%2 == 0)
    [B][SIZE="4"]return power(x, n/2)*power(x, n/2);[/SIZE][/B]
  else
    return x*power(x,n-1);
}

System.out.println(power(5,6));

^^ Thanks a lot for your help mate. Yeah that's the recursive logic that i missed out.
Its working now without using any library methods. :)

Analyzed it with stack diagrams. Your input will invoke the first else i.e the power*power method and it will be like power (5,3)*power( 5,3).

Now since n is 3, it skips to the last conditional and recursively computes x*power(x,n-1) and returns 625 for each power (5,3) and finally gives the result. Again thanks a lot mate.



Solved another recursive algorithm and this time its Euclid's recursive algorithm.

Question: The process is based on the observation that, if r is the remainder when a
is divided by b, then the common divisors of a and b are the same as the
common divisors of b and r. Thus we can use the equation
gcd(a, b) = gcd(b, r)
to successively reduce the problem of computing a GCD to the problem of
computing the GCD of smaller and smaller pairs of integers. For example,
gcd(36,20) = gcd(20, 16) = gcd(16, 4) = gcd(4, 0) = 4
implies that the GCD of 36 and 20 is 4. It can be shown that for any two
starting numbers, this repeated reduction eventually produces a pair where the
second number is 0. Then the GCD is the other number in the pair.
Write a method called gcd that takes two integer parameters and that uses
Euclid's algorithm to compute and return the greatest common divisor of the
two numbers.

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Euclid {
public static int gcd (int a, int b){
	
	
			
				int r = a % b;
				if (r == 0){
					
					return b;
				} else {
			      
				int recurse = gcd (b,r);
				
				return recurse;
                  }
			
			
		}


	public static void main (String [] args) throws IOException{
	BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	
	int p = Integer.parseInt(s);
	int q = Integer.parseInt(r);
	System.out.println (gcd(p,q));
	
}
}

Guys is the code efficient or there are better ways?

@nbaztec - Waiting for your reply buddy.:)
nbaztec
nbaztec #455
Jun 22, 2012 at 2:57 PM
Divide and conquer is already pretty optimal (at least in this regard). One thing though, you don't need the value of `recurse` anywhere except returning it, so why not simply return the value from function.

One a side note, If you are trying to learn Java there are better things to do than to solve Euclidean problems. I usually prefer optimized recursions in C/C++ where one can have pointer control to mess around.
vickybat
vickybat #456
Jun 23, 2012 at 1:34 AM
Divide and conquer is already pretty optimal (at least in this regard). One thing though, you don't need the value of `recurse` anywhere except returning it, so why not simply return the value from function.

One a side note, If you are trying to learn Java there are better things to do than to solve Euclidean problems. I usually prefer optimized recursions in C/C++ where one can have pointer control to mess around.

True, but the material i'm following suggests to practice returning variables to better assist in debugging complex codes. So keeping the practice. The above one is a simple one and recurse variable can be omitted
and function returned directly.

Besides i was going through the recursion chapter and thus solved this. Will be moving on to newer problems. :)
nbaztec
nbaztec #457
Jun 23, 2012 at 11:00 AM
True, but the material i'm following suggests to practice returning variables to better assist in debugging complex codes.
You interpreted it wrongly mate.

What the author meant was to `return` values from functions as a means of determining whether the function failed or executed successfully. Take the following pseudo functions:
Code:
void foo(a,b){
    file.open(a);
    file.write(b);
}

int bar(a,b){
    if(file.open(a)){
        if(file.write(b))
             return 0;
        else
             return 1;
    }    
    return 2;
}

You see the difference between the 2 functions? While `foo` has effectively the same function calls within to perform the same task, `bar` makes use of a paradigm called error codes (albeit in a simpler form). So using `bar` you can better debug complex tasks by noting the return value of the it and take suitable action if it's other than a 0 (or any other success value).

While using a modular approach it is best suited to always return status codes from functions, unless it's trivial.

What I meant was to use:
Code:
    /* int recurse = gcd(a,b);
     * return recurse;
     */
    return gcd(a,b);
Piyush
Piyush #458
Jul 6, 2012 at 6:46 PM
first time using Scanner class
getting error
need help
...

Code:
mport java.util.Scanner.*;

public class Calc
{	
	public static void main (String args[]) 
	{	int result,a,b,c;
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter the operation to perform: 1-->+ 2-->- 3-->/ 4-->* ");
		c=scan.nextInt();
		System.out.println("Enter the two numbers: a and b");
		a=scan.nextInt();
		b=scan.nextInt();
		switch(c)
		{	case '1':
			{	result=a+b;
				System.out.println("Result is "+result);
				break;
			}
		
			case '2':
			{	result=a-b;
				System.out.println("Result is "+result);
				break;
			}
			
			case '3':
			{	result=a*b;
				System.out.println("Result is "+result);
				break;
			}
			
			case '4':
			{	result=a/b;
				System.out.println("Result is "+result);
				break;
			}
			
			default:
			{	System.out.println("Wrong operator choice!!!");
				break;
			}
		}
		
	}
}

error
Code:
Calc.java:29: error: cannot find symbol
		Scanner scan=new Scanner(System.in);
		^
  symbol:   class Scanner
  location: class Calc
Calc.java:29: error: cannot find symbol
		Scanner scan=new Scanner(System.in);
		                 ^
  symbol:   class Scanner
  location: class Calc
2 errors
nbaztec
nbaztec #459
Jul 6, 2012 at 6:49 PM
Code:
import java.util.[B]Scanner[/B]
Piyush
Piyush #460
Jul 6, 2012 at 7:31 PM
Code:
import java.util.[B]Scanner[/B]

thanks
logic seems to be flawed somewhere
will fix it later
main thing is i can use Scanner class now :)
S
Sudhir #461
Jul 28, 2012 at 7:56 PM
guys i'm having problem with ActionListener can anyone please tell me some solution!!!
i want to make a calculator using swing!!!

Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
 *
 * @author SudhiR
 */
class Calci implements ActionListener 
{
char op;
    String value="",cv="";
    int ctr=0;
    Double v1,v2,ans;
Frame fr;
MenuBar mBar;
Menu f,e;
MenuItem q,c,p;
JButton num0,num1,num2,num3,num4,num5,num6,num7,num8,num9,bDot,bAdd,bSub,bDiv,bMul,bSqrt,bPer,clear,bCE,back,equals,inv;
TextField txt;
Panel p1,p2,p3,p4,p5;
    
    
Calci(){
    
fr=new Frame("Calculator");
fr.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
txt=new TextField(35);
txt.setText("0");
txt.setEnabled(false);
mBar=new MenuBar();
f=new Menu("File");
e=new Menu("Edit");
q=new MenuItem("Quit");
c=new MenuItem("Copy");
p=new MenuItem("Paste");
num0=new JButton("0");
num1=new JButton("1");
num2=new JButton("2");
num3=new JButton("3");
num4=new JButton("4");
num5=new JButton("5");
num6=new JButton("6");
num7=new JButton("7");
num8=new JButton("8");
num9 =new JButton("9");
bAdd=new JButton("+");
bSub=new JButton("-");
bDiv=new JButton("/");
bMul=new JButton("*");
bSqrt=new JButton("Sqrt");
bPer=new JButton("%");
clear=new JButton("C");
bCE=new JButton("CE");
back=new JButton("BackSpace");
equals=new JButton("=");
bDot=new JButton(".");
inv=new JButton("+/-");
p1=new Panel();
p2=new Panel();
p3=new Panel();
p4=new Panel();
p5=new Panel();
mBar.add(f);
mBar.add(e);
f.add(q);
e.add(c);
e.add(p);

p1.add(back);
p1.add(clear);
p1.add(bCE);

p2.add(num7);
p2.add(num8);
p2.add(num9);
p2.add(bAdd);
p2.add(bMul);

p3.add(num4);
p3.add(num5);
p3.add(num6);
p3.add(bSub);
p3.add(bDiv);

p4.add(num1);
p4.add(num2);
p4.add(num3);
p4.add(bDot);
p4.add(inv);

p5.add(num0);
p5.add(equals);
p5.add(bSqrt);
p5.add(bPer);

p1.setLayout(new GridLayout(1,3,2,2));
p2.setLayout(new GridLayout(1,5,2,2));
p3.setLayout(new GridLayout(1,5,2,2));
p4.setLayout(new GridLayout(1,5,2,2));
p5.setLayout(new GridLayout(1,4,2,2));

fr.setLayout(new GridLayout(6,1));
fr.setMenuBar(mBar);
fr.setResizable(false);
fr.setSize(300,300);

fr.add(txt);
fr.add(p1);
fr.add(p2);
fr.add(p3);
fr.add(p4);
fr.add(p5);
fr.setVisible(true);

}



public void op()
{
num0.addActionlistener(new ActionListener());
num0.addActionlistener(this);
num1.addActionlistener(this);
num2.addActionlistener(this);
num3.addActionlistener(this);
num4.addActionlistener(this);
num5.addActionlistener(this);
num6.addActionlistener(this);
num7.addActionlistener(this);
num8.addActionlistener(this);
num9.addActionlistener(this);
bAdd.addActionlistener(this);
bSub.addActionlistener(this);
bMul.addActionlistener(this);
bDiv.addActionlistener(this);
bSqrt.addActionlistener(this);
bPer.addActionlistener(this);
equals.addActionlistener(this);
clear.addActionlistener(this);
back.addActionlistener(this);
bCE.addActionlistener(this);
inv.addActionlistener(this);
bDot.addActionlistener(this);

q.addActionlistener(this);
c.addActionlistener(this);
p.addActionlistener(this);

}
//Menu Items//

if(ae.getSource()==q)
{
System.exit(0);
}
else if(ae.getSource()==c)
{
cv+=value;
}
else if(ae.getSource()==p)
{
value+=cv;
}

}


m using netbeans 7.2 for this program it'll give an error that class is not abstract so you cannot implements abstract ActionListener!!

after that i'll use notepad to edit it and then wen i'l compile it it'll give 25 ERRORS

cannot find symbol
.addActionListener(this);

please help me !! i'm new to java and m unable to assign actions the GUI i've made!!! please solve my problem!! ASAP!!!
dead.night7
Sep 30, 2012 at 9:22 PM
Did you use an IDE for making this?
Have a look at my program, Simple basic java... May help you in understanding ActionListener

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {

// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.
jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");

// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});

// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});

// Add the buttons to the content pane.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);

// Create a text-based label.
jlab = new JLabel("Press a button.");

// Add the label to the content pane.
jfrm.add(jlab);

// Display the frame.

do u understand this>? Try it by yourself, this is just an elementary program in Swing now there are ways to solve this
A
Anbarasu #463
Nov 10, 2012 at 12:57 PM
Check this code out:
Code:
import java.io.*;

public class FileOps {
public static void main(String args[])
{
    File file = new File(args[0]);
    try
    {
        BufferedReader in = new BufferedReader(new FileReader(file));
        String s;
        s = in.readLine();
        while(s!=null)
        {
            System.out.println("Read " + s);
            s = in.readLine();
        }
        in.close();
    }
    catch(FileNotFoundException e1)
    {
        System.err.println("File Not Found" + file);
    }
    catch(IOException e2)
    {
        e2.printStackTrace();
    }
}
}
Now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FileOps.main(FileOps.java:13)
Java Result: 1
"
What's the solution? :confused:
try below program execution
java FileOps filename
utkarsh73
utkarsh73 #464
Dec 11, 2012 at 1:33 AM
I see these two very different ways of creating a new thread in Java:

1) We 'extend' the 'Thread' class and override its 'run()' method in the subclass:

Code:
class NewThread extends Thread{
     public void run(){
          System.out.println("Child Thread!");
     }
}
class ThreadTest{
     public static void main(String args[]){
          NewThread nt = new NewThread();
          nt.start();
          System.out.println("Main Thread!");
      }
}

2) And this one 'implements' the 'Runnable' interface and I cannot understand what is actually happening in the first two lines of 'main' method. Please explain this.

Code:
class NewThread implements Runnable{
		public void run(){
			System.out.println("Child Thread!");
		}
}
public class ThreadTest {
	public static void main(String args[]){
		[I]Runnable threadJob = new NewThread();
		Thread nt = new Thread(threadJob);[/I]
		nt.start();
		System.out.println("Main thread");
	}

}

Now, which method is recommended from the above two?? And why??
furious_gamer
Dec 11, 2012 at 11:04 AM
^^

# If you extends Thread class, after that you can’t extend any other class.
# If you implements Runnable, you can extend any other class, which is quite neat.

But on the other hand,

# If you extends Thread class, each of your thread creates unique object and associate with it.
# If you implements Runnable, it shares the same object to multiple threads.

So it is upto you to choose between the two.
utkarsh73
utkarsh73 #466
Dec 11, 2012 at 4:23 PM
Ok, I get it.
But this part I don't understand.
^^
But on the other hand,

# If you extends Thread class, each of your thread creates unique object and associate with it.
# If you implements Runnable, it shares the same object to multiple threads.

what unique objects are u saying?? I have no idea what this means.
vickybat
vickybat #467
Dec 11, 2012 at 5:26 PM
I see these two very different ways of creating a new thread in Java:

1) We 'extend' the 'Thread' class and override its 'run()' method in the subclass:

Code:
class NewThread extends Thread{
     public void run(){
          System.out.println("Child Thread!");
     }
}
class ThreadTest{
     public static void main(String args[]){
          NewThread nt = new NewThread();
          nt.start();
          System.out.println("Main Thread!");
      }
}

2) And this one 'implements' the 'Runnable' interface and I cannot understand what is actually happening in the first two lines of 'main' method. Please explain this.

Code:
class NewThread implements Runnable{
		public void run(){
			System.out.println("Child Thread!");
		}
}
public class ThreadTest {
	public static void main(String args[]){
		[I]Runnable threadJob = new NewThread();
		Thread nt = new Thread(threadJob);[/I]
		nt.start();
		System.out.println("Main thread");
	}

}

Now, which method is recommended from the above two?? And why??

Now read the following carefully mate:

1.
In the first code, NewThread is the subclass of Thread. Since you haven't described the thread class and its methods, i assume it contains the run method which
you're overriding. You can also declare the concrete run method in NewThread even if its not present in Thread class. In ThreadTest class, you declare the main method, create Newthread object with a reference nt and at the same time, invoking the NewThread() constructor ( default or self defined).

Since you have extended Thread class with NewThread, the reference, nt can be used to invoke methods from Thread class which i assume to be start(). It then finally prints "MainThread!".

2.

Second code brings multiple inheritance to the picture and this is where interface is needed. If you want the subclass to contain specific methods which you do not need to inherit from a parent class, you define interface which contains abstract methods unique to a particular functionality. You have to override these methods in the subclass that implements the interface.

In the code, the same NewThread subclass that extends Thread also implements Runnable. It actually overrides the run() method defined as abstract in Runnable interface and should not be present in Thread class. In the main method of Threadtest class, two objects are created with references instantiating the respective constructors. Reference thread job is passed as an argument to the Thread constructor ( why it's so hasn't been described in your code but it clears that the Thread constructor is not default but self defined).

Finally nt object reference invokes the start() method ( what this does hasn't been defined in the code) and then finally prints "Main Thread!".




If you don't understand any specific part, do let us know mate. And if possible, post the entire code.

You need to have a fair idea on constructors, polymorphism and multiple inheritance to understand interfaces. :)
furious_gamer
Dec 11, 2012 at 5:27 PM
Ok, I get it.
But this part I don't understand.


what unique objects are u saying?? I have no idea what this means.

It explains clearly, that if you create new Thread, it means it is creating unique object for that. But for Runnable, this is not the case, It may share same instance for multiple threads.
vickybat
vickybat #469
Dec 11, 2012 at 6:07 PM
Runnable has no constructor as its an interface. It can't be instantiated and thus has no unique instances.
utkarsh73
utkarsh73 #470
Dec 11, 2012 at 6:38 PM
In the code, the same NewThread subclass that extends Thread also implements Runnable. It actually overrides the run() method defined as abstract in Runnable interface and should not be present in Thread class.

The two codes are completely separate from each other. The 'run()' method in the second code actually provides the definition of the abstract method 'run()' declared in the Runnable interface(Inbuilt interface java.lang.Runnable).

Reference thread job is passed as an argument to the Thread constructor ( why it's so hasn't been described in your code but it clears that the Thread constructor is not default but self defined).

threadJob reference is passed as an argument to the java.lang.Thread class's constructor of type "Thread(<Runnable target>)". Its predefined constructor.

Finally nt object reference invokes the start() method ( what this does hasn't been defined in the code) and then finally prints "Main Thread!".

Again, start() method is predefined in the Thread class(java.lang.Thread) which invokes the run() method as per its definition.

Runnable has no constructor as its an interface. It can't be instantiated and thus has no unique instances.

Yeah, Runnable interface does not have any constructor but in the statement "Runnable threadJob = new NewThread();" NewThread class's constructor is invoked not Runnable's.

I understand polymorphism and interfaces, I only wanted to understand the concept behind thread creation in the second code.

It explains clearly, that if you create new Thread, it means it is creating unique object for that. But for Runnable, this is not the case, It may share same instance for multiple threads.

Ok. Now I get it. By extending Thread, each new thread creates a different object of NewThread. But if we use Runnable, only one instance of NewThread is created and shared.
Thanks.
A
Dec 27, 2012 at 10:39 AM
requirement to run J2EE programs..?
furious_gamer
Dec 27, 2012 at 11:05 AM
1. You need to learn Java
2. You need to learn J2EE Architecture
3. Google "How to run JSP/Servlet in Windows/Linux machine"
A
Dec 28, 2012 at 11:19 AM
i want to learn reflection in java
vickybat
vickybat #474
Jan 1, 2013 at 3:50 PM
Guys facing a bit of problem implementing listener. In my case, i'm invoking ActionListener and adding it to the list through a button reference variable and passing (this) as argument.
But the compiler throws an error in the listener segment. Posting the code below. Need a bit of help here guys.

Code:
 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GuiTest {

	JFrame frame;
	
    public static void main (String [] args){
    	GuiTest gui = new GuiTest() ;
    	try {
    	gui.go();
    	}catch (ClassCastException ex){
        	ex.printStackTrace();
        }
    }
    
    public void go (){
    	frame = new JFrame ();
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	
    	JButton button = new JButton ("Test Colour");
    	[B]button.addActionListener(this);[/B]
    	
    	DrawPanel panel = new DrawPanel();
    	
    	frame.getContentPane().add(BorderLayout.SOUTH,button);
    	frame.getContentPane().add(BorderLayout.CENTER,panel);
    	frame. setSize(300,300);
    	frame.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent event){
    	frame.repaint();
    }
}

class DrawPanel extends JPanel{
	
	public void PaintComponent(Graphics g){
		
		g.fillRect (0,0,this.getWidth(),this.getHeight());
		int red = (int)(Math.random()*255);
		int blue= (int)(Math.random()*255);
		int green = (int)Math.random()*255;
		
		Color randomColor = new Color(red,green,blue);
		g.setColor(randomColor);
		g.fillOval(70, 70, 100, 100);
	}
}

Guys need a quick help on this. Though i find the syntax for registering the listener with a widget correct, the compiler throws an error.
I'm using eclipse juno. Need a quick help guys!!!!

Found the problem. I forget to implement the ActionListener interface in GuiTest class. Its working now. :)
bijay_ps
bijay_ps #475
Feb 1, 2013 at 11:53 AM
Q1) why in this case when I am declaring a static variable as final also in Hello class then the static block is not getting processed?
class Hello{
static int a=10;
static{
System.out.println("SB in Hello class");
}
{
System.out.println("IB in Hello class");
}
}
class Test32{
public static void main(String[] args){
System.out.println(Hello.a);
}
}
And if I don't declare it as final, but only static then the static block is getting processed. Can anyone explain why is it happening??

Q2) what is the difference between following two programs? (Both will compile fine, but difference comes when you try to run it. Plz explain)
1)
class Test31{
Test31 obj1=new Test31();
public static void main(String[] args){
Test31 obj2=new Test31();
}
}
2)
class Test31{
static Test31 obj1=new Test31();
public static void main(String[] args){
Test31 obj2=new Test31();
}
}
dashing.sujay
Feb 7, 2013 at 9:00 PM
Any good book for advanced java ?
F
fz8975 #477
Feb 7, 2013 at 9:54 PM
I Used Core Servlets and JSP by Marty Hall and Larry Brown for AJAVA (for first Internal exam),
any good book for java rmi ?
vickybat
vickybat #478
Feb 7, 2013 at 11:35 PM
Any good book for advanced java ?

Are you comfortable with all fundamentals? If not, then head first java period.
Read Bruce Eckell's "Thinking In Java" as a 2nd text book.

Complete reference (java) by Herbert Schildt as reference.

For advanced java, read "SCJP Sun Certified Programmer for Java 5" by Kathy Sierra and Bert Bates ( writers of head first java and head first series creators).
dashing.sujay
Feb 7, 2013 at 11:59 PM
Are you comfortable with all fundamentals? If not, then head first java period.
Read Bruce Eckell's "Thinking In Java" as a 2nd text book.

Complete reference (java) by Herbert Schildt as reference.

For advanced java, read "SCJP Sun Certified Programmer for Java 5" by Kathy Sierra and Bert Bates ( writers of head first java and head first series creators).

Actually it was for a friend and since I've no idea about java, so I asked. He mainly wants to cover EE topics namely servlet, and whatever they are. Anyways thanks for suggestions, I'll let him know.
vickybat
vickybat #480
Feb 8, 2013 at 12:11 AM
Actually it was for a friend and since I've no idea about java, so I asked. He mainly wants to cover EE topics namely servlet, and whatever they are. Anyways thanks for suggestions, I'll let him know.

If he wants to know about servlets and jsp, then get the following:

Head First Labs from O'Reilly Media, Inc. :: Head First Servlets & JSP, Second Edition
bijay_ps
bijay_ps #481
Mar 16, 2013 at 11:28 PM
public class Test{

//1. Test obj1=new Test();

Test(){}

public static void main(String[] args){

//2. Test obj2=new Test();
}
}

In this prgm if U'll write either only the stmnt 1 or stmnt 2 (those whic I have commented and mentioned as 1 and 2) then it'll work fine no compilation error n no runtime error. BUT IF U'll WRITE BOTH OF THEM THEN ITS A RUNTIME ERROR.
Now don't ask me whats the error just see for Urself. I jst wanna knw wats the rsn for this?
F
fz8975 #482
Mar 16, 2013 at 11:45 PM
maybe its a recursive code thats why..!!
RBX
RBX #483
Jun 2, 2013 at 6:31 PM
I have a class LinkedList (members: data, next, and a lot of methods). I want to implement a Stack class as an extension to LinkedList but actually with much limited functionality; I can't reduce the visibility of the methods I don't want, what can be done to make them inaccessible ?

Also, what should be the visibility of data, next in LinkedList ? I currently have them private, but want them to be inherited by subclasses, and don't want the data, and next to be modified by a class using a LinkedList object only by the public methods provided. I am looking at the protected modifier, with the possibility that LinkedList may be extended in other packages, but since I can't reduce the visibility of a member by inheriting it, if a class in other package extends it, the members remain protected in it too, and the members will be freely accessible through the whole package ?

I'd also like to talk about the assumptions made here, correct me if I'm wrong. I am developing this package, so all the classes (LinkedList, Stack etc.) will be developed by me, or are there ways someone else could extend the package ?

I have more things to ask, but it seems I'm too confused right now, it would be great if someone also posts a link with examples on inter-package inheritance, displaying how an object's members are accessed by subclass of its class, and other classes that are not the subclasses of that object's class.

EDIT:
After doing some tests, here are my results *i.imgur.com/19uQkCw.png
(Directed links denote parent to child relationship, green = visible, red = not visible)
What would be the visibility of 'b' in class E ? It can be inherited by F, but not used in F - that makes it neither of default, private, protected.
Z
Jul 18, 2013 at 3:05 AM
I want to learn jQuery...?
Z
Jul 28, 2013 at 4:03 AM
Java has very hard query
ariftwister
Aug 18, 2013 at 1:55 PM
Friends I need your help to write a java program. It's okay, If you could provide me code/logic to this problem.
" A group of character is get from user and stored in an array. Another variable "distance" is also get from user. Now if the distance is 3, then each of the character is changed to its next 3rd letter.
For example a->d,b->e,c->f.....w->z,x->a,y->b,z->c.
Can you help me guys?
harshilsharma63
Aug 19, 2013 at 5:38 AM
Hint: characters are represented by their ASCII values.
abhidev
abhidev #492
Aug 19, 2013 at 8:13 AM
Friends I need your help to write a java program. It's okay, If you could provide me code/logic to this problem.
" A group of character is get from user and stored in an array. Another variable "distance" is also get from user. Now if the distance is 3, then each of the character is changed to its next 3rd letter.
For example a->d,b->e,c->f.....w->z,x->a,y->b,z->c.
Can you help me guys?

Use the ASCII values to find the characters based on the distance as @harshil said
ariftwister
Aug 19, 2013 at 4:19 PM
Guys.. Got it.. Thanks for your help !!

for(i=0;i90)
a=a-26;
}
Edit: Nope the above code isn't right.
Actual code contains type conversion
abhidev
abhidev #494
Jan 8, 2014 at 4:38 PM
This is a java queries section and not Javascript... There must be a different thread for Javascript queries :)
furious_gamer
Jan 8, 2014 at 5:08 PM
^^ Who asked Javascript queries here?
abhidev
abhidev #496
Jan 8, 2014 at 6:26 PM
@piyush deleted the post :D
abhidev
abhidev #498
Jan 8, 2014 at 7:15 PM
Hehe... Well it worked :p
Piyush
Piyush #499
Feb 6, 2014 at 12:07 PM
Hi I am creating a file upload and download form via JSP. Its all working fine, I can upload small files, can create and fetch download for that particular file and delete the file if required. Now the problem is, suppose 2 users are using my app. User A uploaded a file named file.txt. Sometime later User B also uploaded the file named file.txt. Now the previous file will get overwrite. I dont want a popup box which will alert the User B that a file of that name already exists. Instead I want a folder to be created for each user so that they have their files stored on server side in their named folder.
Code:
saveFile="C:/temp/"+saveFile;
I need to modify this line of code I think.
vickybat
vickybat #500
Feb 6, 2014 at 1:15 PM
@piyush

So did you manage to do the xml part for uploading and downloading? I posted about that in the html/javascript thread.

About this one, how will you distinguish users? You can't distinguish users unless you support login.
For this one, you need sessions. Like i said, you need to do some reading on these.

Sessions allow a particular instance of server, to recognize a particular client/browser request. This is achieved through "Cookies" or "URL Rewriting".

So for a particular session, you can prompt the user to create a directory where their respective files go.

I don't know, but i think there should be a respective file server for this. What exactly you are developing?
From the looks of this, i figure its an end to end J2EE project than simple web front end designing.
Piyush
Piyush #501
Feb 6, 2014 at 1:48 PM
Yup I did the XML part. Sorry that I didnt replied to that post since I was stuck on this issue.

And again, my bad, for not explaining the complete scenario. So here it is:

Our group is making a complaint mgmt system based on jsp/jquery and oracle db. We have already done the login / session part. My task was to allow files to get uploaded to the server, which later can be viewed/delete by the admin. So we were discussing that what we can do is, when a remote user clicks on "upload" button to upload a file, a folder should be created on our machine with his name and the file should go there.
This way we can maintain a clean record of all the files from various users. And just to mention, all users have different names, that we have checked since we already have the complete db of the users name and related info.

----------------------------------------------------------------
I searched a bit . There's a method mkdir() in java which can create a folder. Can this help me?
vickybat
vickybat #502
Feb 6, 2014 at 2:00 PM
^^ You can achieve this using regular file handling in java.

A little google gave me this:

jsp - how to create a folder in tomcat webserver using java program? - Stack Overflow

I think you can figure out from here.
Piyush
Piyush #503
Feb 6, 2014 at 2:02 PM
Thanks man I'll post here when I complete this task
Just one more query. I'm using Tomcat 6.0.35 I think. There wont be much difference na between my tomcat and that guy's 7.0 version?
furious_gamer
Feb 6, 2014 at 2:08 PM
Thanks man I'll post here when I complete this task
Just one more query. I'm using Tomcat 6.0.35 I think. There wont be much difference na between my tomcat and that guy's 7.0 version?

If there is any version-specific thing he did, it may be an issue. Otherwise no issues....

Thanks man I'll post here when I complete this task
Just one more query. I'm using Tomcat 6.0.35 I think. There wont be much difference na between my tomcat and that guy's 7.0 version?

If there is any version-specific thing he did, it may be an issue. Otherwise no issues....
Piyush
Piyush #505
Feb 6, 2014 at 2:26 PM
Ok I'l try first..
Piyush
Piyush #506
Feb 11, 2014 at 3:15 PM
Back again. Did some part, stuck on some.
I'm able to upload file and save it in a folder. Connected the code with database . But the thing is, I'm confused now.
I am not aware of the methods/classes which can be helpful in creating folder dynamically according to the name stored in db/ user name of the user uploading at remote machine.

So I'l explain again my sequence of tasks:

1. User clicks on upload button (user on a remote machine using app on our server)
2. Uploads the file and gets the message of successful upload.
3. At our side, a folder is created with his name and his file is saved in the folder. (Note: We have lists of users who will be using app, so that means we do have the usernames/userid)

Till now I'm only able to finish 2 steps, last step is bugging me since 3 days now.

Update:
Found a other way out. I just appended the current date-time before the file name so as to maintain unique file names . Was so depressed (in IT lingo) :evil:
furious_gamer
Feb 11, 2014 at 3:58 PM
Instead of giving user names as folder names, you better hash his name, get some random code like md5. This way folder names will be unique and safe. Only way you can access the folder is, again hash the name with md5.
Piyush
Piyush #508
Feb 11, 2014 at 4:04 PM
Instead of giving user names as folder names, you better hash his name, get some random code like md5. This way folder names will be unique and safe. Only way you can access the folder is, again hash the name with md5.
I dont know how to implement hash codes.
Also, again back to the square one. We have to implement this with the help of separate folders instead of appending date and time.

Thing is, our Director sir wants it this way because, we will be able to easily check and maintain the uploaded attachments. Separate folders for different labs will be helpful when there are like 56 labs. So ya, I agree on their opinion.

So guys..... guide.
furious_gamer
Feb 11, 2014 at 5:41 PM
That is what i am telling..

For ex, you have 56 labs with name like lab1,lab2 .... etc

So, hash the string "lab1" will give you something like 109kajskjaw9uwqsjjs9i. And goes on for lab2, lab3 etc.

So next time, you want to access lab14 folder, all you need to do is, hash the lab14 again with one-way hashing and voila, you have the folder name. Got it?
Piyush
Piyush #510
Feb 11, 2014 at 7:08 PM
That is what i am telling..

For ex, you have 56 labs with name like lab1,lab2 .... etc

So, hash the string "lab1" will give you something like 109kajskjaw9uwqsjjs9i. And goes on for lab2, lab3 etc.

So next time, you want to access lab14 folder, all you need to do is, hash the lab14 again with one-way hashing and voila, you have the folder name. Got it?

Oh you mean that hash will give each lab a certain unique ID which can be used to get the lab name itself? It sounds good, but I have no idea how will I implement it (will have to learn) and whether it will be easy to implement it.
furious_gamer
Feb 12, 2014 at 10:57 AM
See this link : Java MD5 Hashing Example

There, you pass the labname and it will give md5 digest. And you create folder with the obtained digest.
Piyush
Piyush #512
Feb 14, 2014 at 10:02 AM
I was not able to implement it properly so left it.
Anyway, my problem is all fixed now.

New task:
I want to restrict the file type when uploading, like only pdf/txt/rtf/jpg files.
I cant use "accept" attribute since there will be many people who must be having IE 7/8/9. So I need other way out.
furious_gamer
Feb 14, 2014 at 10:55 AM
^^ You can do it at client-side. You can read the file name from file-input field. Check last "." and get the extension. After that, put an conditional statement and restrict.

Example Link : SOF
Piyush
Piyush #514
Feb 14, 2014 at 11:04 AM
Worked flawlessly. Thanks :)
Piyush
Piyush #516
Feb 14, 2014 at 11:20 AM
One more:

I want to set a session expiry condition. And I want to do it via jsp only.
I searched a bit but Filter class was the only solution I found but it needs a proper servlet which I dont wanna do.
Anything there to help here via JSP?
furious_gamer
Feb 14, 2014 at 11:34 AM
Always the best way to keep session expiry part, is Servlet. You can do simple session expiry condition on top of JSP page.

Ex :

if(session.getAttribute("userid")==null)
out.print("Session expired");
else {
// The whole JSP content goes here....
}

OR

if(session.getAttribute("userid")==null) {
//Redirect to any page you want.
}

But seriously, go with Servlet and Filter.
Piyush
Piyush #518
Feb 14, 2014 at 2:42 PM
Hmm... I'll try then.
Harsh Pranami
Feb 15, 2014 at 5:09 PM
So what is the best way to learn java from scratch?? I'm pretty much aware of C and C++.
harshilsharma63
Feb 15, 2014 at 5:46 PM
So what is the best way to learn java from scratch?? I'm pretty much aware of C and C++.

I'm reading Java The Complete Reference and it's good. If you have enough programming practice, you'll only need to know that are exclusive to Java are are handled in a different way in Java.
furious_gamer
Feb 17, 2014 at 10:54 AM
So what is the best way to learn java from scratch?? I'm pretty much aware of C and C++.

Head First Java is another fun way to learn Java. The Complete Reference will be useful read if you finish the Head First.
ariftwister
Mar 13, 2014 at 8:27 PM
Hey Guys I am Developing an Android App to Show Local Bus Schedule. And I get a little trouble in executing specific queries.

The Below SQL query Works well in sqlite browser as i want

Code:
SELECT * FROM pnotocdm WHERE time > time('now','localtime') LIMIT 4;
* pnotocdm is the table name
* time is column name
* time('now','localtime') is the function to get current time in local time format.



However when i convert this sql query to Java rawquery() it does not return the result i want. Any help ?

PS- I stored time column values with only hour and minutes.
ariftwister
Mar 18, 2014 at 12:54 AM
^ Solved it by myself.. Btw got another question..
How to convert the 24 hour format time to 12 hour format time
furious_gamer
Mar 18, 2014 at 11:26 AM
^^ Try this :

String s = "12:18:00";
DateFormat f1 = new SimpleDateFormat("hh:mm:ss");
Date d = f1.parse(s);
DateFormat f2 = new SimpleDateFormat("h:mma");
f2.format(d).toLowerCase();
ariftwister
Mar 19, 2014 at 12:45 AM
Btw I forgot to mention that I want to convert time which is a cursor object. So how to convert the cursor object?
D
daljit #527
May 24, 2014 at 7:17 PM
i don't know its right place what i want to create a gui to perform various action in windows..like to disable USBstor from reg, create a administrator account, disabling builttin administrator, disabling some services...i want to perform all these with a single click....can anybody help me..thanks in advance and sorry for my comn skill
harshilsharma63
May 24, 2014 at 9:03 PM
To create GUI in Java you either need to use AWT or Swing. As Swing is derived from AWT and contains much more features, you should use that instead. You can either parametrically create GUI or use NetBeans' quick GUI builder.
true_lies
true_lies #529
Jul 1, 2014 at 5:30 PM
Started Android Programming, and was going through a few example codes, and making some of my own.
In this i'm trying to display the analog clock showing the current time with a toggle button.
Getting this error in MainActivity... (marked with #)
Multiple markers at this line
- Syntax error on token ")", ;
expected
- Syntax error on token "(", ;
expected

MainActivity.java
Code:
package com.example.toggleclock;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		final AnalogClock clock = (AnalogClock) findViewById(R.id.AnalogClock);
		ToggleButton toggle = (ToggleButton) findViewById(R.id.ToggleButton);
		
		toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
		    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		        
		    	if (isChecked) { 
		        	@Override
#	            public void onClick(View v) {
	                clock.setVisibility(View.VISIBLE);
	            }
		    	}
				else {
					@Override
#	            public void onClick(View v) {
	                clock.setVisibility(View.INVISIBLE);
				}
				}
		    }
		});
	}
}

activity_main.xml
Code:
<RelativeLayout xmlns:android="*schemas.android.com/apk/res/android"
    xmlns:tools="*schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}" >

    <ToggleButton
        android:id="@+id/ToggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textOn="@string/on"
        android:textOff="@string/off"
        android:checked="true" />

    <AnalogClock
        android:id="@+id/AnalogClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ToggleButton"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Again, pretty much new to Android programming. Let me know if something wrong with the code or any changes.
S
sarita95 #530
Jul 20, 2014 at 12:46 PM
Which is the best compiler for JAVA? I am currently compiling and running JAVA programs form cmd, but I would like to know which one is the best compiler for JAVA just like we have TurboC and others for C/C++.
A
Aug 20, 2014 at 7:53 AM
I have installed the jdk1.8.0_11 I also get the verification that the software is installed successfully. I am using the book "CORE JAVA Volume 1 - Fundamentals" 9th edition written by Cay S. Horstmann, Gary Cornell. In this book they have said to make a directory by using the command "mkdir src". Every thing is fine uptil C:\Program Files\Java\jdk1.8.0_11\bin But after this when I use the command "mkdir src" I get the following error "Access Denied". I have set the path correctly. Please help. I am sorry if I have posted the question in the wrong thread. But I am new to programming. Thank you
harshilsharma63
Aug 20, 2014 at 4:04 PM
I have installed the jdk1.8.0_11 I also get the verification that the software is installed successfully. I am using the book "CORE JAVA Volume 1 - Fundamentals" 9th edition written by Cay S. Horstmann, Gary Cornell. In this book they have said to make a directory by using the command "mkdir src". Every thing is fine uptil C:\Program Files\Java\jdk1.8.0_11\bin But after this when I use the command "mkdir src" I get the following error "Access Denied". I have set the path correctly. Please help. I am sorry if I have posted the question in the wrong thread. But I am new to programming. Thank you

This problem is not related to Java, rather to permission settings. You need Admin provilages to modify the files and folders in certain locations like C:\Program Files, C:\Windows, etc. When you ran the command you were most probably in C:\program Files and you were working on a non-elevated command prompt (cmd run without admin privileges) which gave the error on trying to create a new dir there.

I'd recommend creating your Java source files in some other locations like Documents. Or if you necessarily need to create dir in that path then run cmd with admin rights by right clicking on it and choosing "Run as Administrator".
A
Aug 21, 2014 at 8:27 AM
Thank you Harshil, It worked. This was my first post ever uptil now.
tkin
tkin #534
Aug 23, 2014 at 8:44 PM
I have installed the jdk1.8.0_11 I also get the verification that the software is installed successfully. I am using the book "CORE JAVA Volume 1 - Fundamentals" 9th edition written by Cay S. Horstmann, Gary Cornell. In this book they have said to make a directory by using the command "mkdir src". Every thing is fine uptil C:\Program Files\Java\jdk1.8.0_11\bin But after this when I use the command "mkdir src" I get the following error "Access Denied". I have set the path correctly. Please help. I am sorry if I have posted the question in the wrong thread. But I am new to programming. Thank you
Get Eclipse Luna, it takes 5 mins to setup, and then code away, luna supports java 8. Also if you need to learn J2EE, just get TomEE. Coding via notepad is not a a very good way at all, you need to debug your code, see the console, use an IDE.

Also note, if you are new to JAVA altogether please get this book, this is the best book to learn JAVA: SCJP Sun Certified Programmer for Java 6 Study Exam 310-065 Guide (With CD-ROM) (English) 1st Edition - Buy SCJP Sun Certified Programmer for Java 6 Study Exam 310-065 Guide (With CD-ROM) (English) 1st Edition by Sierra, Kathy|Author; Bates, Bert|Aut

- - - Updated - - -

On a side note: Can anyone suggest me some good resources or books to learn Java 8(only new features), specially the lambda functions.
vickybat
vickybat #535
Aug 24, 2014 at 1:15 PM
@Tkin

Hello my friend.:)

I'm a huge fan of cay horstmann. Try this for java 8 - Buy Java SE 8 for the Really Impatient Book Online at Low Prices in India | Java SE 8 for the Really Impatient Reviews & Ratings - Amazon.in

Their Core series act has a very good reference. So i suggest you to try this.

Btw buddy i don't recommend the scjp book by sierra and bates to a newbie into the world of java. I would suggest their head first book to absolute beginners.
tkin
tkin #536
Aug 24, 2014 at 10:01 PM
@Tkin

Hello my friend.:)

I'm a huge fan of cay horstmann. Try this for java 8 - Buy Java SE 8 for the Really Impatient Book Online at Low Prices in India | Java SE 8 for the Really Impatient Reviews & Ratings - Amazon.in

Their Core series act has a very good reference. So i suggest you to try this.

Btw buddy i don't recommend the scjp book by sierra and bates to a newbie into the world of java. I would suggest their head first book to absolute beginners.
Thanks, is there any local edition available? The price is out of my range.
vickybat
vickybat #537
Aug 25, 2014 at 5:20 PM
Thanks, is there any local edition available? The price is out of my range.

Yes

Java SE 8 for the Really Impatient (English) 1st Edition - Buy Java SE 8 for the Really Impatient (English) 1st Edition by Horstmann Online at Best Prices in India - Flipkart.com

Even i'm thinking of getting it.
abhigeek
abhigeek #538
Nov 30, 2014 at 8:39 PM
There is any site like codecademy for Java ? where I can learn Java interactively doing coding.

- - - Updated - - -

Anybody? [MENTION=47611]furious_gamer[/MENTION] [MENTION=10170]JGuru[/MENTION]
furious_gamer
Nov 30, 2014 at 10:00 PM
^^ Did you checked these?

Link1

Link 2
RBX
RBX #540
Dec 1, 2014 at 8:27 AM
^^ Did you checked these?

Link1

Link 2

If these websites allow only the compilation, then I'd like to suggest koding.com
It gives you a VM, and you can install whichever compiler you like, save the code, resume from anywhere. It used to be bad, but when I used it recently, I found it delighting.
thetechfreak
Dec 1, 2014 at 11:48 AM
There is any site like codecademy for Java ? where I can learn Java interactively doing coding.

- - - Updated - - -

Anybody? [MENTION=47611]furious_gamer[/MENTION] [MENTION=10170]JGuru[/MENTION]
Courses on coursera and edX are actually quite good. You should try those when they start.
abhigeek
abhigeek #542
Dec 1, 2014 at 2:20 PM
^^ Did you checked these?

Link1

Link 2

Most of courses are totally for beginners like explaining concept of if/else, array etc. I don't want that cause i'm shifting from C/C++.
furious_gamer
Dec 1, 2014 at 3:12 PM
Most of courses are totally for beginners like explaining concept of if/else, array etc. I don't want that cause i'm shifting from C/C++.

I thought you wanted to do Java Coding online while learning. Silly me... I learn java by reading Head First and I suggest you do the same.
J
jacobsons #544
Dec 14, 2014 at 3:46 PM
Hi Furious Gamer,

You can try here to solve your problem I hope you will get better solution here Brave Little Coder | Learn how to program in C# and Java
abhigeek
abhigeek #545
Jan 14, 2015 at 7:37 PM
Code:
public class test implements Runnable{
            public void run(){
            for(int i=1;i<6;i++){
                System.out.println(" "+i);
                try{
                    Thread.sleep(500);
                }catch(InterruptedException E){
                    System.out.println("Thread Interrupted");
                }
                
            }
            System.out.println("Run one is terminated");
        }


    public static void main(String agrs[]){
    test obj = new test();
    Thread objT = new Thread(obj);
    objT.start();
    try{
    objT.join(); 
    }
    catch(InterruptedException e){
        
    }
    System.out.println("Main one is terminated");
    }
    
}

I'm don't get these two things threading in java.
1). When I have to run class which implement runnable in Java. In main to start run method first I have to create class obj (i.e test obj).
Then I have pass it to thread constructor(i.e Thread objT = new Thread(obj)). Why I can't run it directly.

2). What is use of join statement?
I use it here so in program Main class wait till child class i.e test finish its execution.
And why we have to use catch Exception method in join statement
tkin
tkin #546
Jan 14, 2015 at 11:24 PM
Code:
public class test implements Runnable{
            public void run(){
            for(int i=1;i<6;i++){
                System.out.println(" "+i);
                try{
                    Thread.sleep(500);
                }catch(InterruptedException E){
                    System.out.println("Thread Interrupted");
                }
                
            }
            System.out.println("Run one is terminated");
        }


    public static void main(String agrs[]){
    test obj = new test();
    Thread objT = new Thread(obj);
    objT.start();
    try{
    objT.join(); 
    }
    catch(InterruptedException e){
        
    }
    System.out.println("Main one is terminated");
    }
    
}

I'm don't get these two things threading in java.
1). When I have to run class which implement runnable in Java. In main to start run method first I have to create class obj (i.e test obj).
Then I have pass it to thread constructor(i.e Thread objT = new Thread(obj)). Why I can't run it directly.

2). What is use of join statement?
I use it here so in program Main class wait till child class i.e test finish its execution.
And why we have to use catch Exception method in join statement
1. As Runnable is an interface, you cannot initialize it. But if you implement Runnable in your class you need to initialize your class to start a thread. Your class contains the main method which is Static, so you cannot refer to your test class object using 'this' i.e you cannot write this.start as its a Static method. Hence you need to initialize your test class object in the main method.

But you can do this to control your main class thread.

Code:
public class ThreadTest extends Thread {

	public static void main(String agrs[]){

		for(int i=1;i<6;i++){
			System.out.println(" "+i);
			try{
				Thread.sleep(500);
			}catch(InterruptedException E){
				System.out.println("Thread Interrupted");
			}

		}
		System.out.println("Main thread is terminated");
	}

}

In java, the class that contains the main method is loaded by the classloader and executes in jvm. It's thread, i.e the main thread is always started by jvm, from this thread the child threads, i.e your threads are spawned. So you can control this thread by directly calling Thread.sleep, but as mentioned above, you need to initialize the object if you want to spawn a child thread and control it, as in your example.

PS: You need to implement run() if you implement Runnable but since I am extending Thread class I don't need to do that.

2. If you don't use join then this is the output:
Code:
Main one is terminated
 1
 2
 3
 4
 5
Run one is terminated

Here what happens, child thread is spawned that executes the run method. It goes on, but your main method does not wait, it finishes execution, meanwhile your child thread goes on to execute the rest of the operations asynchronously.
P
phrick #547
Feb 17, 2015 at 6:20 PM
I have two questions about Java:
1) It is said that standard java is not needed in Android app developent, which Java is used then?
Any free tutorials...?
And
2) Can python be used instead of Java for Android app developement? Jython?
Please do reply...
abhigeek
abhigeek #548
Feb 17, 2015 at 6:28 PM
You need to learn Basic Java syntax and OOP concepts for Android Development.
For Java and Android Tutorials try channel TheNewBoston on youtube.
thetechfreak
Feb 17, 2015 at 10:24 PM
I have two questions about Java:
1) It is said that standard java is not needed in Android app developent, which Java is used then?
Any free tutorials...?
And
2) Can python be used instead of Java for Android app developement? Jython?
Please do reply...

Nope. Java knowledge is required.

Also, an online course is starting at coursera(android app developement) and yeah it's free :)
furious_gamer
Feb 17, 2015 at 11:51 PM
I have two questions about Java:
1) It is said that standard java is not needed in Android app developent, which Java is used then?
Any free tutorials...?
And
2) Can python be used instead of Java for Android app developement? Jython?
Please do reply...

1. Android framework is built with the help of Java, and to know Android, you should have some understanding in Java(not per se), but an OOPS language. But knowing Java will surely help.
2. That's bullshit. To develop Andriod, you need Android framework/language. Jython/Python et al used for other purposes. Ex, if you want to create an backend REST service for your android application, you can do so by Python. but not your Android app.

You have Google, the best friend of any developer, so go try that before asking these questions.(Not meant to be rude, but you should preach this before you become just another developer)
P
phrick #551
Mar 1, 2015 at 10:18 PM
1. Android framework is built with the help of Java, and to know Android, you should have some understanding in Java(not per se), but an OOPS language. But knowing Java will surely help.
Ok. Thank you!
2. That's bullshit. To develop Andriod, you need Android framework/language. Jython/Python et al used for other purposes. Ex, if you want to create an backend REST service for your android application, you can do so by Python. but not your Android app.

You have Google, the best friend of any developer, so go try that before asking these questions.(Not meant to be rude, but you should preach this before you become just another developer)

I did google but the result answers are pretty vague. makeuseof.com says standard java not need but helps to know before-hand while android dev courses just start abruptly without going into teaching java. Sorry but still I am not sure which Java to learn (if there are more than one).
Also, I was studying python from May 2014 so thought maybe it might be possible to make do with it, as there flavours of it like ironPython, jython (java implementation in Python); sorry if I hurt your feelings but I really am a noob. Sorry again.
furious_gamer
Mar 1, 2015 at 10:29 PM
Ok. Thank you!


I did google but the result answers are pretty vague. makeuseof.com says standard java not need but helps to know before-hand while android dev courses just start abruptly without going into teaching java. Sorry but still I am not sure which Java to learn (if there are more than one).
Also, I was studying python from May 2014 so thought maybe it might be possible to make do with it, as there flavours of it like ironPython, jython (java implementation in Python); sorry if I hurt your feelings but I really am a noob. Sorry again.

:D Hurt feelings? lulz.

BTW there is just one java. Just this one.

And I get it, since you are from Python, learning Java is somewhat difficult for you. So, just learn this Oracle(earlier called Sun) Java, and you are good to go with Android. If you want to learn Native Android or with frameworks like PhoneGap etc, some basic understanding in Java might be helpful.

Get some good Java book, for getting basic understanding. Just one tip, don't compare Python with Java. Boiler plate codes are a common sight in Java, and LoC will be high. But that is what makes Java, as "Java".
P
phrick #553
Mar 2, 2015 at 11:06 AM
:D Hurt feelings? lulz.

BTW there is just one java. Just this one.

And I get it, since you are from Python, learning Java is somewhat difficult for you. So, just learn this Oracle(earlier called Sun) Java, and you are good to go with Android. If you want to learn Native Android or with frameworks like PhoneGap etc, some basic understanding in Java might be helpful.

Get some good Java book, for getting basic understanding. Just one tip, don't compare Python with Java. Boiler plate codes are a common sight in Java, and LoC will be high. But that is what makes Java, as "Java".
Thanks man, that really helped!
TheSloth
TheSloth #554
May 22, 2016 at 10:46 AM
Could anybody guide me to link where I can learn (Java)Spring framework well?? Its important as I missed few classes in starting and I want to join now but will not be able to understand without basic knowledge. Also, if I feel like the source provided here is better than the teaching staff, then I will continue online. So please help me out here. A link to a website and if possible, a link to a Youtube channel too. Pleeeeeeease reply as soon as possible. Thank you.
S
sampada #555
Sep 23, 2016 at 3:49 PM
error occurs as VK_RIGHT is not declared and it is used
TheSloth
TheSloth #556
Sep 26, 2016 at 6:45 PM
ok i need help here with these 2 code :

1. public class Hello1 {
int b;
public static void main(String[] args) {
int a=9;
Hello1 h1 = new Hello1();
System.out.println("h1.b - "+h1.b);
System.out.println(a);
}
}

This one executes normally.
-------------------------------------------------------------------------

2. class A2{
int a;
A2 objA2 = new A2();
public void show(){
System.out.println("A2-show()");
System.out.println(objA2.a);
}
}
public class InsideObjectCreation {
public static void main(String[] args) {
A2 objA = new A2();
objA.show();
}
}

Here stackoverflow error at line 3.

I want to know how the object of the class is created before even executing the same class completely. Try to be as much detailed as possible with the flow of the program.
quicky008
quicky008 #557
Nov 18, 2016 at 5:56 PM
can anyone help me print the following pattern using java: ( see attached image)


if anyone knows how it can be done please post the solution here.
TheSloth
TheSloth #558
Nov 19, 2016 at 2:48 AM
@quicky008

Code:
import java.util.Scanner;

public class PatternNumPyramid {
    public static void main(String args[]) {
        System.out.println("Enter the number of rows you want to print");
        Scanner input = new Scanner(System.in);
        int numOfRows = input.nextInt();
        int  i, j, k;                                           [I]//to be used in for{} loops[/I]
        boolean flag; [I]                                     //flag is used to ensure that loop k(for space) runs only once after coming to next line[/I]
        for(i=0 ; i<=numOfRows; i++){          [I]//i is to go to next line[/I]
            flag=true;
            for(j=i; j>=0; j--){                         [I]//j is to print in decreasing order[/I]
                if(flag){
                    for(k=numOfRows-j; k>0; k--){ [I] //k is to print spaces[/I]
                        System.out.print(" ");
                    }flag=false;
                }
                System.out.print(j);
                if(i>0){
                    if(j==0){
                        for(int x=1; x<=i; x++){   [I] //x is to print in increasing order[/I]
                            System.out.print(x);
                        }
                    }
                }
            }
            System.out.println("");            
        }
    }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. numOfRows :
(a) As you see, the base of the pyramid starts with digit 5, and total number of rows you want to print are 5+1(=6). So I decided to take that number as common and it also helps to count number of spaces in each row(explained below)

(b) In the condition of the first loop, i<=5(number of rows), is used to print last row which starts from the digit 5. If you use i<5(number of rows) then it will just print 5 rows where 5 row starts from digit 4. You will miss the last row starting from 5.

(c) The above source code is in Java, so I used Scanner object input to take the common value of number of rows, digits at last row and space counts. Scanner is a class from util Library of Java, available to take input from the console. System.in parameter is input stream connected to Keyboard. I used it so that You can print the pyramid with any numerical value.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2. Spaces :
(a)Then comes the part about spaces. How to decide how many spaces should come?
If you see carefully, you will see that in the first row, there are five spaces and then 0 is printed. In next row, four spaces and then comes the 101. The spaces keep decreasing as we go to next row. So I decided to start the number of spaces should be equal to number of rows we want to print. ANd then number of rows should be keep on decreasing as we move to next row.

(b)How to decrease number of spaces in next row you ask? Remember, the spaces has to decrease by one count at each row. I used the logic as,
number of spaces at current row(k) = required number of rows(numOfRows) - value of current row(i) or value of j

(i) number of current row-is obvious one, for example
number of spaces at current row = 5 - 0 (value of current row or i) = 5. then we come to next row,
number of spaces at current row = 5 - 1 (value of current row or i) = 4, next row
number of spaces at current row = 5 - 2 (value of current row or i) = 3, and so on

(ii) how can we use j at the same position you ask? Notice the first digit in each row, it is count in increasing order. We can use same logic as above to find the number of spaces required at the current row.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

3. Digits :
(a) Forget everything and concentrate on just one row. I am using variable j to print the digits in increasing order and x for printing in increasing order. For example, in second last row, 4 3 2 1 0 1 2 3 4 . Here, I used j to print 4 3 2 1 0 and then I checked the value of j. If the value of j is 0, then I need to print the digits in increasing order, so I declared a new variable x to and print the digits till the value of j, i.e. 4.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I made some comments in few lines, to explain why did I take certain variables and their values. Try to change them and experiment a bit to understand the flow of the program. For example you can remove that flag variable and the check the output to see why I needed that variable. Use i to calculate the number of spaces required and check output and so on.

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Output -
How I approached for solution?
a. I just wrote a code to print values in decreasing order like 0 10 210 3210 (its without spaces)
b. Then I modified code to get different rows like
0
10
210
3210
c. Modified code to get spaces at front
0
10
210
3210
d. (final output)Then I had to print digits in reverse order too, used x for that
Code:
[CENTER]        0
      101
    21012
  3210123
[/CENTER]

Tell me if you have any doubts :)

- - - Updated - - -

PS: Formatting is all messed up, the last output is the final output, I coudln't format it properly. Sorry.

- - - Updated - - -

PPS : this source code is definitely not the optimized one. I am still learning how to write optimized source codes
quicky008
quicky008 #559
Nov 19, 2016 at 4:17 AM
^thank you very much indeed for posting such a detailed solution-i'll check it out shortly.
quicky008
quicky008 #560
Jun 18, 2017 at 9:57 PM
Could anybody guide me to link where I can learn (Java)Spring framework well?? Its important as I missed few classes in starting and I want to join now but will not be able to understand without basic knowledge. Also, if I feel like the source provided here is better than the teaching staff, then I will continue online. So please help me out here. A link to a website and if possible, a link to a Youtube channel too. Pleeeeeeease reply as soon as possible. Thank you.
did you find any reliable source for learning spring framework?Are free tutorials for it available online?Also can you suggest from where can one learn other frameworks like strutts,hibernate etc?

Also can anyone tell me what are node js and angular js?Do they have any similarity with OOPs languages like java?Is it particularly challenging to learn for beginners?
TheSloth
TheSloth #562
Jun 22, 2017 at 11:51 PM
did you find any reliable source for learning spring framework?Are free tutorials for it available online?Also can you suggest from where can one learn other frameworks like strutts,hibernate etc?

Also can anyone tell me what are node js and angular js?Do they have any similarity with OOPs languages like java?Is it particularly challenging to learn for beginners?

For (decent) basic knowledge, JavaBrains on youtube is good. I learned throught that. Someone might know of something better. But they have all tutorials you have mentioned in your post. Good place to start I would suggest.

I am yet to start JS but as far as I know and heard of, JS is very different from typical OO languages like C++ and Java. Can't really say if hard or not as it depends on person understaking the course , but, people say its hard(well, fu'k'em, you can start if you want, just make sure you start from the first, means, JavaScript). And as dilip mentioned, node.js is for server side. angular is mostly used front end. Really good to have in current market if one wants to be frontend or fullstack developer
TheSloth
TheSloth #563
Jun 22, 2017 at 11:58 PM
Hmmm, I should also follow things people are following over stackoverflow, not to give the complete code at firsthand. For future, if anyone is going to ask the code, better post the tries made by you and then we will try to suggest things to improve that code :) . Also, do not hesitate.
quicky008
quicky008 #564
Aug 9, 2017 at 10:32 PM
Can anyone tell me what conditions should a class fulfill to be fully encapsulated?Does one need to declare all the class variables as well as methods as private in order to achieve that?Can a class in which the variables have been declared as private but the methods are public be considered encapsulated?
Desmond
Desmond #565
Aug 9, 2017 at 11:27 PM
Can anyone tell me what conditions should a class fulfill to be fully encapsulated?Does one need to declare all the class variables as well as methods as private in order to achieve that?Can a class in which the variables have been declared as private but the methods are public be considered encapsulated?
As long as all your class variables are not directly accessible from outside, your class can be considered encapsulated. As per the Javabeans standards, you must define public getter and setter methods to get or set the values of the variables. Also, you must define public methods to operate on your class variables. Your class variables should remain private at all times.
quicky008
quicky008 #566
Dec 5, 2017 at 7:38 AM
i recently installed Eclipse kepler on my system-after installing it i tried launching kepler with my pre-existing workspace that was formerly used with eclipse mars-kepler suggested that i should üpgrade"my workspace to make the workspace files compatible with kepler-however finally when kepler started once the upgrade process finished none of the programs that were in my workspace were working-eclipse shows a red exclamation mark for every line of code in all programs and displays a "jni error"when i try to run them.Can anyone suggest what am i doing wrong?Are the older programs incompatible as they were created using eclipse mars?Is there any way i can fix this issue?
TheSloth
TheSloth #567
Dec 19, 2017 at 4:26 PM
i recently installed Eclipse kepler on my system-after installing it i tried launching kepler with my pre-existing workspace that was formerly used with eclipse mars-kepler suggested that i should üpgrade"my workspace to make the workspace files compatible with kepler-however finally when kepler started once the upgrade process finished none of the programs that were in my workspace were working-eclipse shows a red exclamation mark for every line of code in all programs and displays a "jni error"when i try to run them.Can anyone suggest what am i doing wrong?Are the older programs incompatible as they were created using eclipse mars?Is there any way i can fix this issue?
Did you fix the issue?? How did you fix it??
quicky008
quicky008 #568
Dec 21, 2017 at 3:13 AM
turns out the version of eclipse that i was using ie kepler didn't support java 8 or higher,i had java 8 installed on my system and so it kept throwing errors and simply refused to work-i finally resolved the issue by installing the latest version of eclipse,that is eclipse O2.
Desmond
Desmond #569
Dec 21, 2017 at 1:31 PM
You can also install JDK7 parallely with JDK8 and use Kepler with JDK7 if needed.
quicky008
quicky008 #570
Dec 23, 2017 at 1:34 AM
^thanks,thats indeed a really useful bit of info-i had no idea that one could use multiple versions of jdk on the same system.
quicky008
quicky008 #571
Jun 7, 2018 at 10:26 PM
can anyone help me print this pattern in java:
(please refer to the image given below):

p1
Desmond
Desmond #572
Jun 8, 2018 at 2:30 PM
Is this a fixed pattern or does it depend on a configurable number of iterations?

In either case, you could do something like this:

Code:
(pseudocode)
loop i from 1 to maxIterations
    spaceCount = maxIterations - (i*2);  //Since there are two stars
    loop j from 1 to i
        str = str + "*"
    end loop
    loop j from 1 to spaceCount
        str = str + " "  //append space
    end loop
    loop j from 1 to i
        str = str + "*"  //Ending stars
    end loop
    print str
end loop
Note that this code does not account for proper conditions for terminating the loop. So I leave that to you to figure out how you want to implement that.

I would personally prefer to use something like StringBuilder though, instead of appending into string.

Edit: Also, instead of the middle loop for appending space, I would personally prefer to create a maximum length space string and append a substring of it.
quicky008
quicky008 #573
Jan 31, 2019 at 12:12 AM
recently i was trying to run this program that was created in swing:

import javax.swing.*;
import java.awt.*;

public class rectangle3 {



public static void main(String[] args) {

JFrame f1=new JFrame("myrect")
{
public void paint(Graphics g)
{

g.drawString("Hello", 90,80);
}

};
f1.setSize(500,500);
f1.setVisible(true);
f1.setDefaultCloseOperation(f1.EXIT_ON_CLOSE);


}

}

On being executed,the text "Hello" did show up,but quite inexplicably,instead of the frame being opaque,it contained an image of the window in the background(ie it looked like someone had taken a screenshot of the window where the program had been written and had set it as the background image of the frame)-this was really weird,i couldn't understand what went wrong here.

Can anyone suggest what caused this strange behaviour while running this code?also is there any possible way to resolve this issue?
Desmond
Desmond #574
Jan 31, 2019 at 12:42 AM
I will have to try running this code and debug it to see what's actually going on.

But from what you've described it looks like you are drawing the text but haven't set any background color for the frame and that is probably causing this issue.

Sent from my A0001 using Tapatalk
Desmond
Desmond #575
Jan 31, 2019 at 12:39 PM
@quicky008 try this:

Code:
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;

public class rectangle3 {

    public static void main(String[] args) {

        JFrame f1 = new JFrame("myrect") {           
            
            public void paint(Graphics g) {
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, 500, 500);
                g.setColor(Color.BLACK);
                g.drawString("Hello", 90, 80);
            }

        };
        f1.setSize(500, 500);
        f1.setVisible(true);
        f1.setDefaultCloseOperation(f1.EXIT_ON_CLOSE);

    }

}
quicky008
quicky008 #576
Jan 31, 2019 at 12:53 PM
Thank you, i will try this out now.
quicky008
quicky008 #577
Aug 28, 2019 at 5:12 PM
can anyone help me solve this problem:

Q)Complete the code segment to call the default method in the interface First and Second.

Ans:-

Code:
interface First{

    // default method

    default void show(){
        System.out.println("Default method implementation of First interface.");
    }

}

 

interface Second{

    // Default method

    default void show(){
        System.out.println("Default method implementation of Second interface.");
    }

}

// Implementation class code

class Question44 implements First, Second{

    // Overriding default show method

    public void show(){

// Call show() of First interface.

// Call show() of Second interface.

}

    public static void main(String args[]){
        Question44 q = new Question44();
        q.show();
    }
}
Desmond
Desmond #578
Aug 28, 2019 at 6:21 PM
Got this to run by using this implementation:
Code:
class Question44 implements First, Second {

   // Overriding default show method

   public void show() {

       // Call show() of First interface.
       First.super.show();
       // Call show() of Second interface.
       Second.super.show();
   }

   public static void main(String args[]) {
       Question44 q = new Question44();
       q.show();
   }
}
quicky008
quicky008 #579
Aug 29, 2019 at 10:14 AM
^thanks a lot for the reply,but why has the super been used in this case?Can we call the default function of an interface by using the interface's name,followed by the super keyword?
Desmond
Desmond #580
Aug 29, 2019 at 12:22 PM
why has the super been used in this case
Because the method is not static. You can only call static methods using the class name qualifier.
TheSloth
TheSloth #581
Aug 30, 2019 at 9:47 AM
^this. And to understand why or how do we use Class/Interface names to call static method, you should read how the memory allocation works in Java.
quicky008
quicky008 #582
Sep 14, 2019 at 6:40 PM
i'm sorry if this seems irrelevant,but can someone recommend some good books for the foll. subjects:

1.Algorithms-it should cover all the essential precepts,including things like time complexity,space complexity etc in an easy to understand manner.

2.Automata.-i hardly know much about automata and would like to improve my understanding and knowledge of this subject to a greater extent.Ullman's book on automata is really popular-but is it easy to grasp for people who are not very familiar with this subject?

3.Data structures-the market seems flooded with a myriad books on this subject.But which one would be truly helpful for beginners?

4.Assembly language programming-while i have no immediate need for learning this subject,i still would like to explore it sometime later,simply because of my interest in this field.

5.Core java and advanced java programming.

Ps. recently i came across a book called "cracking the coding interview" on amazon.It seems very highly rated and is probably intended to help people acquire a more in-depth knowledge of the process of solving difficult problems that one may be given during tech-interviews/exams etc-is this book really as good as its made out to be?
Desmond
Desmond #583
Sep 15, 2019 at 12:25 AM
5.Core java and advanced java programming.
Don't know about others but Herbert Schildt's book is best for Java. I think it's called Java complete reference or something.
TheSloth
TheSloth #584
Sep 16, 2019 at 9:42 AM
The last book I used to learn anything related to career was probably 6-7yrs back, from the book Desmond suggested. It really is a good book for beginners. You could also try Head First Java. I usually go for online resources. You could try Udemy, MOOC EDX Online courses for all these topics. They provide demo and you get the option of refund if you didn't like the teaching of the instructor on Udemy.
thetechfreak
Sep 27, 2019 at 4:12 AM
Don't know about others but Herbert Schildt's book is best for Java. I think it's called Java complete reference or something.
+1 for this. My college professor(during bachelor degree) consulted this book and Head First. Both of them are very good. Great for learning Java. It's a shame I haven't written much Java after my Bachelor's degree(other than for Android).
TheSloth
TheSloth #587
Nov 18, 2020 at 5:05 PM
*www.humblebundle.com/books/java-programming-more-oreilly-books

5 Java based books fro $1.
thetechfreak
Nov 18, 2020 at 5:19 PM
*www.humblebundle.com/books/java-programming-more-oreilly-books

5 Java based books fro $1.
Yeah worth it. Also, a whole book dedicated to threads. Wow. @dDesmond David could use it maybe.

The 8$ bundle with Kotlin is something I could consider.

Sent from my vivo 1807 using Tapatalk
Desmond
Desmond #589
Nov 18, 2020 at 7:19 PM
Wow, those are some pretty good books.

Edit: Bought all of them. Now will I get time to read, that is the question.
TheSloth
TheSloth #590
Nov 18, 2020 at 7:57 PM
I also have been thinking to buy because of Java Threads but I am not able to decide. Do we really need to think about threads in web development when all the java based frameworks like Spring Boot, Play etc runs in a container which is self managed by the containers. Am I right?
What use cases do we have in today's Java programming where deep knowledge on Threads might come handy?
Desmond
Desmond #591
Nov 18, 2020 at 9:26 PM
Do we really need to think about threads in web development
Not really but depends on your use case. It's most helpful if you are doing something like batch processing.
Spring Boot, Play etc runs in a container which is self managed by the containers. Am I right?
These don't run in a container by default. You will have to write a Dockerfile for your build to run in a container.
What use cases do we have in today's Java programming where deep knowledge on Threads might come handy?
Like I said, batch processing or data processing. Like if you have to process a large number of files, then you will have to use threads to process them parallelly to increase throughput. But then again you don't have to know too much for most common use cases, just general idea is usually enough.
TheSloth
TheSloth #592
Nov 18, 2020 at 10:24 PM
These don't run in a container by default. You will have to write a Dockerfile for your build to run in a container.
Doesn't spring/play comes with its own container which creates a independent thread for each (http)request and those threads are managed until the purpose is served.
Desmond
Desmond #593
Nov 19, 2020 at 12:03 AM
Doesn't spring/play comes with its own container which creates a independent thread for each (http)request
If you are speaking about servlet container, then yes. But this is not something spectacular, a servlet container is basically same as an ordinary web server with the added functionality of running web applications and routing the requests to the appropriate web applications. As such, like any other web server, it creates new threads to handle requests.
those threads are managed until the purpose is served.
But not by us, the request thread's lifecycle is handled internally by the servlet container. We can spawn new threads for our own purposes though INSIDE the servlets but not in the servlet container itself.

For example, say I want to create a web application that takes a date range and calculates the average salary of all employees within that time range. In that case, you can define a servlet to spawn multiple threads to perform this calculation in parallel. But this is after the servlet container receives the request and spawns a thread to handle the request and then route the request to your container. So, you don't have to worry about how the servlet container is handling the threads.
TheSloth
TheSloth #594
Nov 19, 2020 at 10:18 AM
Very well explained. So far I have not implemented anything significant/exciting using Threads and since everything gets taken care by servlet container itself, I feel even more lazy to go through this topic since I have other things to focus on.

Also i gave in and bought the books for my collection. Paid Rs.77.71 instead of 74.
quicky008
quicky008 #595
Dec 18, 2020 at 3:31 PM
In a java program on file handling,I came across this statement: copy("temp.txt",Filename);

what does the copy command do here exactly?

When i tried to run it,it shows an error that says
Unresolved compilation problem:
The method copy(String, String) is undefined for the type file5 (where file5 was the class name)

Any ideas as to why is this happening?

couldn't find much info or examples on copy anywhere online.
thetechfreak
Dec 18, 2020 at 3:34 PM
I think the variables you pass in the copy method need to be the source and destination to paste the files.

So source.txt needs another filenane to copy into..


Can you share your code via pastebin or something?

Sent from my vivo 1807 using Tapatalk
quicky008
quicky008 #597
Dec 18, 2020 at 3:37 PM
it looks like this:

import java.io.*;
public class file5 {

//wap to insert a record in an existing file

public static void main(String[] args) throws IOException
{

String fileName="c:\\java\\student.txt";
String nametoinsert="B2";
String after="B";
int age=24,marks=25;


FileReader fr=new FileReader(fileName);
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter("c:\\java\\TEMP.TXT",false);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
String name;
while((name=br.readLine())!=null)
{
pw.println(name);
if(name.equalsIgnoreCase(after))
{ pw.println(nametoinsert);
pw.println(age);
pw.println(marks);
}
}
br.close();
fr.close();
pw.close();
bw.close();
fw.close();

copy("c:\\java\\TEMP.TXT",fileName);

System.out.println("Record inserted successfully !");
}





}

}
Desmond
Desmond #598
Dec 18, 2020 at 4:06 PM
The method copy(String, String) is undefined for the type file5 (where file5 was the class name)
Seems like a custom written method. It's probably outside the main() method in the same class. Do you have the code for the whole class?

Perhaps you are expected to write that method yourself.
TheSloth
TheSloth #599
Dec 18, 2020 at 7:29 PM
Also, would suggest to learn nio package in java APIs, way better than using buffered input streams for common works like these. I just feel that it looks more organized and straight-forward when reading code which uses nio package.
Desmond
Desmond #600
Dec 18, 2020 at 8:27 PM
Yeah, but it's good to know the classic java.io.* classes as well for general knowledge.
quicky008
quicky008 #601
Dec 18, 2020 at 10:58 PM
Yes,after writing a custom copy method for copying the contents of 1 file to another,its working.It was stupid of me to assume that copy was referencing some built in copy function in java.I had confused it with Files.copy(),which is intended for a somewhat different usage.
TheSloth
TheSloth #602
Dec 19, 2020 at 12:20 AM
In case of doubts, always move the cursor over the class/method/identifier name to find out more info about it provided by IDE. Always read the stack trace carefully. Some basic pointers to debug your code quicker. I have overlooked details and wasted lot of times looking for solutions which were not even my problems and always hated myself for not looking into the errors in more details.
quicky008
quicky008 #603
Jan 21, 2021 at 11:01 PM
a friend has asked for my assistance with a program that he needs as a part of some kind of "project work".The program is as follows:

"Wap in java to create a console based application to encrypt and decrypt a message (using cipher text/unicode exchange etc)."

While i have done some elementary coding in java,i really dont know much about encryption,especially things like this "unicode exchange".Can anyone give me some pointers as to what it really is and how i could possibly incorporate it into a program on encryption?Some tutorials or sample code detailing the process of encryption using unicode would have been very helpful indeed.

I am by no means a java expert thus any help i received with this would be greatly appreciated.
Desmond
Desmond #604
Jan 21, 2021 at 11:08 PM
You might want to look into the javax.crypto package. It contains classes that allow you to perform almost any kind of encryption.

Specifically read up about the Cipher class and how to use it.
quicky008
quicky008 #605
Jan 21, 2021 at 11:37 PM
i found some documentation on the crypto package,like this one here:

*docstore.mik.ua/orelly/java-ent/jnut/ch26_01.htm

However it all seems rather difficult to understand.Is there any hands on guide/tutorial that explains everything in a noob friendly way?Also what exactly is unicode exchange-is that a system of encryption like RSA,DES etc?
Desmond
Desmond #606
Jan 22, 2021 at 4:26 AM
I found this after a quick search: Java Cipher Class Example Tutorial - Encryption and Decryption Example

Might be what you need.

I have never heard of unicode exchange myself, perhaps you should ask for clarification.
quicky008
quicky008 #607
Jan 22, 2021 at 10:50 PM
thank you very much for sharing this-i will check it out.
quicky008
quicky008 #608
Mar 15, 2021 at 2:47 PM
When i attempt to run the foll. program:

Java:
public class Main extends Thread {

    public static int amount = 0;

    public static void main(String[] args) {
        Main thread = new Main();
        thread.start();
        // Wait for the thread to finish
        while(thread.isAlive()) {
            System.out.println("Waiting...");
        }

        // Update amount and print its value
        System.out.println("Main: " + amount);
        amount++;
        System.out.println("Main: " + amount);
    }

    public void run() {
        amount++;
    }
}

I get the foll. Output:

Waiting...
Waiting...
Main: 1
Main: 2


Can anyone explain why it happens? I am trying to understand mutithreading but this example is getting me confused.

Why have they used isalive()? Why is the waiting message displayed twice?
Desmond
Desmond #609
Mar 15, 2021 at 3:17 PM
Can anyone explain why it happens? I am trying to understand mutithreading but this example is getting me confused.
Here's what's happening:

1. You start the thread, the run() method gets called, `amount` gets incremented by 1 and the thread terminates. The program prints `Waiting...` until this termination occurs.
2. You print the value of `amount`, which is now 1 because of being incremented in the run() method.
3. You increment the value of `amount` in the main() method, the value is now 2.
4. You print the value of `amount` again.

I don't know what you are trying to test with this program though.

Why have they used isalive()? Why is the waiting message displayed twice?
isAlive() just returns true or false based on whether the thread is alive or not. Since your thread is only incrementing the value of `amount` exactly once, the thread does not live for long. Once it finishes executing all lines of code in the `run()` method, the thread terminates immediately, that is why it prints "Waiting..." twice because it terminates quickly. You can get the thread to be alive longer by calling a `Thread.sleep()` method in your `run()` method. This will result in many more "Waiting..." messages to be printed.
TheSloth
TheSloth #610
Mar 15, 2021 at 3:49 PM
replace your while loop with
while(thread.isAlive()) {

System.out.println("Waiting..."+thread.getName() + " -- " + thread.getState());
}
Now you can check in which state thread was. isAlive is true if thread has started and not terminated yet.
TheSloth
TheSloth #611
Mar 15, 2021 at 3:50 PM
And please tell us from where you are reading this kind of example. It seems bad example to explain multithreading.
Desmond
Desmond #612
Mar 15, 2021 at 4:05 PM
Also, it's a better practice to use a Runnable rather than extending a Thread. You don't need to extend a Thread class unless you absolutely have to.
quicky008
quicky008 #613
Mar 15, 2021 at 7:51 PM
Thanks a lot for the replies.

The source of the above code was a tutorial on threads that i found on W3schools:

*www.w3schools.com/java/java_threads.asp

This example can be found under the topic entitled "Concurrency problems"

I agree that using the runnable interface seems like a better idea,as extending the Thread class could prevent the class containing the code from extending other classes,if needed.

It seems the purpose of using threads is to allow the code/program to operate more efficiently by "doing multiple things at the same time"-i can't quite understand from the above example how this is being accomplished.Rather than using threads,one could simply achieve this by calling a function that's dedicated to that particular task(such as incrementing the value of amount in the above example)-so what added advantage does a thread bring to the table?

Can anyone please point me to a simple example that illustrates the above concept ie thread being used to do multiple things simultaneously in a more lucid manner?


Also how can i create and run multiple threads in the same program?I think in this example they have only created one thread that modifies the value of amount only one time.

Ever since i started learning java,the concept of threads has always kind of confounded me.Threads are supposed to make programming more efficient,but the examples i found online or in text books only increased my confusion rather than mitigating it.
quicky008
quicky008 #614
Mar 15, 2021 at 7:58 PM
one more question,even though it may sound rather asinine:

Why is the method of running a thread created by extending Thread class different from that of the one where it has been created by implementing runnable interface?In case of the former,one only needs to invoke the start() method via an object of the class,but for the latter,it can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method- why does such a difference exist?Is it like this by design?

Also can anyone please suggest a guide or simple tutorial for ADT and message passing in java?
Desmond
Desmond #615
Mar 15, 2021 at 9:49 PM
i can't quite understand from the above example how this is being accomplished
The above example is demonstrating that you can increment the value of `amount` in parallel. Though it is not a very good example.
so what added advantage does a thread bring to the table?
It allows you to run things in parallel. For example, if you were to create a UI application in a single thread, you would not want the whole application to freeze if you want to trigger some long running job. In this case, you run the job in a separate thread and let your UI application run in the main thread. This way your UI application does not freeze and the job goes on in the background.
Can anyone please point me to a simple example that illustrates the above concept ie thread being used to do multiple things simultaneously in a more lucid manner?
Also how can i create and run multiple threads in the same program?I think in this example they have only created one thread that modifies the value of amount only one time.
Consider this code:

Java:
package come.desmonddavid.ThreadTest;

public class ThreadTest {
    public static void main(String[] args) {
        Runnable r = () -> {
            System.out.println("Starting thread "+Thread.currentThread().getId());
            for(int i = 0; i < 10; i++) {
                long sleepTime = 1000L;
                try {
                    System.out.println(Thread.currentThread().getId()+": Sleeping for "+sleepTime+" milliseconds");
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Exiting thread "+Thread.currentThread().getId());
        };
      
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(r);
      
        t1.start();
        t2.start();
        t3.start();
    }
}

Here, I am defining a Runnable that logs some messages when the thread starts, sleeps and ends. It also prints the thread id in each message.

After this I am defining three Threads to run this Runnable and I start them. When you run this, you will get an output similar to the following:

Code:
Starting thread 11
11: Sleeping for 1000 milliseconds
Starting thread 13
Starting thread 12
12: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
Exiting thread 11
Exiting thread 13
Exiting thread 12

As you can see, the system creates three threads with ids as 11, 12 and 13. However, you will notice that every time you re-run the program, the sequence is different every time. This is because each of these threads are running in parallel. So, which thread executes when is chosen by the operating system. This is also not a very good example, but you can see how parallel processing works in this case.
Desmond
Desmond #616
Mar 15, 2021 at 10:02 PM
Threads are supposed to make programming more efficient,but the examples i found online or in text books only increased my confusion rather than mitigating it.
Threads can also make your code very complicated by potentially introducing problems such as race conditions, deadlocks, ConcurrentModificationExceptions, etc. So, you have to be very careful when using Threads. You should read up about thread safety in Java to see why this is important.
Why is the method of running a thread created by extending Thread class different from that of the one where it has been created by implementing runnable interface?In case of the former,one only needs to invoke the start() method via an object of the class,but for the latter,it can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method- why does such a difference exist?Is it like this by design?
Extending a Thread class may be beneficial in case when you already have some Thread functionality defined either as an abstract class or an existing concrete class and you need to enhance it's functionality. This however is a very special case and for most cases you will not need to extend a thread class since you simply need to run some piece of code. In this latter case, implementing a Runnable is simpler and thus preferable over extending a Thread class.
Desmond
Desmond #617
Mar 15, 2021 at 10:25 PM
Also can anyone please suggest a guide or simple tutorial for ADT and message passing in java?
What is ADT?

As for message passing, it's a broad topic. As in there are many ways to implement it. One way I can think of is to expose some methods after extending a Thread class and pass values to the thread using that.

Here is an example:

Java:
package come.desmonddavid.ThreadTest;

public class MessagePassingTest {
    public static void main(String[] args) throws InterruptedException {
        SquareThread st = new SquareThread();
        st.start();
        Thread.sleep(1000);
        st.feedValue(2);
        Thread.sleep(1000);
        st.feedValue(4);
        Thread.sleep(1000);
        st.feedValue(10);
        Thread.sleep(1000);
        st.quit();
    }
}

class SquareThread extends Thread {

    private volatile boolean valChanged = false;
    private volatile boolean quitThread = false;
    private volatile int value = 0;

    @Override
    public void run() {
  
        System.out.println("Starting SquareThread");
  
        while(true) {
            if(quitThread) {
                System.out.println("Exiting SquareThread");
                return;
            }
      
            if(valChanged) {
                System.out.println("Square of " + value + " is " + value * value);
                valChanged = false;
            }
        }
    }

    public void feedValue(int value) {
        this.value = value;
        valChanged = true;
    }

    public void quit() {
        quitThread = true;
    }

}

Here, SquareThread is a thread that runs in an infinite loop and waits for values or a request to terminate. The main thread (The thread that runs the main() method) then feeds values to this thread via the feedValue() method, waiting 1 second between feeding values three times. After than the main() method calls quit() and that terminates the thread. This is a very simple example, so I think you should be able to understand just by looking at it. If you have any doubts, then ask here.

Edit: This is also a good example of when extending Thread is beneficial.

Edit2: Also note that the variables in the thread use the volatile keyword. It's important to use either volatile variables or atomic datatypes because of thread safety. If I had not used volatile, the SquareThread may or may not see the new values that we pass to the thread via feedValue() or quit(). You can test what happens by removing the volatile keywords from the variables and run the program again.
TheSloth
TheSloth #618
Mar 15, 2021 at 11:16 PM
^This is good stuff.

@quicky008 Desmond has already linked one site above called Baeldung, this site is pretty much my goto for nearly all topics related to Java and java based frameworks. Apart from this you can refer howtodoinjava and jenkov. geeksforgeeks is also decent. BUT STOP referring w3schools, javatpoint tutorialspoint like sites. refer these if you don't find good examples on the sites I mentioned earlier. And also make a habit of reading official documentation for thorough understanding of some topics if you really want to know the internal workings.
quicky008
quicky008 #619
Mar 16, 2021 at 12:54 AM
@Desmond David : Thank you for all the comprehensive & in-depth tutorials you posted in response to my queries.I will go through them tomorrow.

I attempted to study the code on achieving concurrency using threads that you posted earlier,but there were certain things in it that i didn't quite understand eg the foll. expression :

Runnable r = () ->


It seems the arrow symbol is a representative of lambda expressions in java,but i am not really familiar with it and thus couldn't grasp its purpose in this code.Also isn't runnable an interface that's present in java?Are you trying to instantiate runnable here?(not sure whether interfaces can be instantiated or not)

Also why is r being passed as a parameter to the constructor of the thread class here?

I agree that message passing is quite a broad and somewhat abstruse topic,and the examples i found online hardly helped me understand any of it.I will take a look at your code tomorrow-perhaps it will help clear things up to some extent(there's a tutorial available at geeksforgeeks but it seemed quite complicated from my preliminary inspection)


@TheSloth :Thanks for suggesting Baeldung,to be honest i never heard of it until today,and i must say that it does look really interesting.I will look up some of the things that i didn't understand all that well (eg message passing)in it tomorrow.

The reason many folks keep checking out w3schools,javatpoint etc is that their links pop up most frequently when one searches for something on google(programming related,that is).They are frustratingly popular it seems!
Desmond
Desmond #620
Mar 16, 2021 at 1:44 AM
It seems the arrow symbol is a representative of lambda expressions in java,but i am not really familiar with it and thus couldn't grasp its purpose in this code.Also isn't runnable an interface that's present in java?Are you trying to instantiate runnable here?(not sure whether interfaces can be instantiated or not)
Sorry, that was a force of habit. We use Java 8 at work, so I have developed a habit of using lambdas.

Basically, Runnable r = () -> {} is equivalent to:

Java:
Runnable r = new Runnable() {
    public void run() {
        // Do something
    }
}

Since Runnable has been made into a Functional Interface in Java 8, that means you can use a lambda when defining it. But you can also use an Anonymous Inner Class like the second example if you want. Interfaces can be instantiated like classes but since interface methods are not defined, you have to define them as well like I have with the run() method in the second example.

Also why is r being passed as a parameter to the constructor of the thread class here?
Because Thread has multiple overloaded constructors, one of them takes a Runnable as an argument. Reference: Thread (Java Platform SE 8 )

@TheSloth :Thanks for suggesting Baeldung,to be honest i never heard of it until today,and i must say that it does look really interesting.I will look up some of the things that i didn't understand all that well (eg message passing)in it tomorrow.
I still take reference from Baeldung, and I have over 9 years of experience working in software development.
The reason many folks keep checking out w3schools,javatpoint etc is that their links pop up most frequently when one searches for something on google(programming related,that is).They are frustratingly popular it seems!
I think they are okay for beginners.
TheSloth
TheSloth #621
Mar 16, 2021 at 11:59 AM
Sorry, that was a force of habit. We use Java 8 at work, so I have developed a habit of using lambdas.
This is good. I also wanted to be like this but I am so much use to Java 7 that even when working with Java 8 I continue old practices because of which I have been struggling a lot lately.

@quicky008 One major advantage of baeldung is that the author uses latest java code so to understand the examples on that website, you need to first update your own java knowledge. I came across lambda expressions like that and was forced to learn that first before understanding the solution to my problem
I will suggest you also to refer coding practices in new java versions and use those as habit. Otherwise you will struggle like me.
Desmond
Desmond #622
Mar 16, 2021 at 12:56 PM
Lambdas are not very hard to learn. They are just functional interfaces that have a single method. Knowing when to use it will take some practice though. Start by learning Stream API in Java 8, this is one area where lambdas are used a lot.
TheSloth
TheSloth #623
Mar 16, 2021 at 1:11 PM
Yeah. I am working on 2 projects where one uses Java 8 ,so trying to use streams with filter wherever possible. To get more practiced, I should do some personal projects. Otherwise my work mostly involves Java 7.
quicky008
quicky008 #624
May 26, 2021 at 1:30 AM
Somebody gave me this code,apparently its from a website called hackerrank:
Java:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {



    // Complete the findNumber function below.
    static String findNumber(List<Integer> arr, int k) {
        String answer = "NO";
        for (Integer i : arr) {
            if (i == k) {
                answer = "YES";
                break;
            }
        }
        return answer;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        int arrCount = Integer.parseInt(bufferedReader.readLine().trim());

        List<String> arrTemp = new ArrayList<>();

        IntStream.range(0, arrCount).forEach(i -> {
            try {
                arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        List<Integer> arr = arrTemp.stream()
            .map(String::trim)
            .map(Integer: parseInt)
            .collect(toList());

        int k = Integer.parseInt(bufferedReader.readLine().trim());

        String res = findNumber(arr, k);

        bufferedWriter.write(res);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
};

I was asked to explain what's going on but i am quite confused regarding some of the things that are present in the above code.For instance,what's the significance of the following line:
arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));

Also what do the foll. mean?

List<Integer> arr = arrTemp.stream()
.map(String::trim)
.map(Integer: parseInt)
.collect(toList())

Its clear that arr is a List of type integer,but why have they assigned arrTemp.stream() to it?Also what exactly is the purpose of .map and .collect?

Any explanations on the above would be greatly appreciated.Also is this website ie hackerrank a good place to improve one's understanding of core-java and prepare oneself for coding related interviews(esp. for folks who don't have extensive knowledge of programming)?
Desmond
Desmond #625
May 26, 2021 at 10:33 AM
Could you use code tags to format your code? It's hard to read like this.
Desmond
Desmond #626
May 26, 2021 at 10:42 AM
For instance,what's the significance of the following line:
arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));
It's adding each line to the array after removing whitespace from the end of the string. It's using regular expressions to identify the whitespaces.


Also what do the foll. mean?

List<Integer> arr = arrTemp.stream()
.map(String::trim)
.map(Integer: parseInt)
.collect(toList());

Its clear that arr is a List of type integer,but why have they assigned arrTemp.stream() to it?Also what exactly is the purpose of .map and .collect?
This is the Java 8 Stream API. You can use streams to chain operations on some collections such as on list. Here, the stream of the string array is being transformed into an integer stream and then collected into a list.

arrTemp.stream() creates a stream using the elements in this array.

The first map() trims each string (Now that I think of it, trim could be used instead of replaceAll above and this operation could have been avoided.)

The second map() transforms each string to integer.

Finally, the collect() consolidates the resultant elements, in this case into a list. There are many other collectors available that can consolidate in other ways.
Desmond
Desmond #627
May 26, 2021 at 11:00 AM
There is a lot of things wrong with the code though. For example BufferedReader is being used to write to STDOUT when you could simply use System.out.println(). Also, I'd personally use the Scanner class to read the lines rather than use BufferedReader for the same.
Desmond
Desmond #629
May 26, 2021 at 1:34 PM
What is the HackerRank problem statement that this is a solution for? Can you give me the link? This program seems way to complex for what it's meant to do.

I can see that it says // Complete the findNumber function below. which means that the main() method was already like that in the code but I find it hard to believe.
quicky008
quicky008 #630
May 26, 2021 at 1:42 PM
i received it from someone i know,apparently he was given this question as a part of some kind of test round after applying for an internship with them.

This pdf details the entire problem,the "find the number" part was initially incomplete and the person taking this test was expected to solve it.

PS there are quite a few spelling and syntactical errors in the pdf as it was copied directly from their IDE,hopefully it will not affect the readability of the code.
Desmond
Desmond #631
May 26, 2021 at 6:56 PM
i received it from someone i know,apparently he was given this question as a part of some kind of test round after applying for an internship with them.

This pdf details the entire problem,the "find the number" part was initially incomplete and the person taking this test was expected to solve it.

PS there are quite a few spelling and syntactical errors in the pdf as it was copied directly from their IDE,hopefully it will not affect the readability of the code.
Yeah, looks like the main() method is the same from the problem statement.

The solution is to simply implement the findNumber() method. As such I don't think you are expected to understand what's in the main() method since that simply runs the findNumber() method.
khalil1210
khalil1210 #632
May 26, 2021 at 7:39 PM
Modified the code to make it readable.

Ignore the predefined code as now, focus on the problem statement and if you are able to run the code as expected.

If you want to start in hackerrank, pick your favourite language and start here - Day 0: Hello, World. | HackerRank

Java:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Soultion {

    // Complete the findNumber function below.
    static String findNumber(List<Integer> arr, int k) {
        String answer = "NO";
        for (Integer i : arr) {
            if (i == k) {
                answer = "YES";
                break;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arrLen = sc.nextInt();
        List<Integer> arr = new ArrayList<Integer>();
        for (int i = 0; i < arrLen; i++) {
            arr.add(sc.nextInt());
        }
        int k = sc.nextInt();
        String res = findNumber(arr, k);
        System.out.println(res);
        sc.close();
    }
}
Desmond
Desmond #633
May 28, 2021 at 11:53 AM
I have 2004 hackos on HackerRank. I have had an account with them when they used to be known as Interview Street.
khalil1210
khalil1210 #634
May 28, 2021 at 12:47 PM
I have 9966 hackos. Used to solve a lot of project euler programs and practice problems
Desmond
Desmond #635
May 28, 2021 at 12:57 PM
Yeah, I have not logged in in a long time now. I guess I will start again. Looks like a lot of new problems added since I last visited.
quicky008
quicky008 #636
May 28, 2021 at 5:43 PM
@Desmond David :thanks for your in-depth reply,your explanations really helped me in understanding this rather abstruse piece of code.

@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
khalil1210
khalil1210 #637
May 28, 2021 at 9:55 PM
@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
It helped me to write code, improving problem solving skills and gain confidence. I never had any high rank, so can't comment on that part. I used to spend a lot of time on understanding the easy questions and writing a solution and running the test cases.

During my college my main problem was I understood the problem, was able to build a solution, but I was never able to put it as code and run the test cases. I landed in a internship in my last year in college, because we had multiple coding rounds and I was confident and was able to successfully run the code.

One of my friends during college got few interview calls based on their his profile ( 5 years back )

Another friend got a interview based on his hackerrank profile and secured the job. He had 3+ years experience ( 2 years back ).The company sent him a test link, it had 10 java multiple choice questions and one program. Though he was not able to successfully run all the test cases, he was selected and in interview they asked him about how he solved it.

Don't stress on getting a higher rank, focus on
  • data structures
    • what are different types of data structures
    • where we use them
    • why we use them
  • algorithms
    • sorting algorithms ( binary sort, merge sort )
    • search ( binary search )
    • Big O notation
    • Time complexity
    • space complexity

There are other sites as well

Programming Challenges, and Coding Competitions on HackerEarth - has hiring weekly challenges for Indian companies

LeetCode - The World's Leading Online Programming Learning Platform - This is paid, I haven't tried it. Students from US use this site for FAANG companies, not sure about India. very popular on reddit.

Other sites I like

Codeforces

*www.spoj.com/
Desmond
Desmond #638
May 28, 2021 at 10:23 PM
There is also project Euler. Also look forward to Advent of Code every year.
TheSloth
TheSloth #639
May 30, 2021 at 10:16 PM
There is a lot of things wrong with the code though. For example BufferedReader is being used to write to STDOUT when you could simply use System.out.println(). Also, I'd personally use the Scanner class to read the lines rather than use BufferedReader for the same.
The code is from Hackerrank I guess. They have run all their test cases and match the output of the code against each test case, which are probably in some files. I am assuming this the reason they are using bufferedreader.
TheSloth
TheSloth #640
May 30, 2021 at 10:30 PM
@Desmond David :thanks for your in-depth reply,your explanations really helped me in understanding this rather abstruse piece of code.

@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
Indirectly, Yes. Directly, may be.
Indirectly in way since you have been solving lots of problems and improving skills, there is no other way to gain high rank or more points.

You can practice these coding things always to stay in touch with coding but I suggest you read more about how to code, design patterns, algorithms to be better at coding. Coding practices on these sites will help you keep your pace in solving problems but they don't help in improving code standards and knowledge bank. Read a lot! If you are in college, then you must do that ! Later you might not find time to do extensive reading because of job and house related works.

A lot of companies conduct challenges on hackerearth, you can attend those on weekends to get used to coding in limited amount of time. Weekdays you can do normal problems.
There are lots of start up companies on @ngeL list who ask candidates to attend 1st round through Hackerrank or Hackerearth. So stick to these sites to stay in touch with current market evaluations.
TheSloth
TheSloth #642
Aug 19, 2024 at 7:11 PM
Need help in understanding why reg ex pattern
Code:
((/?)([A-Z]{3})([0-9]{1,15}))
is returning false for input
Code:
ABC123/DEF1223456/GHI12345678980834

Sample code:
Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExCHGSTagPattern {
  public static void main(String[] args) {
  String input1 = "ABC123";
  String input2 = "ABC123/DEF1223456/GHI12345678980834";
  Pattern p = Pattern.compile("((/?)([A-Z]{3})([0-9]{1,15}))");
  Matcher m1 = p.matcher(input1);
  Matcher m2 = p.matcher(input2);
  System.out.println("output1-"+m1.matches());
  while(m2.find()) {
    System.out.println(m2.group()+"-"+p.matcher(m2.group()).matches());
  }
  System.out.println("output2-"+m2.matches());
  }
}

@Desmond @khalil1210 @quicky008
Desmond
Desmond #643
Aug 19, 2024 at 7:55 PM
I think you haven't escaped the first forward slash.

I matched all the groups in your string using this regex:

([A-Z]{3}\d{1,15})\/?

Edit: Replaced \d+ with \d{1,15} since you have a constraint on the number of digits.
TheSloth
TheSloth #644
Aug 19, 2024 at 8:38 PM
I think you haven't escaped the first forward slash.

I matched all the groups in your string using this regex:

([A-Z]{3}\d{1,15})\/?

Edit: Replaced \d+ with \d{1,15} since you have a constraint on the number of digits.
I am trying but its not working in IDE. i did match the strings on *regex101.com/

View attachment 1724080208719.png
khalil1210
khalil1210 #645
Aug 19, 2024 at 8:59 PM
Try with this website to test with different inputs which can come up - *regex101.com/r/4dq5xR/1

Java:
Pattern p = Pattern.compile("([A-Z]{1,3}[0-9]{1,15}/?)+");

I think this code should work

Explanation for my code --
[A-Z]{1,3} --> any character from A to Z which will repeat for minimum 1 to maximum 3 times
[0-9]{1,15} --> any number from 0 to 9 which will repeat for minimum 1 to maximum 15 times
/? --> / can come for zero or more times

this regex can possibly match with strings like [A-Z]{1,3}[0-9]{1,15}/? -->
ABC123
DEF123/
X1
YZ23/
XYZ123456789012345/

But we want the above group to come one or more times, so we can mention it as group and add + for one or more times

final regex is - ([A-Z]{1,3}[0-9]{1,15}/?)+

View attachment 1724081351825.png
TheSloth
TheSloth #646
Aug 19, 2024 at 9:22 PM
The problem is I am able to match the regex with online compiler. But for some reason it's not working in IDE. I am using Java 17
Desmond
Desmond #647
Aug 19, 2024 at 9:27 PM
I am trying but its not working in IDE. i did match the strings on *regex101.com/

View attachment 22926
In Java you have to escape the backslashes for regex Strings.

private static final String pattern = "([A-Z]{3}\\d{1,15})\\/?";

Java:
class Main {

    private static final String pattern = "([A-Z]{3}\\d{1,15})\\/?";
 
    private static final String input = "ABC123/DEF1223456/GHI12345678980834";
 
    public static void main(String[] args) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(input);
        while(m.find()) {
            System.out.println(m.group(1));
        }
    }
}

Yields:

Code:
ABC123
DEF1223456
GHI12345678980834

With some group adjustment, the ending slashes can be excluded.

Edit: Apparently, simply using group(1) will match the bracketed group in the regex. Updated the answer to reflect that.
Desmond
Desmond #648
Aug 19, 2024 at 10:02 PM
BTW, note that regex implementations are not standard and different languages/platforms have slightly different behaviour.
TheSloth
TheSloth #649
Aug 19, 2024 at 10:26 PM
In Java you have to escape the backslashes for regex Strings.

private static final String pattern = "([A-Z]{3}\\d{1,15})\\/?";

Java:
class Main {

    private static final String pattern = "([A-Z]{3}\\d{1,15})\\/?";
 
    private static final String input = "ABC123/DEF1223456/GHI12345678980834";
 
    public static void main(String[] args) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(input);
        while(m.find()) {
            System.out.println(m.group(1));
        }
    }
}

Yields:

Code:
ABC123
DEF1223456
GHI12345678980834

With some group adjustment, the ending slashes can be excluded.

Edit: Apparently, simply using group(1) will match the bracketed group in the regex. Updated the answer to reflect that.
if you add m.matches() line at the end, it returns false. This is exactly my question, we are able to see the group from the entire input which matches, I am wondering why m.matches() return false at the end.
TheSloth
TheSloth #650
Aug 19, 2024 at 11:20 PM
Try with this website to test with different inputs which can come up - *regex101.com/r/4dq5xR/1

Java:
Pattern p = Pattern.compile("([A-Z]{1,3}[0-9]{1,15}/?)+");

I think this code should work

Explanation for my code --
[A-Z]{1,3} --> any character from A to Z which will repeat for minimum 1 to maximum 3 times
[0-9]{1,15} --> any number from 0 to 9 which will repeat for minimum 1 to maximum 15 times
/? --> / can come for zero or more times

this regex can possibly match with strings like [A-Z]{1,3}[0-9]{1,15}/? -->
ABC123
DEF123/
X1
YZ23/
XYZ123456789012345/

But we want the above group to come one or more times, so we can mention it as group and add + for one or more times

final regex is - ([A-Z]{1,3}[0-9]{1,15}/?)+

View attachment 22927
It worked! Adding the + symbol at the end of the entire group returns true. You are a saviour <3
Desmond
Desmond #651
Aug 20, 2024 at 2:53 AM
Ok, I misunderstood your question. I thought you wanted to extract the individual components of the string.

Though I would use \d instead of [0-9] since it matches single digits, while the [] notation works if you are creating an alphanumeric pattern.