En este ejercicio se verá la creación de una instancia de un objeto usando la palabra reservada "new".
0. Ejecutar el IDE NetBeans.
1. Crear el proyecto NetBeans
Figura-1.10: Creación del proyecto
2. Modificar el código generado ClassAndObject.java como se muestra en Código-1.11.
public class ClassAndObject
{ public static void main(String[] args) { // Create an instance of a class by using a Java language keyword "new". // For example, in order to create an object instance of a String class, // you will do the following String strInstance1 = new String("I am object instance of a String class"); System.out.println("value of strIntance1 = " + strInstance1); // String class a special class for which you can create an instance // of it by assigning a string literal. No other class allows this form of object creation. String strInstance2 = "I am object instance of a String class"; System.out.println("value of strIntance2 = " + strInstance2); } } |
value of strIntance1 = I am object
instance of a String class value of strIntance2 = I am object instance of a String class |
public class ClassAndObject
{ public static void main(String[] args) { // Create an instance of a class by using a Java language keyword "new". // For example, in order to create an object instance of a String class, // you will do the following String strInstance1 = new String("I am object instance of a String class"); System.out.println("value of strIntance1 = " + strInstance1); // String class a special class for which you can create an instance // of it by assigning a string literal. No other class allows this form of object creation. String strInstance2 = "I am object instance of a String class"; System.out.println("value of strIntance2 = " + strInstance2); // Create an object instance of Integer class Integer intInstance1 = new Integer(20); System.out.println("value of intInstance1 = " + intInstance1); // Create another object instance of Integer class Integer intInstance2 = new Integer(30); System.out.println("value of intInstance2 = " + intInstance2); } } |
value of strIntance1 = I am object
instance of a String class value of strIntance2 = I am object instance of a String class value of intInstance1 = 20 value of intInstance2 = 30 |
Se ha visto cómo crear una instancia de objeto de clases Java tales como String e Integer mediante el uso de new
.
Volver al inicio
En este ejercicio se muestra cómo invocar métodos
static y no-static (instance) de una clase. La forma de llamar el método static de una clase se realiza de la siguiente forma:
<Nombre de la clase>.<Nombre del método static> |
Integer.parseInt("25"); //
parseInt() es un método static de la clase Integer |
<Nombre del objeto de una clase>.<nombre del método no-static> |
String str1 = new String("Hello"); //
Crea un objeto de la clase String char x = str1.charAt(0); // Llamada del método de instancia charAt() de la clase String class a través del objeto |
1. Crear un proyecto NetBeans
2. Modificar StaticAndInstanceMethods.java como se muestra en Código-2.11.
public class StaticAndInstanceMethods
{ public static void main(String[] args) { // Create two instances of String class String strInstance1 = new String("I am object instance of a String class"); String strInstance2 = "Live your passion!"; // Invoke an instance method charAt() through an object instance of String class char x = strInstance1.charAt(2); char y = strInstance2.charAt(1); char z = strInstance2.charAt(0); System.out.println("The 3rd char of strInstance1 = " + x); System.out.println("The 2nd char of strInstance2 = " + y); System.out.println("The 1st char of strInstance2 = " + z); // Invoke an instance method equalsIgnoreCase(..) method boolean b = strInstance1.equalsIgnoreCase(strInstance2); String strInstance3 = b? "Yes":"No"; System.out.println("Do strInstance1 and strInstance2 have same string ignoring case? " + strInstance3); // Invoke a static-method, valueOf (int i), of the String class int i = 23; String strInstance4 = String.valueOf(i); System.out.println("value of strInstance4 = " + strInstance4); // You already have used parseInt() static method of the Integer class in // previous exercises. String strInstance5 = new String("34"); // Create an object instance of String class int ii = Integer.parseInt(strInstance5); System.out.println("value of ii = " + ii); } } |
The 3rd char of strInstance1 = a The 2nd char of strInstance2 = i The 1st char of strInstance2 = L Do strInstance1 and strInstance2 have same string ignoring case? No value of strInstance4 = 23 value of ii = 34 |
public class StaticAndInstanceMethods
{ public static void main(String[] args) { // Create two instances of String class String strInstance1 = new String("I am object instance of a String class"); String strInstance2 = "Live your passion!"; // Invoke an instance method charAt() through an object instance of String class char x = strInstance1.charAt(2); char y = strInstance2.charAt(1); char z = strInstance2.charAt(0); System.out.println("The 3rd char of strInstance1 = " + x); System.out.println("The 2nd char of strInstance2 = " + y); System.out.println("The 1st char of strInstance2 = " + z); // Invoke an instance method equalsIgnoreCase(..) method boolean b = strInstance1.equalsIgnoreCase(strInstance2); String strInstance3 = b? "Yes":"No"; System.out.println("Do strInstance1 and strInstance2 have same string ignoring case? " + strInstance3); // Invoke a static-method, valueOf (int i), of the String class int i = 23; String strInstance4 = String.valueOf(i); System.out.println("value of strInstance4 = " + strInstance4); // You already have used parseInt() static method of the Integer class in // previous exercises. String strInstance5 = new String("34"); // Create an object instance of String class int ii = Integer.parseInt(strInstance5); System.out.println("value of ii = " + ii); // The following Código will generate a compile error since you are trying to // invoke a instance method through a class. Fix this compile error. char f = String.charAt(2); } } |
//
endsWith() method String str = "Hello"; System.out.println( str.endsWith( "slo" ) ); // forDIgit() method System.out.println( Character.forDigit(13, 16) ); // floor() method System.out.println( Math.floor(3.14)); // isDigit() method System.out.println( "0=" + Character.isDigit('0')); System.out.println( "A=" +Character.isDigit('A')); |
En este ejercicio se mostrará el paso por valor. Los parámetros de tipo primitivo se pasan por valor mientras que los parámetros de tipo referencia se pasan por referencia. Un array se considera como de tipo referencia aun cuando los elementos contienen tipos primitivos.
1. Crear proyecto NetBeans
public class TestPassByValue
{ public static void main(String[] args) { int i = 10; // Print the value of i System.out.println("start of the main method and i = " + i); // Call method test, which is defined below // and pass int value as a parameter. Since // int is a primitive type, this parameter is passed // by value. test( i ); // print the value of i. please note that i not changed System.out.println("end of the main method and i = " + i); } // Another static method in the TestPassByValue class public static void test(int j){ System.out.println("start of the test method and j = " + j); // change value of parameter i j = 33; System.out.println("end of the test method and j = " + j); } } |
3. Construir y ejecutar el programa
start of the main method and i =
10 start of the test method and j = 10 end of the test method and j = 33 end of the main method and i = 10 |
1. Crear un proyecto NetBeans
public class TestPassByReference
{ public static void main(String[] args) { System.out.println("main: start"); // Create an array of integers and initialize // the array with 10, 11, and 12. int [] ages = {10, 11, 12}; // Print array values. The array should display // 10, 11, 12 for (int i=0; i<ages.length; i++ ){ System.out.println(ages[i]); } System.out.println("main: before calling the test method"); // Call test and pass references to array. // Since the array is a reference type, what is // being passed is a pointer to actual array. test(ages); System.out.println("main: after calling the test method"); // Print array values again. It now should contain changed values. // display the changed values. for (int i=0; i<ages.length; i++ ){ System.out.println(ages[i]); } System.out.println("main: end"); } // Another static method in the TestPassByReference class public static void test(int[] arr){ System.out.println("test: start"); // change values of array for (int i=0; i<arr.length; i++ ){ arr[i] = i + 50; } System.out.println("test: end"); } } |
3. Construir y ejecutar el programa
main: start 10 11 12 main: before calling the test method test: start test: end main: after calling the test method 50 51 52 main: end |
Este ejercicio muestra el concepto de alcance de una variable. También se muestra a declarar tres tipos de variables: static variable, instance variable, y local variable.
1. Creación del proyecto NetBeans
public class ScopeOfVariable
{ public static void main(String[] args) { int var1 = 10; if (var1 < 100){ int var2 = 20; } else { int var2 = 21; } // Access to var1 is allowed so no compile error. System.out.println("value of var1 = " + var1); // Access to var2 is not allowed so compile error will be generated System.out.println("value of var2 = " + var2); } } |
public class ScopeOfVariable
{ public static void main(String[] args) { int var1 = 10; // var2 is now defined in an outer scope int var2 = 15; if (var1 < 100){ //int var2 = 20; var2 = 20; } else { //int var2 = 21; var2 = 21; } // Access to var1 is allowed so no compile error. System.out.println("value of var1 = " + var1); // Access to var2 is now allowed System.out.println("value of var2 = " + var2); } } |
5. Construir y ejecutar el programa
value of var1 = 10 value of var2 = 20 |
En este apartado se va a crear tres tipos de variables: static variable, instance variable, y local variable.
1. Creación del proyecto NetBeans
public class ThreeVariablesTypes
{ // Example of static variable static String myStaticVariable = "static variable"; // Example of instance variable String myInstanceVariable = "instance variable"; /** * @param args the command line arguments */ public static void main(String[] args) { String myLocalVariable = "local variable"; System.out.println("myStaticVariable = " + myStaticVariable); System.out.println("myInstanceVariable = " + myInstanceVariable); System.out.println("myLocalVariable = " + myLocalVariable); } } |
En este ejercicio se va a realizar casting de tipos primitivos y se convierten tipos primitivos en sus respectivas clases Wrapper y viceversa.
1. Creación del proyecto NetBeans
public class CastingPrimitives
{ public static void main(String[] args) { // Implicit casting example 1 int numInt = 10; double numDouble = numInt; System.out.println("int " + numInt + " is implicitly casted to double " + numDouble); // Implicit casting example 2 int numInt1 = 3; int numInt2 = 2; double numDouble2 = numInt1/numInt2; System.out.println("numInt1/numInt2 " + numInt1/numInt2 + " is implicitly casted to double " + numDouble2); // Explicit casting example 1 double valDouble = 10.12; int valInt = (int)valDouble; System.out.println("double " + valDouble + " is explicitly casted to int " + valInt); // Explicit casting example 2 double x = 10.2; int y = 2; int result = (int)(x/y); System.out.println("x/y " + x/y + " is explicitly casted to int " + result); } } |
3. Construir y ejecutar el programa
int 10 is implicitly casted to double
10.0 numInt1/numInt2 0 is implicitly casted to double 0.0 double 10.12 is explicitly casted to int 10 x/y 5.1 is explicitly casted to int 5 |
1. Crear proyecto NetBeans
public class
ConvertingPrimitivesToWrappers { public static void main(String[] args) { // Create Integer object instance Integer dataCount = new Integer(7801); // Convert Integer type into int primitive type using intValue() method int newCount = dataCount.intValue(); System.out.println("int newCount = " + newCount); // Using static method of the Integer wrapper class // to convert a String type to int primitive type String pennsylvania = "65000"; int penn = Integer.parseInt(pennsylvania); System.out.println("int penn = " + penn); // Convert int primitive type into Integer type Integer myInteger = new Integer(penn); System.out.println("Integer myInteger = " + myInteger); } } |
3. Construir y ejecutar el programa
int newCount = 7801 int penn = 65000 Integer myInteger = 65000 |
En este ejercicio se ve cómo comparar objetos (object instances) usando la clase String class como ejemplo.
1. Creación del proyecto NetBeans
public class EqualsTestString
{ /** * @param args the command line arguments */ public static void main(String[] args) { // Declare two String type variables, str1 and str2 String str1, str2; // Initialize the variables. Note that the variables contain // pointers to the actual object instances. str1 = "Life is worth living... with Passion!"; str2 = str1; // Display the values of the str1 and str2 variables System.out.println("String1: " + str1); System.out.println("String2: " + str2); // The "==" notation, when it is used with variables of reference types not // primitive types, means whether the variables point to the same object // instance or not. // Check if str1 and str2 are the same object meaning if the two variables // points to the same String type object instance. System.out.println("Same object? " + (str1 == str2)); // Reinitialize str2 variable. It is now pointing to a new String type object instance. str2 = new String(str1); // Display the values of the str1 and str2 variables System.out.println("String1: " + str1); System.out.println("String2: " + str2); // Check if str1 and str2 are the same object meaning if the two variables // points to the same String type object instance. System.out.println("Same object? " + (str1 == str2)); // Check if str1 and str2 have the same vaule System.out.println("Same value? " + str1.equals(str2)); } } |
3. Construir y ejecutar el programa
String1: Life is worth living... with
Passion! String2: Life is worth living... with Passion! Same object? true String1: Life is worth living... with Passion! String2: Life is worth living... with Passion! Same object? false Same value? true |
En este ejercicio, se usará el método getClass() de la clase Object para encontrar la clase de la instancia del objeto. También se muestra el uso del operador instanceOf operator para encontrar si la instancia de un objeto es de un tipo particular.
1. Creación del proyecto NetBeans
public class GetClassMethod
{ public static void main(String[] args) { // Create String object instance String str1 = "Life is worth living... with Passion!"; // Find out the class information of String object instance // via getClass() method. Note that it returns Class object instance. Class str1Class = str1.getClass(); System.out.println("Class of str1 object instance is " + str1Class); // the String name of the Class object instance. String str1ClassName = str1Class.getName(); System.out.println("Class of str1 object instance is " + str1Class); // Create Integer object instance Integer int1 = new Integer(34); // Find out the class information of Integer object instance // via getClass() method. Note that it returns Class object instance. Class int1Class = int1.getClass(); System.out.println("Class of int1 object instance is " + int1Class); // the String name of the Class object instance. String int1ClassName = int1Class.getName(); System.out.println("Class of int1 object instance is " + int1Class); } } |
3. Construir y ejecutar el programa
Class of str1 object instance is class
java.lang.String Class of str1 object instance is class java.lang.String Class of int1 object instance is class java.lang.Integer Class of int1 object instance is class java.lang.Integer |
1. Creación del proyecto NetBeans
public class instanceofOperator
{ public static void main(String[] args) { // Create String object instance String str1 = "Life is worth living... with Passion!"; Integer int1 = new Integer(40); // Check if str1 is String type using instanceof operator. // Check also if it is Object type. boolean b1 = str1 instanceof String; System.out.println("str1 is String type: " + b1); boolean b2 = str1 instanceof Object; System.out.println("str1 is Object type: " + b2); // Check if int1 is Integer type using instanceof operator. // Check also if it is Object type. b1 = int1 instanceof Integer; System.out.println("int1 is Integer type: " + b1); b2 = int1 instanceof Object; System.out.println("int1 is Object type: " + b2); b2 = int1 instanceof Number; System.out.println("int1 is Number type: " + b2); } } |
3. Construir y ejecutar el programa
str1 is String type: true str1 is Object type: true int1 is Integer type: true int1 is Object type: true int1 is Number type: true |