How to print the contents of text inside a set of brackets found in a in a string

Question:
How to print the text inside the brackets from the string: "Here is [some] text"

Answer:
Using a Matcher

Code:
import java.util.regex.*;
 
public class Delimiter {
   public static void main(String[] args) {
      String str = "Here is [some] text";
      System.out.println("str: " + str);    
      Matcher m = Pattern.compile("\\[([^)]+)\\]").matcher(str);
      while(m.find()) {
       System.out.println(m.group(1));    
     }
   }
}

Output:
$ java Delimiter 
str: Here is [some] text
some

Print out all of the System Properties

Code:
import java.util.*;
 
public class ListProperties {
   public static void main(String[] args) {
      Properties props = System.getProperties();
      props.list(System.out);
   }
}

Output:
$ java ListProperties
-- listing properties --
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=/jdk7/jre/lib/amd64
java.vm.version=24.45-b08
java.vm.vendor=Oracle Corporation
java.vendor.url=http://java.oracle.com/
path.separator=:
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg=sun.io
user.country=US
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=unknown
java.vm.specification.name=Java Virtual Machine Specification
user.dir=/tmp/src
java.runtime.version=1.7.0_45-b34
java.awt.graphicsenv=sun.awt.X11GraphicsEnvironment
java.endorsed.dirs=/jdk7/jre/lib/endorsed
os.arch=amd64
java.io.tmpdir=/tmp
line.separator=

java.vm.specification.vendor=Oracle Corporation
os.name=Linux
sun.jnu.encoding=UTF-8
java.library.path=/usr/java/packages/lib/amd64:/usr/lib...
java.specification.name=Java Platform API Specification
java.class.version=51.0
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
os.version=3.2.0-67-generic
user.home=/home/dennis
user.timezone=
java.awt.printerjob=sun.print.PSPrinterJob
file.encoding=UTF-8
java.specification.version=1.7
user.name=dennis
java.class.path=.
java.vm.specification.version=1.7
sun.arch.data.model=64
java.home=/jdk7/jre
sun.java.command=ListProperties
java.specification.vendor=Oracle Corporation
user.language=en
awt.toolkit=sun.awt.X11.XToolkit
java.vm.info=mixed mode
java.version=1.7.0_45
java.ext.dirs=/jdk7/jre/lib/ext:/usr/java/packages/...
sun.boot.class.path=/jdk7/jre/lib/resources.jar:/jdk7/jre...
java.vendor=Oracle Corporation
file.separator=/
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.cpu.isalist=

How can I find out from where a class is loaded from?

Question:
How can I find out from where a class is loaded from?

Code:
public class ClassLocationTest {
   public static void main(String[] args) {
      ClassLocation cl = new ClassLocation();
      System.out.println(cl.getClass().getProtectionDomain().getCodeSource().getLocation());
   }
}
 
class ClassLocation {
}

Output:
$ javac -d /tmp/classes ClassLocationTest.java

$ java -cp /tmp/classes ClassLocationTest
file:/tmp/classes/

How to specify a different directory for your compiled bytecode classes

Use the -d option if  want to specify explicitly where you would like the compiled bytecode class files to go:

$ pwd
/tmp/src

$ ls
HelloWorld.java

$ ls /tmp/classes

$ javac -d /tmp/classes HelloWorld.java

$ ls
HelloWorld.java

$ ls /tmp/classes
HelloWorld.class

$ java -cp /tmp/classes HelloWorld
Hello, World

Whats does @Override mean?

Question:
Whats does @Override mean?

Answer:
The override annotation (@Override) indicates that a method declaration intends on overriding a method declaration in the classes supertype.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.

Code:
public class Animal {
 
   public void speak(){
   }    
 
}
 
class Cat extends Animal{
   @Override
   public void speak(){
      System.out.println("meow");
   }    
}
 

Class implementing two interfaces

Code:
class MyClass implements MyInterfaceOne,MyInterfaceTwo {
 
  public void methodOne(){
      System.out.println("inside methodOne()");
  }
  public void methodTwo(){
      System.out.println("inside methodTwo()");
  }
 
}
 
