Showing posts with label Barry Burd. Show all posts
Showing posts with label Barry Burd. Show all posts

Sunday, 29 June 2014

How to Concatenate Strings in Java

This example shows how to concatenate strings i.e. how to join them together:

andrew@UBUNTU:~/Java$ cat prog38.java
public class prog38
{
public static void main (String args[])
  {
  String first_name = "Andrew";
  String surname = "Reid";
  String full_name = first_name + " " + surname;
  System.out.println ("full_name = " + full_name);
  }
}
andrew@UBUNTU:~/Java$ javac prog38.java
andrew@UBUNTU:~/Java$ java prog38
full_name = Andrew Reid
andrew@UBUNTU:~/Java$


Tuesday, 7 May 2013

How to Use Octal Values in Java

You can tell Java that a number is in octal (base 8) by prefixing it with a zero.

In the example below, the variable octal_77 is assigned the value 077 i.e. octal 77. The program then displays the value in decimal (base 10).

UNIX > cat prog21.java
public class prog21
{
public static void main (String args[])
  {
  int octal_77 = 077;
  System.out.println
  ("octal 77 = " + octal_77);
  }
}
UNIX > javac prog21.java
UNIX > java prog21
octal 77 = 63
UNIX > 

You can check the result yourself by converting octal 77 to decimal (base 10) like this:

octal 77 = (in decimal or base 10) (7 x 8) + 7 = 63

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.

Monday, 29 April 2013

How to Copy a long Java Variable Into an int

You might think that you could copy a long variable into an int variable like this:
 
Solaris > cat prog10.java
public class prog10
{
public static void main (String args[])
  {
  int a;
  long b = 100;
  a = b;
  System.out.println ("a = " + a);
  System.out.println ("b = " + b);
  }
}
Solaris >
 
… but you get a compilation error if you try:
 
Solaris > javac prog10.java
prog10.java:7: possible loss of precision
found   : long
required: int
  a = b;
      ^
1 error
Solaris >
 
You have to do it like this instead:
 
Solaris > cat prog11.java
public class prog11
{
public static void main (String args[])
  {
  int a;
  long b = 100;
  a = (int) b;
  System.out.println ("a = " + a);
  System.out.println ("b = " + b);
  }
}
Solaris > javac prog11.java
Solaris > java prog11
a = 100
b = 100
Solaris >

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.