Java Queries Here..

Jaskanwar Singh

Aspiring Novelist
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);
    }
 

Jaskanwar Singh

Aspiring Novelist
^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;
    }
 
Last edited:

dashing.sujay

Moving
Staff member
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

Aspiring Novelist
thanks sujay, and second question?

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

vickybat

I am the night...I am...
^^ 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

Moving
Staff member
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

Moving
Staff member
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. :)
 

dashing.sujay

Moving
Staff member
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

I am the night...I 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

Moving
Staff member
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. :)
 
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

Journeyman
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

Retired Forum Mod
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.
 
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

Journeyman
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 !! ";
	}
}
 
Top Bottom