interface MyInterfaceOne {
  void methodOne();
}
 
interface MyInterfaceTwo {
  void methodTwo();
}
 
public class MyClassTest {
   public static void main(String[] args) {
      MyClass mc = new MyClass();
      mc.methodOne();
      mc.methodTwo();
   }
}
 

Output:
$ java MyClassTest
inside methodOne()
inside methodTwo()

Error: Could not find or load main class HelloWorld.java

My program compiles fine:

$ javac HelloWorld.java


But when I run it I get the following error:

$ java HelloWorld.java
Error: Could not find or load main class HelloWorld.java



Try to run it without the .java extension:

$ java HelloWorld
Hello, World

What is the difference between java and javax?

The prefix java is commonly used for the core packages.

The prefix javax is commonly used for packages that comprise Java standard extensions.

How many packages are there in Java SE 7 API?

Oracle includes 209 packages in the Java SE 7 API.

Here is the link to the API specification for the Java™ Platform, Standard Edition:
Java™ Platform, Standard Edition 7 API Specification


Here is the list:

java.applet
java.awt
java.awt.color
java.awt.datatransfer
java.awt.dnd
java.awt.event
java.awt.font
java.awt.geom
java.awt.im
java.awt.im.spi
java.awt.image
java.awt.image.renderable
java.awt.print
java.beans
java.beans.beancontext
java.io
java.lang
java.lang.annotation
java.lang.instrument
java.lang.invoke
java.lang.management
java.lang.ref
java.lang.reflect
java.math
java.net
java.nio
java.nio.channels
java.nio.channels.spi
java.nio.charset
java.nio.charset.spi
java.nio.file
java.nio.file.attribute
java.nio.file.spi
java.rmi
java.rmi.activation
java.rmi.dgc
java.rmi.registry
java.rmi.server
java.security
java.security.acl
java.security.cert
java.security.interfaces
java.security.spec
java.sql
java.text
java.text.spi
java.util
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
java.util.jar
java.util.logging
java.util.prefs
java.util.regex
java.util.spi
java.util.zip
javax.accessibility
javax.activation
javax.activity
javax.annotation
javax.annotation.processing
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
javax.imageio
javax.imageio.event
javax.imageio.metadata
javax.imageio.plugins.bmp
javax.imageio.plugins.jpeg
javax.imageio.spi
javax.imageio.stream
javax.jws
javax.jws.soap
javax.lang.model
javax.lang.model.element
javax.lang.model.type
javax.lang.model.util
javax.management
javax.management.loading
javax.management.modelmbean
javax.management.monitor
javax.management.openmbean
javax.management.relation
javax.management.remote
javax.management.remote.rmi
javax.management.timer
javax.naming
javax.naming.directory
javax.naming.event
javax.naming.ldap
javax.naming.spi
javax.net
javax.net.ssl
javax.print
javax.print.attribute
javax.print.attribute.standard
javax.print.event
javax.rmi
javax.rmi.CORBA
javax.rmi.ssl
javax.script
javax.security.auth
javax.security.auth.callback
javax.security.auth.kerberos
javax.security.auth.login
javax.security.auth.spi
javax.security.auth.x500
javax.security.cert
javax.security.sasl
javax.sound.midi
javax.sound.midi.spi
javax.sound.sampled
javax.sound.sampled.spi
javax.sql
javax.sql.rowset
javax.sql.rowset.serial
javax.sql.rowset.spi
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.nimbus
javax.swing.plaf.synth
javax.swing.table
javax.swing.text
javax.swing.text.html
javax.swing.text.html.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
javax.tools
javax.transaction
javax.transaction.xa
javax.xml
javax.xml.bind
javax.xml.bind.annotation
javax.xml.bind.annotation.adapters
javax.xml.bind.attachment
javax.xml.bind.helpers
javax.xml.bind.util
javax.xml.crypto
javax.xml.crypto.dom
javax.xml.crypto.dsig
javax.xml.crypto.dsig.dom
javax.xml.crypto.dsig.keyinfo
javax.xml.crypto.dsig.spec
javax.xml.datatype
javax.xml.namespace
javax.xml.parsers
javax.xml.soap
javax.xml.stream
javax.xml.stream.events
javax.xml.stream.util
javax.xml.transform
javax.xml.transform.dom
javax.xml.transform.sax
javax.xml.transform.stax
javax.xml.transform.stream
javax.xml.validation
javax.xml.ws
javax.xml.ws.handler
javax.xml.ws.handler.soap
javax.xml.ws.http
javax.xml.ws.soap
javax.xml.ws.spi
javax.xml.ws.spi.http
javax.xml.ws.wsaddressing
javax.xml.xpath
org.ietf.jgss
org.omg.CORBA
org.omg.CORBA_2_3
org.omg.CORBA_2_3.portable
org.omg.CORBA.DynAnyPackage
org.omg.CORBA.ORBPackage
org.omg.CORBA.portable
org.omg.CORBA.TypeCodePackage
org.omg.CosNaming
org.omg.CosNaming.NamingContextExtPackage
org.omg.CosNaming.NamingContextPackage
org.omg.Dynamic
org.omg.DynamicAny
org.omg.DynamicAny.DynAnyFactoryPackage
org.omg.DynamicAny.DynAnyPackage
org.omg.IOP
org.omg.IOP.CodecFactoryPackage
org.omg.IOP.CodecPackage
org.omg.Messaging
org.omg.PortableInterceptor
org.omg.PortableInterceptor.ORBInitInfoPackage
org.omg.PortableServer
org.omg.PortableServer.CurrentPackage
org.omg.PortableServer.POAManagerPackage
org.omg.PortableServer.POAPackage
org.omg.PortableServer.portable
org.omg.PortableServer.ServantLocatorPackage
org.omg.SendingContext
org.omg.stub.java.rmi
org.w3c.dom
org.w3c.dom.bootstrap
org.w3c.dom.events
org.w3c.dom.ls
org.xml.sax
org.xml.sax.ext
org.xml.sax.helpers

