This forum is in archive mode. You will not be able to post new content.

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - sherlock

Pages: [1]
1
Java / Re: ranges of ints, bytes, shorts, chars
« on: June 15, 2014, 12:09:35 PM »
Unless you have arrays, the JVM won't make a difference handling short, byte or int. Local variables of these types all occupy 32 bit cells within the JVM despite their actual length.
The integer operations are optimized for int values. Using byte or short instead of int is most of the time less efficient as the operations are slower.
Memorywise it is really only a good choice if dealing with very large arrays.

In only remembered that it saves space in arrays so i concluded it would save space in variables too, which was wrong.

Regarding space and efficiency:
Code: [Select]
    public int addInts(int x, int y) {
        return x + y;
    }
   
    public short addShorts(short x, short y) {
        // you need the (short) cast since short + short returns an int
        return (short) (x + y);
    }

which compiles to:

Code: [Select]
    public int addInts(int x, int y) {
        iload_1 //loads the int value of x on the stack
        iload_2 //loads the int value of y on the stack
        iadd //pops the two int values on top of the stack (here: x, y) and pushes the sum on the stack
        ireturn //returns the int value on top of the stack
    }

    public short addShorts(short x, short y) {
        iload_1 //loads the int value of x on the stack --> same space as an int in ram needed
        iload_2 //loads the int value of y on the stack --> same space as an int in ram needed
        iadd //pops the two int values on top of the stack (here: x, y) and pushes the sum on the stack
        i2s // converts the int to short --> extra instruction -->less efficient
        ireturn //returns the int (in this case it's a short) value on top of the stack
    }



The reason why there are no extra instructions for datatypes like shorts is explained in the JVM specification:
Quote
Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a byte. Instead, the instruction set of the Java Virtual Machine provides a reduced level of type support for certain operations. In other words, the instruction set is intentionally not orthogonal. Separate instructions can be used to convert between unsupported and supported data types as necessary.
In our example: there are no load, add and return instructions for shorts => the JVM uses the integer ones.

I hope this is more correct.

2
Java / Re: ranges of ints, bytes, shorts, chars
« on: June 14, 2014, 08:33:14 PM »
There are two main reasons, i can think of:

Firstly using a smaller datatype requires less space (ram) at runtime.
However in practice people tend to prefer int to short, simply because they are used to using int and for normal applications it won't make much of a difference.

Secondly - and in my opinion often that's the more important reason - it increases the readability of code immensely.  E. g. if a variable is declared as a char, you know it represents an Character (digit, letter, symbol).

3
Java / [java] LinesCounter
« on: April 17, 2014, 01:30:27 PM »
This is just some sloppy code i quickly wrote.

It simply counts the amount of lines in all files you select.
extensions -> only processes files, which have one of the extensions
count empty lines -> counts empty lines when toggled

