import java.applet.Applet;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Panel;
import java.awt.ScrollPane;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.EOFException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;

public class VncViewer extends Applet implements Runnable, WindowListener {
  boolean inAnApplet = true;
  
  boolean inSeparateFrame = false;
  
  String[] mainArgs;
  
  RfbProto rfb;
  
  Thread rfbThread;
  
  Frame vncFrame;
  
  Container vncContainer;
  
  ScrollPane desktopScrollPane;
  
  GridBagLayout gridbag;
  
  ButtonPanel buttonPanel;
  
  Label connStatusLabel;
  
  VncCanvas vc;
  
  OptionsFrame options;
  
  ClipboardFrame clipboard;
  
  RecordingFrame rec;
  
  Object recordingSync;
  
  String sessionFileName;
  
  boolean recordingActive;
  
  boolean recordingStatusChanged;
  
  String cursorUpdatesDef;
  
  String eightBitColorsDef;
  
  String socketFactory;
  
  String host;
  
  int port;
  
  String passwordParam;
  
  boolean showControls;
  
  boolean offerRelogin;
  
  boolean showOfflineDesktop;
  
  int deferScreenUpdates;
  
  int deferCursorUpdates;
  
  int deferUpdateRequests;
  
  int debugStatsExcludeUpdates;
  
  int debugStatsMeasureUpdates;
  
  public static Applet refApplet;
  
  int[] encodingsSaved;
  
  int nEncodingsSaved;
  
  public static void main(String[] paramArrayOfString) {
    VncViewer vncViewer = new VncViewer();
    vncViewer.mainArgs = paramArrayOfString;
    vncViewer.inAnApplet = false;
    vncViewer.inSeparateFrame = true;
    vncViewer.init();
    vncViewer.start();
  }
  
  public void init() {
    readParameters();
    refApplet = this;
    if (this.inSeparateFrame) {
      this.vncFrame = new Frame("TightVNC");
      if (!this.inAnApplet)
        this.vncFrame.add("Center", this); 
      this.vncContainer = this.vncFrame;
    } else {
      this.vncContainer = this;
    } 
    this.recordingSync = new Object();
    this.options = new OptionsFrame(this);
    this.clipboard = new ClipboardFrame(this);
    if (RecordingFrame.checkSecurity())
      this.rec = new RecordingFrame(this); 
    this.sessionFileName = null;
    this.recordingActive = false;
    this.recordingStatusChanged = false;
    this.cursorUpdatesDef = null;
    this.eightBitColorsDef = null;
    if (this.inSeparateFrame)
      this.vncFrame.addWindowListener(this); 
    this.rfbThread = new Thread(this);
    this.rfbThread.start();
  }
  
  public void update(Graphics paramGraphics) {}
  