What is a Static Import?

Question:
What is a Static Import?

Answer:
Static imports allow the static items of one class to be referenced in another without qualification.

Code:
import static java.lang.Math.PI;
import static java.lang.Integer.MAX_VALUE;
 
public class StaticImportStatements {
   public static void main(String[] args) {
      System.out.println("PI: " + PI);
      System.out.println("Int max: " + MAX_VALUE);
   }
}

Output:
$ java StaticImportStatements
PI: 3.141592653589793
Int max: 2147483647

Printing a copyright symbol in java

Question:
How can you print a copyright symbol in java?

Answer:
Use the unicode \u00A9.

Code:
public class Copyright {
   public static void main(String[] args) {
      System.out.println("Copyright \u00a9 2014");
   }
}

Output:
$ java Copyright
Copyright © 2014

Printing a percent sign "%" using printf

Question:
How do you print a percent sign "%" using printf?

Answer:
Escaped percent sign is double percent (%%)

Code:
public class PrintPercentSign {
 
   public static void main(String[] args) {
 
      System.out.printf("4 out of 10 is %d%% \n", 40);
 
   }
}

Output:
$ java PrintPercentSign
4 out of 10 is 40% 

Java tip calculator

Code:
import java.util.Scanner;
 
public class TipCalculator {
 
  public static void main(String [] args) {
 
    double rate1 = 0.1;
    double rate2 = 0.15;
    double rate3 = 0.2;
 
    Scanner keyboard = new Scanner(System.in);
 
    System.out.print("Enter the purchase price: ");
    double total = keyboard.nextDouble();
 
    System.out.printf("10%%: %.2f \n", (total*rate1));
    System.out.printf("15%%: %.2f \n", (total*rate2));
    System.out.printf("20%%: %.2f \n", (total*rate3));
  }
}

Output:
$ java TipCalculator
Enter the purchase price: 29.99
10%: 3.00 
15%: 4.50 
20%: 6.00 

Generating random integers in a range

Question:
How do you generate random integers in a range with Java?