Code: [Select]
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class LinesCounter extends JPanel {

    public static void main(String[] args) {
        LinesCounter linesCounter = new LinesCounter();
    }

    private final JFrame frame;

    private final JCheckBox countEmptyLines;
    private final JTextField extensions;
    private final JButton chooseFiles;
    private final JLabel label;

    private JFileChooser fileChooser;
    private File[] files;
    private int returnVal;

    private final ArrayList<String> extensionStrings;

    private final ActionListener chooseFilesListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fileChooser.setMultiSelectionEnabled(true);
            returnVal = fileChooser.showDialog(LinesCounter.this, "Choose Files");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                files = fileChooser.getSelectedFiles();
                JOptionPane.showMessageDialog(null,
                        "" + countLines(files, getExtensions(), countEmptyLines.isSelected()),
                        "Amount of lines", JOptionPane.INFORMATION_MESSAGE);
            }
        }

    };

    public LinesCounter() {
        super(new GridLayout(4, 1));

        extensionStrings = new ArrayList<String>();
        countEmptyLines = new JCheckBox("count empty lines");
        extensions = new JTextField();
        chooseFiles = new JButton("choose files");
        chooseFiles.addActionListener(chooseFilesListener);
        label = new JLabel("eg:.java;.doc;.class");
        this.add(countEmptyLines);
        this.add(extensions);
        this.add(label);
        this.add(chooseFiles);

        frame = new JFrame();
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private int countLines(final File[] files, final String[] extensions,
            final boolean countEmptyLines) {
        if (files == null) {
            return 0;
        }
        int lines = 0;
        for (final File file : files) {
            lines += countLines(file, extensions, countEmptyLines);
        }
        return lines;
    }

    private int countLines(final File file, final String[] extensions, final boolean countEmptyLines) {
        if (file == null || !file.exists()) {
            return 0;
        }
        if (file.isDirectory()) {
            int lines = 0;
            final File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (final File f : files) {
                    lines += countLines(f, extensions, countEmptyLines);
                }
            }
            return lines;
        } else {
            final String fileName = file.getName();
            if (fileName != null && stringEndsWith(fileName, extensions)) {
                try {
                    final BufferedReader bR = new BufferedReader(new FileReader(file));
                    String line = bR.readLine();
                    int lines = 0;
                    while (line != null) {
                        if (!line.isEmpty()) {
                            lines++;
                        } else {
                            if (countEmptyLines) {
                                lines++;
                            }
                        }
                        line = bR.readLine();
                    }
                    bR.close();
                    return lines;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    private boolean stringEndsWith(final String string, final String... extensions) {
        if (string == null || extensions == null) {
            return false;
        }
        for (final String extension : extensions) {
            if (string.endsWith(extension)) {
                return true;
            }
        }
        return false;
    }

    private String[] getExtensions() {
        final Scanner scanner = new Scanner(extensions.getText());
        scanner.useDelimiter(";");
        extensionStrings.clear();
        while (scanner.hasNext()) {
            extensionStrings.add(scanner.next());
        }
        scanner.close();
        return extensionStrings.toArray(new String[extensionStrings.size()]);
    }

}

4
Java / Re: For loop
« on: April 13, 2014, 12:09:28 PM »
I was talking about Java 7. I meant "newer" compared to the version he was using before.
I see, makes sense now :)

5
Java / Re: For loop
« on: April 12, 2014, 07:38:51 PM »
What exactly did you do?
Just downloading and installing a JDK is not enough. You need to change the settings in Eclipse.
Also: Eclipse ships with 1.7. There should be an option for a newer version already.
Thank you man. This the new boston tutorials are the worst as I can see now. So stupid. Now it works. Thanks +1
Actually there is no option for a newer version, until you install the plugin "Java 8 support for Eclipse Kepler SR2" in the Eclipse Marketplace

6
Java / Re: For loop
« on: April 11, 2014, 02:49:25 PM »
Rightclick the project > Properties > Java Build Path > Libraries > which version of the jdk are you using in this project?
=> Make sure using jdk.1.7.0_51
Also  check properties > Java Compiler > which compiler compilance level did you choose?
=> Should be 1.7

7
Java / Re: Java quiz series
« on: April 04, 2014, 06:33:26 PM »
Hey guys,
I  enjoy this kind of challenges and really would like to see them continue, so i thought it would be a nice way to introduce myself by posting one (since the last one was posted some time ago).
The challenge is probably too easy, simply explain what is happening ;)

Code: [Select]
import java.lang.reflect.Method;

public class Main {

    private String key = "hello";
   
    public Main(){
        key = decrypt(key);
    }

    public static void main(String[] args) {
        final Main m = new Main();
        m.doStuff();
    }
   
    private String decrypt(final String s){
        final char[] c = s.toCharArray();
        for(int i = 0; i < c.length; i++){
            c[i] = (char)(c[i] - 4 - i);
        }
        return String.valueOf(c);
    }
   
    private void hello(){
        System.out.println("Hey guys!");
    }
   
    public void doStuff(){
        try {
            Method m = this.getClass().getDeclaredMethod(key);
            m.invoke(this);
        } catch (Exception e) {
            //I don't care ;)
        }
    }
   
    {{
      key = "ljrsw"; 
    }}

}


Pages: [1]


Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.