Showing posts with label Joshua Bloch. Show all posts
Showing posts with label Joshua Bloch. Show all posts

Saturday, 28 June 2014

How to Extract a Character from a String in Java

This example shows how to define a string then extract the character at a given position in that string. It does this using the String.charAt() method. Note that character positions are numbered from zero, not one. The first part uses a string variable whereas the second uses a string literal:

andrew@UBUNTU:~/Java$ cat prog37.java
public class prog37
{
public static void main (String args[])
  {
  String Andrews_name = "Andrew";
  char first_letter = Andrews_name.charAt(0);
  System.out.println
   ("1st letter of Andrew = " + first_letter);
  char fourth_letter = "Andrew".charAt(3);
  System.out.println
   ("4th letter of Andrew = " + fourth_letter);
  }
}
andrew@UBUNTU:~/Java$ javac prog37.java
andrew@UBUNTU:~/Java$ java prog37
1st letter of Andrew = A
4th letter of Andrew = r
andrew@UBUNTU:~/Java$



Thursday, 25 April 2013

Java Short Integers

These are 16-bit signed integers. They can store values between -32768 and +32767 both inclusive. If you try to assign numbers outside this range, you get a compilation error: 

UBUNTU > cat prog5.java
public class prog5
{
public static void main (String args[])
  {
  // Declare a short integer:
  short num1;

  // Try to assign some invalid values:
  num1 = -32769;
  num1 = 32768;
  }
}
UBUNTU > javac prog5.java
prog5.java:9: possible loss of precision
found   : int
required: short
  num1 = -32769;
          ^
prog5.java:10: possible loss of precision
found   : int
required: short
  num1 = 32768;
         ^
2 errors
UBUNTU >

...but numbers within the range are accepted:

UBUNTU > cat prog6.java
public class prog6
{
public static void main (String args[])
  {
  // Declare a short integer:
  short num1;

  // Assign the minimum valid value:
  num1 = -32768;

  // Display the value:
  System.out.println("num1 = " + num1);

  // Assign the maximum valid value:
  num1 = 32767;

  // Display the value:
  System.out.println("num1 = " + num1);
  }
}
UBUNTU > javac prog6.java
UBUNTU > java prog6
num1 = -32768
num1 = 32767
UBUNTU >


If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.