  public void run() {
    this.gridbag = new GridBagLayout();
    this.vncContainer.setLayout(this.gridbag);
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridwidth = 0;
    gridBagConstraints.anchor = 18;
    if (this.showControls) {
      this.buttonPanel = new ButtonPanel(this);
      this.gridbag.setConstraints(this.buttonPanel, gridBagConstraints);
      this.vncContainer.add(this.buttonPanel);
    } 
    try {
      connectAndAuthenticate();
      doProtocolInitialisation();
      if (this.options.autoScale && this.inSeparateFrame) {
        Dimension dimension;
        try {
          dimension = this.vncContainer.getToolkit().getScreenSize();
        } catch (Exception exception) {
          dimension = new Dimension(0, 0);
        } 
        createCanvas(dimension.width - 32, dimension.height - 32);
      } else {
        createCanvas(0, 0);
      } 
      gridBagConstraints.weightx = 1.0D;
      gridBagConstraints.weighty = 1.0D;
      if (this.inSeparateFrame) {
        Panel panel = new Panel();
        panel.setLayout(new FlowLayout(0, 0, 0));
        panel.add(this.vc);
        this.desktopScrollPane = new ScrollPane(0);
        gridBagConstraints.fill = 1;
        this.gridbag.setConstraints(this.desktopScrollPane, gridBagConstraints);
        this.desktopScrollPane.add(panel);
        this.vncFrame.add(this.desktopScrollPane);
        this.vncFrame.setTitle(this.rfb.desktopName);
        this.vncFrame.pack();
        this.vc.resizeDesktopFrame();
      } else {
        this.gridbag.setConstraints(this.vc, gridBagConstraints);
        add(this.vc);
        validate();
      } 
      if (this.showControls)
        this.buttonPanel.enableButtons(); 
      moveFocusToDesktop();
      processNormalProtocol();
    } catch (NoRouteToHostException noRouteToHostException) {
      fatalError("Network error: no route to server: " + this.host, noRouteToHostException);
    } catch (UnknownHostException unknownHostException) {
      fatalError("Network error: server name unknown: " + this.host, unknownHostException);
    } catch (ConnectException connectException) {
      fatalError("Network error: could not connect to server: " + this.host + ":" + this.port, connectException);
    } catch (EOFException eOFException) {
      if (this.showOfflineDesktop) {
        eOFException.printStackTrace();
        System.out.println("Network error: remote side closed connection");
        if (this.vc != null)
          this.vc.enableInput(false); 
        if (this.inSeparateFrame)
          this.vncFrame.setTitle(this.rfb.desktopName + " [disconnected]"); 
        if (this.rfb != null && !this.rfb.closed())
          this.rfb.close(); 
        if (this.showControls && this.buttonPanel != null) {
          this.buttonPanel.disableButtonsOnDisconnect();
          if (this.inSeparateFrame) {
            this.vncFrame.pack();
          } else {
            validate();
          } 
        } 
      } else {
        fatalError("Network error: remote side closed connection", eOFException);
      } 
    } catch (IOException iOException) {
      String str = iOException.getMessage();
      if (str != null && str.length() != 0) {
        fatalError("Network Error: " + str, iOException);
      } else {
        fatalError(iOException.toString(), iOException);
      } 
    } catch (Exception exception) {
      String str = exception.getMessage();
      if (str != null && str.length() != 0) {
        fatalError("Error: " + str, exception);
      } else {
        fatalError(exception.toString(), exception);
      } 
    } 
  }
  
  void createCanvas(int paramInt1, int paramInt2) throws IOException {
    this.vc = null;
    try {
      Class clazz = Class.forName("java.awt.Graphics2D");
      clazz = Class.forName("VncCanvas2");
      Class[] arrayOfClass = { getClass(), int.class, int.class };
      Constructor constructor = clazz.getConstructor(arrayOfClass);
      Object[] arrayOfObject = { this, new Integer(paramInt1), new Integer(paramInt2) };
      this.vc = (VncCanvas)constructor.newInstance(arrayOfObject);
    } catch (Exception exception) {
      System.out.println("Warning: Java 2D API is not available");
    } 
    if (this.vc == null)
      this.vc = new VncCanvas(this, paramInt1, paramInt2); 
  }
  
  void processNormalProtocol() throws Exception {
    try {
      this.vc.processNormalProtocol();
    } catch (Exception exception) {
      if (this.rfbThread == null) {
        System.out.println("Ignoring RFB socket exceptions because applet is stopping");
      } else {
        throw exception;
      } 
    } 
  }
  
  void connectAndAuthenticate() throws Exception {
    int j;
    showConnectionStatus("Initializing...");
    if (this.inSeparateFrame) {
      this.vncFrame.pack();
      this.vncFrame.show();
    } else {
      validate();
    } 
    showConnectionStatus("Connecting to " + this.host + ", port " + this.port + "...");
    this.rfb = new RfbProto(this.host, this.port, this);
    showConnectionStatus("Connected to server");
    this.rfb.readVersionMsg();
    showConnectionStatus("RFB server supports protocol version " + this.rfb.serverMajor + "." + this.rfb.serverMinor);
    this.rfb.writeVersionMsg();
    showConnectionStatus("Using RFB protocol version " + this.rfb.clientMajor + "." + this.rfb.clientMinor);
    int i = this.rfb.negotiateSecurity();
    if (i == 16) {
      showConnectionStatus("Enabling TightVNC protocol extensions");
      this.rfb.setupTunneling();
      j = this.rfb.negotiateAuthenticationTight();
    } else {
      j = i;
    } 
    switch (j) {
      case 1:
        showConnectionStatus("No authentication needed");
        this.rfb.authenticateNone();
        return;
      case 2:
        showConnectionStatus("Performing standard VNC authentication");
        if (this.passwordParam != null) {
          this.rfb.authenticateVNC(this.passwordParam);
        } else {
          String str = askPassword();
          this.rfb.authenticateVNC(str);
        } 
        return;
    } 
    throw new Exception("Unknown authentication scheme " + j);
  }
  
