Articles tagged with: java fundamentals examples
Java Codes »
To find the superclass of an object we first need to call the getClass() method of the object to return the Class-object.The Class object then has a method called getSuperClass() which returns another Class object on which the method getName() can be called.In the example below we call the getSuperClass() method for four different object types: Vector, ArrayList, String and Integer.
import java.util.ArrayList;import java.util.Vector;/** * Main.java * * *#64;a*#117;t*#104;*#111;*#114; www*#46;*#106;a*#118;*#97;d*#98;.c*#111;m */public class Main { /** * Constructor */ public Main() { checkObjectSuperClass(new Vector()); checkObjectSuperClass(new ArrayList()); checkObjectSuperClass(“Test String”); checkObjectSuperClass(new Integer(1)); } /** * Checks which superclass the object has. * * @param testObject The object */ public void checkObjectSuperClass(Object testObject) { System.out.println(“Object …
Java Codes »
To check if a string contains another string the method indexOf() is used. It returns the index in the haystack string where the needle string begins.If the needle string is not present in the haystack string, the value -1 is returned.In the code example below we check two needle strings against a haystack string, one exists and one does not.
/** * Main.java * * *#64;a*#117;t*#104;*#111;r *#119;ww.*#106;a*#118;*#97;*#100;*#98;*#46;*#99;o*#109; */public class Main { /** * Checks if string contains another string. */ public void checkStringContains() { String haystack = “Programming in Java”; String needle1 = “Java”; String needle2 = “Pascal”; int index1 = haystack.indexOf(needle1); int index2 = …
Java Codes »
To convert all lower case characters in a string to upper case, use the method toUpperCase() of the String class.The example below shows how to use it. Note that the method returns a String so you’ll need to assign the return value of the method to a variable (in this case the same variable).
/** * Main.java * * *#64;*#97;uth*#111;*#114; www.*#106;a*#118;ad*#98;.c*#111;m */public class Main { /** * Converts all lower case characters to upper case */ public void stringToUpperCase() { String str = “All Lower Case Characters In This String Will Be Converted To Upper Case”; str = str.toUpperCase(); System.out.println(str); } /** * Starts the …
Java Codes »
>This code example shows how to display the current user logged on to the computer.There is a system property called ‘user.name’ which holds the value of the current user. The property is obtained by calling the getProperty() method of the System class.
>/** * * @*#97;u*#116;hor w*#119;*#119;*#46;*#106;av*#97;d*#98;.*#99;*#111;m */public class Main { public void getCurrentUser() { String currentUser = System.getProperty(“user.name”); System.out.println(“Current user is “ currentUser); } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().getCurrentUser(); }}
