Converting Object into primitives
Can someone help me, i am calling a method that return Object and i want to know how i can cast it as an int or a char or a double
thanx for any help in advance
If the Object type is valid for a cast, just do it:
Object o = 55;
int i = (int)o;
double d = (double)o;
char c = (char)o;
If you attempt to cast something that's not valid - for instance a String, it'll throw
"ClassCastException: Cannot cast java.lang.String to int"
Similar Messages
-
Convert Objects into an XML Document? Possible?
Hello,
Is there a way to convert different objects into an XML File/Document
If I create 10 objects and then I want to create an XML Document
of these objects,is it possible to do this?
AjayHello,
Is there a way to convert different objects into an
XML File/Document
If I create 10 objects and then I want to create an
XML Document
of these objects,is it possible to do this?
Ajayjust override the .toString() method... -
Converting objects into Strings
How would someone convert an object of say (String, int, double, String) into a readable string. I tried the toString() method but all I get is something like this
Student@1f12c4e..I'm not sure I understand "how" to override. The whole point of this project is to use quicksort on a list of students, unfortunately all I get is the address whenever I use the .toStrings() method.
Here's what I have, any help would be greatly appreciated-so very close
import cs1.Keyboard;
import java.io.*;
import java.util.*;
public class StudentTraverse
public static void main(String[] args)
String newName;
int newSocial;
double newGPAs;
String newMajors;
System.out.println("How many Students would you like to add");
Student newStudent;
StudentList12 WORK = new StudentList12();
int total = Keyboard.readInt();
for(int number = total; number > 0; number--)
System.out.println("Name?");
newName = Keyboard.readString();
System.out.println("Social?");
newSocial = Keyboard.readInt();
System.out.println("GPA?");
newGPAs = Keyboard.readDouble();
System.out.println("Major?");
newMajors = Keyboard.readString();
newStudent = new Student(newName, newSocial, newGPAs, newMajors);
System.out.println("Inserting: "+newStudent.toString());
WORK.add(newStudent);
for(total = 0; total < WORK.size(); total++)
System.out.println("top" total": "+WORK.top(total).toString());
try
BufferedReader in = new BufferedReader(new FileReader("LIST.out"));
while (in.ready())
// Print file line to scree
System.out.println (in.readLine());
in.close();
catch (Exception e)
System.err.println("File input error");
public class StudentNode
public Student student;
public StudentNode next;
public StudentNode()
next = null;
student = null;
public StudentNode(Student d, StudentNode n)
student = d;
next = n;
public void setNext(StudentNode n)
next = n;
public void setData(Student d)
data = d;
public StudentNode getNext()
return next;
public Student getData()
return data;
public String toString()
return ""+data;
public StudentNode(Student newStudent)
METHOD NAME: StudentNode
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Acts as a node for the Student list
ALGORITHM:Acts as node for the list
INSTANCE VARIABLES: none
student = newStudent;
next = null;
public class Student
private String name;
private int social;
private double GPA;
private String Major;
public Student(String newName, int newSocial, double newGPAs, String newMajors)
METHOD NAME: Student
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: The actual Student class, determines what is allowed in the array
ALGORITHM:Declare what variables will be needed for the program
INSTANCE VARIABLES: String name, int social, double GPA, String Major
name = newName;
social = newSocial;
GPA = newGPAs;
Major = newMajors;
import java.io.*;
import cs1.Keyboard;
import java.io.BufferedWriter;
import java.util.*;
public class StudentList12
private StudentNode list;
static int i = 0;
public StudentList12()
METHOD NAME: StudentList12
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Declares the Node
ALGORITHM:Declare the Node
INSTANCE VARIABLES: none
list = null;
public boolean isEmpty()
return list == null;
public int size()
return i;
public void add(Student newStudent)
METHOD NAME: add
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Let's users add objects to the array of objects
ALGORITHM:Traverses the current list and adds object to the end
INSTANCE VARIABLES: none
list = new StudentNode(newStudent, list);
i++;
current = current.next;
current.next = node;
public Student remove()
if(isEmpty())
return null;
StudentNode tmp = list;
list = tmp.getNext();
i--;
return tmp.getData();
public void insertEnd(Student newStudent)
if(isEmpty())
add(newStudent);
else
StudentNode t = list;
while(t.getNext() != null)
t=t.getNext();
StudentNode tmp = new StudentNode(newStudent, t.getNext());
t.setNext(tmp);
i++;
public Student removeEnd()
if(isEmpty())
return null;
if(list.getNext() == null)
return remove();
StudentNode t = list;
while(t.getNext().getNext() != null)
t = t.getNext();
Student newStudent = t.getNext().getData();
t.setNext(t.getNext().getNext());
i--;
return newStudent;
public Student top(int n)
StudentNode t = list;
for(int i = 0; i <n && t != null; i++)
t = t.getNext();
return t.getData();
public void writeToFile(int n)
int z = n;
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
for(int counter = z; counter >= 0; counter--)
System.out.println(counter);
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
out.write(list.toString());
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
} -
I'm using java reflection to return value of an attribute from a Class. The attribute is a float primitive. However, the return form is an Object. How do I cast it into the float primitive again?
Thanks.
LGFrom the API for Method.invoke: >>if the value has a primitive type, it is first appropriately wrapped in an object<<
So if the method returns a float primitive, Method.invoke will return a Float object. -
Conversion of object into integer
hi
How to convert Object into integer.
I want to get value of JTable cell.So im doing
for(int i=0;i<4i++)
String value=(String) JTable.getValueAt(i,2);
s.o.p("Table value :"+JTable.getValueAt(i,2));
int changedValue=Integer.parseInt(Value);
s.o.p("Changed value :"+value);
}JTable.getValueAt(0,2) : 0
JTable.getValueAt(1,2) : 0
JTable.getValueAt(2,2) : 2
JTable.getValueAt(3,2) : 4
Theses are the respective values of the respective row positions
Im able to get values of 1st row and 2nd row which are of 0 values
But the value of third row and 4th row im gettin an exception
java.lang.Integer cannot cast to java.lang.String
please help anyoneIf the data in the model is of type Integer you can't cast it to String.
You need to cast this to Integer and call intValue method to get as int.
If you want further help post a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html] that demonstrates the problem. -
How do I (or can I) convert an embedded smart object into a linked smart object
If I start with an embedded Smart Object (S.O)., can I easily convert in into a linked type of S.O.? I have not seen this feature available in the tooling yet. Please advise.
Since an embedded smart object is, well, embedded, there's no way to just convert. You'll have to point a link somewhere.
If you want to keep the smart object as is, open it and "Save As" to a new location, then link to that (Place Linked). Then delete the old. -
How can I convert table object into table record format?
I need to write a store procedure to convert table object into table record. The stored procedure will have a table object IN and then pass the data into another stored procedure with a table record IN. Data passed in may contain more than one record in the table object. Is there any example I can take a look? Thanks.
I'm afraid it's a bit labourious but here's an example.
I think it's a good idea to work with SQL objects rather than PL/SQL nested tables.
SQL> CREATE OR REPLACE TYPE emp_t AS OBJECT
2 (eno NUMBER(4)
3 , ename VARCHAR2(10)
4 , job VARCHAR2(9)
5 , mgr NUMBER(4)
6 , hiredate DATE
7 , sal NUMBER(7,2)
8 , comm NUMBER(7,2)
9 , deptno NUMBER(2));
10 /
Type created.
SQL> CREATE OR REPLACE TYPE staff_nt AS TABLE OF emp_t
2 /
Type created.
SQL> Now we've got some Types let's use them. I've only implemented this as one public procedure but you can see the principles in action.
SQL> CREATE OR REPLACE PACKAGE emp_utils AS
2 TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
3 PROCEDURE pop_emp (p_emps in staff_nt);
4 END emp_utils;
5 /
Package created.
SQL> CREATE OR REPLACE PACKAGE BODY emp_utils AS
2 FUNCTION emp_obj_to_rows (p_emps IN staff_nt) RETURN EmpCurTyp IS
3 rc EmpCurTyp;
4 BEGIN
5 OPEN rc FOR SELECT * FROM TABLE( CAST ( p_emps AS staff_nt ));
6 RETURN rc;
7 END emp_obj_to_rows;
8 PROCEDURE pop_emp (p_emps in staff_nt) is
9 e_rec emp%ROWTYPE;
10 l_emps EmpCurTyp;
11 BEGIN
12 l_emps := emp_obj_to_rows(p_emps);
13 FETCH l_emps INTO e_rec;
14 LOOP
15 EXIT WHEN l_emps%NOTFOUND;
16 INSERT INTO emp VALUES e_rec;
17 FETCH l_emps INTO e_rec;
18 END LOOP;
19 CLOSE l_emps;
20 END pop_emp;
21 END;
22 /
Package body created.
SQL>Looks good. Let's see it in action...
SQL> DECLARE
2 newbies staff_nt := staff_nt();
3 BEGIN
4 newbies.extend(2);
5 newbies(1) := emp_t(7777, 'APC', 'CODER', 7902, sysdate, 1700, null, 40);
6 newbies(2) := emp_t(7778, 'J RANDOM', 'HACKER', 7902, sysdate, 1800, null, 40);
7 emp_utils.pop_emp(newbies);
8 END;
9 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM emp WHERE deptno = 40
2 /
EMPNO ENAME JOB MGR HIREDATE SAL COMM
DEPTNO
7777 APC CODER 7902 17-NOV-05 1700
40
7778 J RANDOM HACKER 7902 17-NOV-05 1800
40
SQL> Cheers, APC -
Error : while converting a WD ABAP object into SAP Transaction
Hi,
I am trying to converting a WD ABAP object into SAP Transaction but i am getting the following error while executing the transaction :
Network Access Message: The page cannot be displayed
Technical Information (for Support personnel)
Error Code: 502 Proxy Error. The specified Secure Sockets Layer (SSL) port is not allowed. ISA Server is not configured to allow SSL requests from this port. Most Web browsers use port 443 for SSL requests. (12204)
IP Address: 10.114.6.144
Date: 4/7/2011 10:41:
Please help.> ISA Server is not configured to allow SSL requests from this port. Most Web browsers use port 443 for SSL requests. (12204)
This seems to be your specific network configuration. It seems that your corporate network is blocking HTTPS requests which don't use port 443. Your ABAP system is configured to use a port other than 443. Either talk to your basis admins about changing your ABAP system configuration to use port 443 or talk to your network administrators to allow whichever port the ABAP system is running on. -
Converting object wrapper type array into equivalent primary type array
Hi All!
My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
//Method signature
Object createArray( Class clazz, String value ) throws Exception;
//and usage should be as follows:
Object arr = createArray( Integer.class, "2%%3%%4" );
//"arr" will be passed as a parameter of a method again via reflection
public void compute( Object... args ) {
a = (int[])args[0];
//or
Object arr = createArray( Double.class, "2%%3%%4" );
public void compute( Object... args ) {
b = (double[])args[0];
//and the method implementation -
Object createArray( Class clazz, String value ) throws Exception {
String[] split = value.split( "%%" );
//create array, e.g. Integer[] or Double[] etc.
Object[] o = (Object[])Array.newInstance( clazz, split.length );
//fill the array with parsed values, on parse error exception will be thrown
for (int i = 0; i < split.length; i++) {
Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
o[i] = meth.invoke( null, new Object[]{ split[i] });
//here convert Object[] to Object of type int[] or double[] etc...
/* and return that object*/
//NB!!! I want to avoid the following code:
if( o instanceof Integer[] ) {
int[] ar = new int[o.length];
for (int i = 0; i < o.length; i++) {
ar[i] = (Integer)o;
return ar;
} else if( o instanceof Double[] ) {
//...repeat "else if" for all primary types... :(
return null;
Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
Did I make myself clear? :)
Thanks in advance,
Pavel GrigorenkoI think I've found the answer myself ;-)
Never thought I could use something like int.class or double.class,
so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
and the easy solution is the following -
Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
for (int j = 0; j < split.length; j++) {
Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
Object val = meth.invoke( null, new Object[]{ split[j] });
Array.set( primeArray, j, val );
}where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc. -
Converting Array Objects into ArrayCollections
Hi,
I am facing problem with converting Array Objects into ArrayCollections. How can i convert Array Objects into ArrayCollections. If any one knows how can we do that Pl reply.
Thanks in advance to all
Regards
subbareddy.pHi Bhasker,
thanks for u r reply. Here i attached screen shot of my server "data.result".
My proxy varaible contains
My object varaible "obj" contains
After parsing the result my arraycollection contains, (i mean after converting Object to Array to ArrayCollection) the below information. For information Pl find the attached arraycollection.png image. In the attached image my arraycollection name is "users".
Here i pasted the code that i used to convert "ObjectProxy" to "ArrayCollection"
var proxy:ObjectProxy = ObjectProxy(data.result);
var obj:Object = proxy.object_proxy::object;
var arrycoll:Array = ArrayUtil.toArray(obj);
model.users = new ArrayCollection(arrycoll);
Regards
sss -
API for converting a Java object into XML?
Do you know of any Java API that I could use to convert a Java
object into its equivalent XML representation?
For example if I have a class called "Foo" with variables va, vb
and I have an instance of Foo with va having the value 1 and vb
having the value 2, I would like be able to generate the
following XML fragment:
<Foo>
<va>1</va>
<vb>2</vb>
</Foo>
Thanks,
-- Rob
nullRob Tan (guest) wrote:
: Do you know of any Java API that I could use to convert a Java
: object into its equivalent XML representation?
: For example if I have a class called "Foo" with variables va,
vb
: and I have an instance of Foo with va having the value 1 and
vb
: having the value 2, I would like be able to generate the
: following XML fragment:
: <Foo>
: <va>1</va>
: <vb>2</vb>
: </Foo>
: Thanks,
: -- Rob
There is none that I know of.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
null -
Convert an Object into a String
Good day to everyone. I am trying to do a little coding in which a user will input his desired username. I want to check the database if the desired username of the current user is existing, so there'll be no duplication. I'm using JPA for the model and JSF for the controller and view.
Here's my Model.
@Entity
public class WebUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String lastName;
private String firstName;
private String middleName;
private String username;
private String password;
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof WebUser)) {
return false;
WebUser other = (WebUser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
return "web.model.WebUser[id=" + id + "]";
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getMiddleName() {
return middleName;
public void setMiddleName(String middleName) {
this.middleName = middleName;
public String getUsername() {
return username;
public void setUsername(String username) {
this.username = username;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;
}The controller and jsp are auto-generated from Netbeans. My question is, how will I convert the 'WebUser' object into a String so I can compare the value from input text to the value in the database?
Here is my validation method inside WebUserController.java
public void validateUsername(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
String newUsername = (String) value;
System.out.println("new user name: " +newUsername);
System.out.println("component: " +component);
int webUserSize;
StringBuffer sb = new StringBuffer();
//webUsers.toString();
if ((webUsers == null) || (webUsers != null)) {
System.out.println("web users null");
List<WebUser> allWebUsers = getWebUsers();
webUserSize = allWebUsers.size();
System.out.println("all web users: " +allWebUsers);
System.out.println("size " +webUserSize);
for(int i=1; i<=webUserSize; ++i) {
sb.append(allWebUsers);
System.out.println("username: " +sb.append(allWebUsers));
}Honestly I'm new to java and having a hard time with this one. Hope someone can help me. Thanks a lot.
I know my code is a mess. :(Thanks for the help guys! I used the "unique constraint" annotation of JPA and my problem is solved.
Here's the code:
@Entity
@Table(
name="WebUser",
uniqueConstraints={@UniqueConstraint(columnNames={"username"})}
public class WebUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String lastName;
private String firstName;
private String middleName;
private String username;
private String password;
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof WebUser)) {
return false;
WebUser other = (WebUser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
//return "web.model.WebUser[id=" + id + "]";
return "web.model.User[username=" + username +"]";
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getMiddleName() {
return middleName;
public void setMiddleName(String middleName) {
this.middleName = middleName;
public String getUsername() {
return username;
public void setUsername(String username) {
this.username = username;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;
}Thanks again guys! -
Converting EJB Object into XML
All:
Suppose I have an EJB that is named MyDog, it has attributes as follows:
name
breed
weight
age
Is there a way to convert this Object into an XML document? Something like:
<?xml version=\"1.0\" ?>
<MyDog>
<name>Bubba</name>
<breed>Australian Shepherd</breed>
<weight>65 lbs</weight>
<age>6 years old</age>
</MyDog>
I can't find any information on doing this - any ideas, links, etc? There has to be a way to do this, but I can't find it. I'm welcome to any ideas out there!check JAXB - might be usefull for you: http://java.sun.com/xml/jaxb/index.html
-
How to convert bytes[] into File object
hi
how to convert byte array into File object
pls.. help me
Regards
srinurrrr007 wrote:
Hi,
How to convert bytes[] into multipage File object?? ]There's no such thing as a "multipage File object." You ought to re-read this thread closely, and read the [API docs for File|http://java.sun.com/javase/6/docs/api/java/io/File.html] to clear up your confusion about what a File object is.
I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream. Then you need a pdf API, like iText or fop. You can't just concatenate pdf files, word docs, excel sheets, etc., like you can text files. Google for java pdf api. -
How to convert bytes[] into multipage File object
Hi,
How to convert bytes[] into multipage File object??
I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream.
Thanks for you help in advance..Only text format allows you to concatenate two files together to get a longer files.
Most formats have a header and a footer and so you cannot simply add one to the other.
You need to use a PDF API which will allow you to build the new document (if one exists)
Maybe you are looking for
-
Can't add music to iPhone 5s and songs not deleting off phone
Tried restarting phone several times and this has not resolved the issue. I have deleted a bunch of music off of my phone... when I plug into iTunes, the songs do not show in iTunes but remain on my phone... also when I try to add new music - it won'
-
Cannot add items to DOCK. Dock bar near end?
I cannot add items to the dock and the dock bar is near the end of the dock listing. I cannot move the bar.
-
Swf demo files won't play in flash file on website
Using Captivate 4, I created a project and published to a folder (as Flash 8). The main flash file has 4 swf demo files that are supposed to play on one of the slides; I uploaded all the published files (swf, js, htm) into a folder within my website'
-
Regarding PO version to be created before output
Hi, I have version managment active in my all document types for PO. But the problem is user changes PO in ME22N, no version is created until output message is taken in ME9F. I wan that after the final release of PO, if any body changes PO using ME22
-
My daughter's iphone got wet and camera does not work. She lives in Madbury, NH 03823. Where can she take it for repair?