  void showConnectionStatus(String paramString) {
    if (paramString == null) {
      if (this.vncContainer.isAncestorOf(this.connStatusLabel))
        this.vncContainer.remove(this.connStatusLabel); 
      return;
    } 
    System.out.println(paramString);
    if (this.connStatusLabel == null) {
      this.connStatusLabel = new Label("Status: " + paramString);
      this.connStatusLabel.setFont(new Font("Helvetica", 0, 12));
    } else {
      this.connStatusLabel.setText("Status: " + paramString);
    } 
    if (!this.vncContainer.isAncestorOf(this.connStatusLabel)) {
      GridBagConstraints gridBagConstraints = new GridBagConstraints();
      gridBagConstraints.gridwidth = 0;
      gridBagConstraints.fill = 2;
      gridBagConstraints.anchor = 18;
      gridBagConstraints.weightx = 1.0D;
      gridBagConstraints.weighty = 1.0D;
      gridBagConstraints.insets = new Insets(20, 30, 20, 30);
      this.gridbag.setConstraints(this.connStatusLabel, gridBagConstraints);
      this.vncContainer.add(this.connStatusLabel);
    } 
    if (this.inSeparateFrame) {
      this.vncFrame.pack();
    } else {
      validate();
    } 
  }
  
  String askPassword() throws Exception {
    showConnectionStatus(null);
    AuthPanel authPanel = new AuthPanel(this);
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridwidth = 0;
    gridBagConstraints.anchor = 18;
    gridBagConstraints.weightx = 1.0D;
    gridBagConstraints.weighty = 1.0D;
    gridBagConstraints.ipadx = 100;
    gridBagConstraints.ipady = 50;
    this.gridbag.setConstraints(authPanel, gridBagConstraints);
    this.vncContainer.add(authPanel);
    if (this.inSeparateFrame) {
      this.vncFrame.pack();
    } else {
      validate();
    } 
    authPanel.moveFocusToDefaultField();
    String str = authPanel.getPassword();
    this.vncContainer.remove(authPanel);
    return str;
  }
  
  void doProtocolInitialisation() throws IOException {
    this.rfb.writeClientInit();
    this.rfb.readServerInit();
    System.out.println("Desktop name is " + this.rfb.desktopName);
    System.out.println("Desktop size is " + this.rfb.framebufferWidth + " x " + this.rfb.framebufferHeight);
    setEncodings();
    showConnectionStatus(null);
  }
  
  void setEncodings() {
    setEncodings(false);
  }
  
  void autoSelectEncodings() {
    setEncodings(true);
  }
  