Code:
import java.util.Random;
 
public class RandomNumbers {
 
   public static void main(String[] args) {
 
      Random r = new Random();
      int x;
 
      // generate random number between 10 and 20
      int low=10;
      int high=20;
      x = r.nextInt(high-low)+low;
      System.out.println(x);
   }
}

Output:
$ java RandomNumbers
15

How to find if a constantly changing integer has been the same value for 3 seconds

Question:
How to find if a constantly changing integer has been the same value for 3 seconds ant not disturb other actions of the program for those 3 secs.

Code:
import java.util.*;
import java.text.*;
 
public class TimerExample {
 
   static int x=0;
   static int timerx = x;
 
   public static void main(String[] args) {
 
      class MyTimeTask extends TimerTask {
        public void run() {
          if(timerx != x) {
            timerx=x;
            System.out.println("x changed: " + x);
          }
          System.out.println("x: " + x);
        }
      }
 
      Timer timer = new Timer(true);
      timer.schedule(new MyTimeTask(), 0, 3000);
 
      for (int i=0;i<10;i++){
        x=i;
        try {
          Thread.sleep(8000);
        } catch (InterruptedException e) {
        }
      }
   }
}

Output:
$ java TimerExample
x: 0
x: 0
x: 0
x changed: 1
x: 1
x: 1
x: 1
x changed: 2
x: 2
x: 2
x changed: 3
x: 3
x: 3
x: 3
x changed: 4
x: 4
x: 4
x: 4
x changed: 5
x: 5
x: 5
x changed: 6
x: 6
x: 6
x: 6
x changed: 7
x: 7
x: 7
x: 7
x changed: 8
x: 8
x: 8
x changed: 9
x: 9
x: 9
x: 9

Use a loop to display and calculate the sum of the evenly positioned digits in a string

Question:
In Java, how do we use a loop to display and calculate the sum of the evenly positioned digits?

Eg. If input is 29664 then output is 15 (9+6)

Code:
import java.util.*;
 
public class SumOfEvensPositions {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.print("Enter a number: ");
      String str = sc.nextLine();
 
      try {
         Integer.parseInt(str); 
 
         int total=0;
         for(int i=1;i<str.length();i=i+2){
            System.out.println("Pos " + (i+1) + " : "  + str.charAt(i));
            total = total + Character.getNumericValue(str.charAt(i));
         }
         System.out.println("Total: " + total);
 
      } catch(NumberFormatException e) { 
         System.out.println("Invalid number");
      } 
   }
}
 

Output:
$ java SumOfEvensPositions
Enter a number: 29664
Pos 2 : 9
Pos 4 : 6
Total: 15

High Low guessing game without an if statement.

Code:
import java.util.*;
 
public class HighLowGuessingGame {
 
   public static void main(String[] args) {
 
      Random random = new Random();
      Scanner scanner = new Scanner(System.in);
 
      int number = random.nextInt(100)+1;
      int guess = -1;
      int count=0;
 
      while(guess!=number){
         Beginning:
         while (guess!=number) {
            count=count+1;
            System.out.print("Enter a number between 1 and 100: ");
            guess = scanner.nextInt();
 
            while (guess<number) {
               System.out.println("Too low, please try again");
               break Beginning;
            } 
            while (guess>number) {
               System.out.println("Too high, please try again");
               break Beginning;
            } 
         }
      }
 
      System.out.println("Correct, the number was " + number);
      System.out.println("It took you " + count + " trys.");
   }
}

Output:
$ java HighLowGuessingGame
Enter a number between 1 and 100: 50
Too low, please try again
Enter a number between 1 and 100: 75
Too high, please try again
Enter a number between 1 and 100: 63
Too low, please try again
Enter a number between 1 and 100: 69
Too low, please try again
Enter a number between 1 and 100: 72
Too high, please try again
Enter a number between 1 and 100: 70
Correct, the number was 70
It took you 6 trys.

Calculate how many total calories were consumed in cookies