  void setEncodings(boolean paramBoolean) {
    if (this.options == null || this.rfb == null || !this.rfb.inNormalProtocol)
      return; 
    int i = this.options.preferredEncoding;
    if (i == -1) {
      long l = this.rfb.kbitsPerSecond();
      if (this.nEncodingsSaved < 1) {
        System.out.println("Using Tight/ZRLE encodings");
        i = 7;
      } else if (l > 2000L && this.encodingsSaved[0] != 5) {
        System.out.println("Throughput " + l + " kbit/s - changing to Hextile encoding");
        i = 5;
      } else if (l < 1000L && this.encodingsSaved[0] != 7) {
        System.out.println("Throughput " + l + " kbit/s - changing to Tight/ZRLE encodings");
        i = 7;
      } else {
        if (paramBoolean)
          return; 
        i = this.encodingsSaved[0];
      } 
    } else if (paramBoolean) {
      return;
    } 
    int[] arrayOfInt = new int[20];
    byte b = 0;
    arrayOfInt[b++] = i;
    if (this.options.useCopyRect)
      arrayOfInt[b++] = 1; 
    if (i != 7)
      arrayOfInt[b++] = 7; 
    if (i != 16)
      arrayOfInt[b++] = 16; 
    if (i != 5)
      arrayOfInt[b++] = 5; 
    if (i != 6)
      arrayOfInt[b++] = 6; 
    if (i != 4)
      arrayOfInt[b++] = 4; 
    if (i != 2)
      arrayOfInt[b++] = 2; 
    if (this.options.compressLevel >= 0 && this.options.compressLevel <= 9)
      arrayOfInt[b++] = -256 + this.options.compressLevel; 
    if (this.options.jpegQuality >= 0 && this.options.jpegQuality <= 9)
      arrayOfInt[b++] = -32 + this.options.jpegQuality; 
    if (this.options.requestCursorUpdates) {
      arrayOfInt[b++] = -240;
      arrayOfInt[b++] = -239;
      if (!this.options.ignoreCursorUpdates)
        arrayOfInt[b++] = -232; 
    } 
    arrayOfInt[b++] = -224;
    arrayOfInt[b++] = -223;
    boolean bool = false;
    if (b != this.nEncodingsSaved) {
      bool = true;
    } else {
      for (byte b1 = 0; b1 < b; b1++) {
        if (arrayOfInt[b1] != this.encodingsSaved[b1]) {
          bool = true;
          break;
        } 
      } 
    } 
    if (bool) {
      try {
        this.rfb.writeSetEncodings(arrayOfInt, b);
        if (this.vc != null)
          this.vc.softCursorFree(); 
      } catch (Exception exception) {
        exception.printStackTrace();
      } 
      this.encodingsSaved = arrayOfInt;
      this.nEncodingsSaved = b;
    } 
  }
  
  void setCutText(String paramString) {
    try {
      if (this.rfb != null && this.rfb.inNormalProtocol)
        this.rfb.writeClientCutText(paramString); 
    } catch (Exception exception) {
      exception.printStackTrace();
    } 
  }
  
  void setRecordingStatus(String paramString) {
    synchronized (this.recordingSync) {
      this.sessionFileName = paramString;
      this.recordingStatusChanged = true;
    } 
  }
  
  boolean checkRecordingStatus() throws IOException {
    synchronized (this.recordingSync) {
      if (this.recordingStatusChanged) {
        this.recordingStatusChanged = false;
        if (this.sessionFileName != null) {
          startRecording();
          return true;
        } 
        stopRecording();
      } 
    } 
    return false;
  }
  
  protected void startRecording() throws IOException {
    synchronized (this.recordingSync) {
      if (!this.recordingActive) {
        this.options.getClass();
        this.cursorUpdatesDef = this.options.choices[3].getSelectedItem();
        this.options.getClass();
        this.eightBitColorsDef = this.options.choices[5].getSelectedItem();
        this.options.getClass();
        this.options.choices[3].select("Disable");
        this.options.getClass();
        this.options.choices[3].setEnabled(false);
        this.options.setEncodings();
        this.options.getClass();
        this.options.choices[5].select("No");
        this.options.getClass();
        this.options.choices[5].setEnabled(false);
        this.options.setColorFormat();
      } else {
        this.rfb.closeSession();
      } 
      System.out.println("Recording the session in " + this.sessionFileName);
      this.rfb.startSession(this.sessionFileName);
      this.recordingActive = true;
    } 
  }
  
  protected void stopRecording() throws IOException {
    synchronized (this.recordingSync) {
      if (this.recordingActive) {
        this.options.getClass();
        this.options.choices[3].select(this.cursorUpdatesDef);
        this.options.getClass();
        this.options.choices[3].setEnabled(true);
        this.options.setEncodings();
        this.options.getClass();
        this.options.choices[5].select(this.eightBitColorsDef);
        this.options.getClass();
        this.options.choices[5].setEnabled(true);
        this.options.setColorFormat();
        this.rfb.closeSession();
        System.out.println("Session recording stopped.");
      } 
      this.sessionFileName = null;
      this.recordingActive = false;
    } 
  }
  
  void readParameters() {
    this.host = readParameter("HOST", !this.inAnApplet);
    if (this.host == null) {
      this.host = getCodeBase().getHost();
      if (this.host.equals(""))
        fatalError("HOST parameter not specified"); 
    } 
    this.port = readIntParameter("PORT", 5900);
    readPasswordParameters();
    if (this.inAnApplet) {
      String str1 = readParameter("Open New Window", false);
      if (str1 != null && str1.equalsIgnoreCase("Yes"))
        this.inSeparateFrame = true; 
    } 
    this.showControls = true;
    String str = readParameter("Show Controls", false);
    if (str != null && str.equalsIgnoreCase("No"))
      this.showControls = false; 
    this.offerRelogin = true;
    str = readParameter("Offer Relogin", false);
    if (str != null && str.equalsIgnoreCase("No"))
      this.offerRelogin = false; 
    this.showOfflineDesktop = false;
    str = readParameter("Show Offline Desktop", false);
    if (str != null && str.equalsIgnoreCase("Yes"))
      this.showOfflineDesktop = true; 
    this.deferScreenUpdates = readIntParameter("Defer screen updates", 20);
    this.deferCursorUpdates = readIntParameter("Defer cursor updates", 10);
    this.deferUpdateRequests = readIntParameter("Defer update requests", 0);
    this.debugStatsExcludeUpdates = readIntParameter("DEBUG_XU", 0);
    this.debugStatsMeasureUpdates = readIntParameter("DEBUG_CU", 0);
    this.socketFactory = readParameter("SocketFactory", false);
  }
  
  private void readPasswordParameters() {
    String str = readParameter("ENCPASSWORD", false);
    if (str == null) {
      this.passwordParam = readParameter("PASSWORD", false);
    } else {
      byte[] arrayOfByte1 = { 0, 0, 0, 0, 0, 0, 0, 0 };
      int i = str.length() / 2;
      if (i > 8)
        i = 8; 
      for (byte b = 0; b < i; b++) {
        String str1 = str.substring(b * 2, b * 2 + 2);
        Integer integer = new Integer(Integer.parseInt(str1, 16));
        arrayOfByte1[b] = integer.byteValue();
      } 
      byte[] arrayOfByte2 = { 23, 82, 107, 6, 35, 78, 88, 7 };
      DesCipher desCipher = new DesCipher(arrayOfByte2);
      desCipher.decrypt(arrayOfByte1, 0, arrayOfByte1, 0);
      this.passwordParam = new String(arrayOfByte1);
    } 
  }
  
  public String readParameter(String paramString, boolean paramBoolean) {
    if (this.inAnApplet) {
      String str = getParameter(paramString);
      if (str == null && paramBoolean)
        fatalError(paramString + " parameter not specified"); 
      return str;
    } 
    for (byte b = 0; b < this.mainArgs.length; b += 2) {
      if (this.mainArgs[b].equalsIgnoreCase(paramString))
        try {
          return this.mainArgs[b + 1];
        } catch (Exception exception) {
          if (paramBoolean)
            fatalError(paramString + " parameter not specified"); 
          return null;
        }  
    } 
    if (paramBoolean)
      fatalError(paramString + " parameter not specified"); 
    return null;
  }
  
  int readIntParameter(String paramString, int paramInt) {
    String str = readParameter(paramString, false);
    int i = paramInt;
    if (str != null)
      try {
        i = Integer.parseInt(str);
      } catch (NumberFormatException numberFormatException) {} 
    return i;
  }
  
  void moveFocusToDesktop() {
    if (this.vncContainer != null && 
      this.vc != null && this.vncContainer.isAncestorOf(this.vc))
      this.vc.requestFocus(); 
  }
  