Question:
A bag of cookies holds 40 cookies. There are 10 “serving in the bag and that a serving equals 300 calories. Write a program that asks the user to input how many cookies they actually ate and then reports how many total calories were consumed.

Code:
import java.util.Scanner;
 
public class Cookies {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter how many cookies you ate: ");
 
    int cookieCount = sc.nextInt();
 
    int servingSize = 40/10;
    int caloriesPerCookie = 300/servingSize;
    int totalCalories = cookieCount * caloriesPerCookie;
 
    System.out.println("Total calories consumed: " + totalCalories);
  }
}

Output:
$ java Cookies
Enter how many cookies you ate: 6
Total calories consumed: 450

Calculating and printing the nth prime number

Question:
How to write a java program Given a number n as input, return the value of the nth prime. Note that n is always greater than 0.?

Code:
import java.util.Scanner;
 
public class NthPrime {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter n to compute the nth prime number: ");
 
    int nth = sc.nextInt();
 
    int num, count, i;
    num=1;
    count=0;
 
    while (count < nth){
      num=num+1;
      for (i = 2; i <= num; i++){
        if (num % i == 0) {
          break;
        }
      }
      if ( i == num){
        count = count+1;
      }
    }
    System.out.println("Value of nth prime: " + num);
  }
}

Output:
$ java NthPrime
Enter n to compute the nth prime number: 10
Value of nth prime: 29

Test if the sum of two ints is a power of two?

Question:
How to write a java program that 4 ints have been provided as input. Return true if the sum of any two of them is a power of 2.?

Code:
public class TestSums {
   public static void main(String[] args) {
 
      int vars[] = new int[args.length];
      for(int n=0;n<vars.length;n++){
         try {
            vars[n]= Integer.parseInt(args[n]);
         } catch (NumberFormatException e) { 
            System.out.println(args[n] + " is no a number.");
         }
      }
 
      for(int i=0;i<vars.length;i++){
         for(int j=i+1;j<vars.length;j++){
            System.out.print(vars[i] + "," + vars[j] + ": " );
            System.out.println(sumIsPowerOfTwo(vars[i],vars[j]));
         }
      }
   }
 
   static boolean sumIsPowerOfTwo(int x, int y) {
      int z = x + y;
      return ((z & (z -1)) == 0);
   }
}

Output:
$ java TestSums 2 4 6 8
2,4: false
2,6: true
2,8: false
4,6: false
4,8: false
6,8: false

remainder, quotient, product and average

Question:
Write a Java program to calculate the remainder and quotient of two integer numbers, then calculate the product and the average of the remainder value and quotient value, and show the output.

Code:
public class Example {
   public static void main(String[] args) {
 
      int integer1 = 33;
      int integer2 = 7;
 
      int quotient =  integer1 / integer2;
      int remainder = integer1 % integer2;
 
      int product = quotient * remainder;
      double average = (double)(quotient + remainder) / 2;
 
      System.out.println("Quotient: " + quotient);
      System.out.println("Remainder: " + remainder);
      System.out.println("Product: " + product);
      System.out.println("Average: " + average);
   }
}
 

Output:
$ java Example
Quotient: 4
Remainder: 5
Product: 20
Average: 4.5

Temperature class that will hold a temperature in Fahrenheit and provide methods to convert to Celsius and kelvin

Question:
Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to convert to Celsius and kelvin.

Code:
import java.util.Scanner;
 
public class TemperatureTest {
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter Fahrenheit temperature: ");
    double ftemp = sc.nextDouble(); 
 
    Temperature temp = new Temperature(ftemp);
    System.out.println("The temperature in Fahrenheit is " + temp.getFahrenheit());
    System.out.println("The temperature in Celsius is " + temp.getCelsius());
    System.out.println("The temperature in Kelvin is " + temp.getKelvin());
  }
}
 
class Temperature {
 
  double ftemp;
  Temperature(double ftemp) {
    this.ftemp = ftemp;
  }
 
  double getFahrenheit(){
    return ftemp;
  }
  double getCelsius(){
    return ((double)5/9*(ftemp-32));
  }
  double getKelvin(){
    return (((double)5/9*(ftemp-32))+273);
  }
}