  public synchronized void disconnect() {
    System.out.println("Disconnecting");
    if (this.vc != null) {
      double d1 = (System.currentTimeMillis() - this.vc.statStartTime) / 1000.0D;
      double d2 = Math.round(this.vc.statNumUpdates / d1 * 100.0D) / 100.0D;
      int i = this.vc.statNumPixelRects;
      int j = this.vc.statNumTotalRects - this.vc.statNumPixelRects;
      System.out.println("Updates received: " + this.vc.statNumUpdates + " (" + i + " rectangles + " + j + " pseudo), " + d2 + " updates/sec");
      int k = i - this.vc.statNumRectsTight - this.vc.statNumRectsZRLE - this.vc.statNumRectsHextile - this.vc.statNumRectsRaw - this.vc.statNumRectsCopy;
      System.out.println("Rectangles: Tight=" + this.vc.statNumRectsTight + "(JPEG=" + this.vc.statNumRectsTightJPEG + ") ZRLE=" + this.vc.statNumRectsZRLE + " Hextile=" + this.vc.statNumRectsHextile + " Raw=" + this.vc.statNumRectsRaw + " CopyRect=" + this.vc.statNumRectsCopy + " other=" + k);
      int m = this.vc.statNumBytesDecoded;
      int n = this.vc.statNumBytesEncoded;
      if (n > 0) {
        double d = Math.round(m / n * 1000.0D) / 1000.0D;
        System.out.println("Pixel data: " + this.vc.statNumBytesDecoded + " bytes, " + this.vc.statNumBytesEncoded + " compressed, ratio " + d);
      } 
    } 
    if (this.rfb != null && !this.rfb.closed())
      this.rfb.close(); 
    this.options.dispose();
    this.clipboard.dispose();
    if (this.rec != null)
      this.rec.dispose(); 
    if (this.inAnApplet) {
      showMessage("Disconnected");
    } else {
      System.exit(0);
    } 
  }
  
  public synchronized void fatalError(String paramString) {
    System.out.println(paramString);
    if (this.inAnApplet) {
      Thread.currentThread().stop();
    } else {
      System.exit(1);
    } 
  }
  
  public synchronized void fatalError(String paramString, Exception paramException) {
    if (this.rfb != null && this.rfb.closed()) {
      System.out.println("RFB thread finished");
      return;
    } 
    System.out.println(paramString);
    paramException.printStackTrace();
    if (this.rfb != null)
      this.rfb.close(); 
    if (this.inAnApplet) {
      showMessage(paramString);
    } else {
      System.exit(1);
    } 
  }
  
  void showMessage(String paramString) {
    this.vncContainer.removeAll();
    Label label = new Label(paramString, 1);
    label.setFont(new Font("Helvetica", 0, 12));
    if (this.offerRelogin) {
      Panel panel1 = new Panel(new GridLayout(0, 1));
      Panel panel2 = new Panel(new FlowLayout(0));
      panel2.add(panel1);
      this.vncContainer.setLayout(new FlowLayout(0, 30, 16));
      this.vncContainer.add(panel2);
      Panel panel3 = new Panel(new FlowLayout(1));
      panel3.add(label);
      panel1.add(panel3);
      panel1.add(new ReloginPanel(this));
    } else {
      this.vncContainer.setLayout(new FlowLayout(0, 30, 30));
      this.vncContainer.add(label);
    } 
    if (this.inSeparateFrame) {
      this.vncFrame.pack();
    } else {
      validate();
    } 
  }
  
  public void stop() {
    System.out.println("Stopping applet");
    this.rfbThread = null;
  }
  
  public void destroy() {
    System.out.println("Destroying applet");
    this.vncContainer.removeAll();
    this.options.dispose();
    this.clipboard.dispose();
    if (this.rec != null)
      this.rec.dispose(); 
    if (this.rfb != null && !this.rfb.closed())
      this.rfb.close(); 
    if (this.inSeparateFrame)
      this.vncFrame.dispose(); 
  }
  
  public void enableInput(boolean paramBoolean) {
    this.vc.enableInput(paramBoolean);
  }
  
  public void windowClosing(WindowEvent paramWindowEvent) {
    System.out.println("Closing window");
    if (this.rfb != null)
      disconnect(); 
    this.vncContainer.hide();
    if (!this.inAnApplet)
      System.exit(0); 
  }
  
  public void windowActivated(WindowEvent paramWindowEvent) {}
  
  public void windowDeactivated(WindowEvent paramWindowEvent) {}
  
  public void windowOpened(WindowEvent paramWindowEvent) {}
  
  public void windowClosed(WindowEvent paramWindowEvent) {}
  
  public void windowIconified(WindowEvent paramWindowEvent) {}
  
  public void windowDeiconified(WindowEvent paramWindowEvent) {}
}
 
by

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.