Output:
$ java TemperatureTest
Enter Fahrenheit temperature: -40
The temperature in Fahrenheit is -40.0
The temperature in Celsius is -40.0
The temperature in Kelvin is 233.0

What is the difference between a float and a double in Java?

Question:
What is the difference between a float and a double in Java?

Answer:
The double data type is a double-precision 64-bit IEEE 754 floating point.
The float data type is a single-precision 32-bit IEEE 754 floating point.


See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Code:
public class Ranges {
 
   public static void main(String[] args) {
 
      // double min / max.
      System.out.println("  Double.MAX_VALUE: " + Double.MAX_VALUE);
      System.out.println("  Double.MIN_NORMAL: " + Double.MIN_NORMAL);
 
      // float min / max.
      System.out.println("  Float.MAX_VALUE: " + Float.MAX_VALUE);
      System.out.println("  Float.MIN_VALUE: " + Float.MIN_VALUE);
 
   }
}

Output:
$ java Ranges
  Double.MAX_VALUE: 1.7976931348623157E308
  Double.MIN_NORMAL: 2.2250738585072014E-308
  Float.MAX_VALUE: 3.4028235E38
  Float.MIN_VALUE: 1.4E-45

Shuffle two random size arrays of numbers into one single array

Question:
How to shuffle two random size arrays of numbers into one single array?

Code:
import java.util.*;
 
public class ShuffleArrays {
   public static void main(String[] args) {
      Random r = new Random();
 
      int array1[] = new int[r.nextInt(10)];
      int array2[] = new int[r.nextInt(10)];
      int array3[] = new int[array1.length + array2.length];
 
      System.out.println("array1 size: " + array1.length);
      System.out.println("array2 size: " + array2.length);
      System.out.println("array3 size: " + array3.length);
 
      // populate array1 & array2 with random numbers
      for(int i=0;i<array1.length;i++){
         array1[i]=r.nextInt(100);
      }
      for(int i=0;i<array2.length;i++){
         array2[i]=r.nextInt(100);
      }
 
 
      // populate array3 with contents of array1 & array2
      for(int i=0;i<array1.length;i++){
         array3[i]=array1[i];
      }
      for(int i=0;i<array2.length;i++){
         array3[i+array1.length]=array2[i];
      }
 
      System.out.println("array1: " + Arrays.toString(array1));
      System.out.println("array2: " + Arrays.toString(array2));
      System.out.println("array3: " + Arrays.toString(array3));
 
      // shuffle array3
      int temp;
      int swapindex;
      System.out.println("array3: shuffling");
      for(int i=0;i<array3.length;i++){
         temp=array3[i];
         swapindex=r.nextInt(array3.length);
         array3[i]=array3[swapindex];
         array3[swapindex]=temp;
      } 
      System.out.println("array3: " + Arrays.toString(array3));
   }
}

Output:
$ java ShuffleArrays
array1 size: 9
array2 size: 6
array3 size: 15
array1: [82, 52, 72, 62, 77, 65, 39, 28, 97]
array2: [27, 0, 12, 78, 35, 14]
array3: [82, 52, 72, 62, 77, 65, 39, 28, 97, 27, 0, 12, 78, 35, 14]
array3: shuffling
array3: [72, 39, 77, 82, 27, 78, 62, 97, 12, 0, 35, 65, 14, 52, 28]

Converting seconds to hours, minutes and seconds.

Question:
How to convert seconds to hours/minutes/seconds?

Code:
import java.util.Scanner;
 
public class Seconds {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.print("Enter the number of seconds: ");
      int input = sc.nextInt();
 
      int hours = input / 3600;
      int minutes = (input % 3600) / 60;
      int seconds = (input % 3600) % 60;
 
      System.out.println("Hours: " + hours);
      System.out.println("Minutes: " + minutes);
      System.out.println("Seconds: " + seconds);
 
   }
}

Output:
$ java Seconds
Enter the number of seconds: 50391
Hours: 13
Minutes: 59
Seconds: 51