ZeePedia

Learning Basics of JAVA

<< Java Virtual Machine & Runtime Environment
JAVA: Object Oriented Programming >>
img
Web Design & Development ­ CS506
VU
Lesson 3
Learning Basics
Strings
A string is commonly considered to be a sequence of characters stored in memory and accessible as a
unit. Strings in java are represented as objects.
String Concatenation
"+" operator is used to concatenate strings
­  System.out.pritln("Hello" + "World") will print Hello World on console
String concatenated with any other data type such as int will also convert that datatype to
String and the result will be a concatenated String displayed on console. For example,
­
int i = 4;
­
int j = 5;
System.out.println ("Hello" + i)
will print Hello 4 on screen
­
However
System,.out..println( i+j) ;
will print 9 on the console because both i and j are of type int.
Comparing Strings
For comparing Strings never use == operator, use equals method of String class.
­
== operator compares addresses (shallow comparison) while equals compares values (deep
comparison)
E.g string1.equals(string2)
Example Code: String concatenation and comparison
public class StringTest {
public static void main(String[] args) {
int i = 4;
int j = 5;
System.out.println("Hello" + i); // will print Hello4
System.out.println(i + j); // will print 9
String s1 = new String ("pakistan");
String s2 = "pakistan";
if (s1 == s2) {
16
img
Web Design & Development ­ CS506
VU
System.out.println("comparing string using == operator");
}
if (s1.equals( s2) ) {
System.out.println("comparing string using equal method");
}
}
}
On execution of the above program, following output will produce
Taking in Command Line Arguments
In Java, the program can be written to accept command-line-arguments.
Example Code: command-line arguments
/* This Java application illustrates the use of Java command-line
arguments. */
public class CmdLineArgsApp {
public static void main(String[] args){ //main method
System.out.println("First argument " + args[0]);
System.out.println("Second argument " + args[1]);
}//end main
}//End class.
To execute this program, we pass two arguments as shown below:
public void someMethod( ) {
int x; //local variable
System.out.println(x); // compile time error
·
These parameters should be separated by space. .
·
The parameters that we pass from the command line are stored as Strings inside the "args"
17
img
Web Design & Development ­ CS506
VU
array. You can see that the type of "args" array is String.
Example Code: Passing any number of arguments
In java, array knows their size by using the length property. By using, length property we can determine
how many arguments were passed. The following code example can accept any number of arguments
* This Java application illustrates the use of Java
command-line arguments. */
public class AnyArgsApp {
public static void main(String[] args){ //main method
for(int i=0; i < args.length; i++)
System.out.println("Argument:" + i + "value" +args[i]);
}//end main
}//End class.
Output
C:\java AnyArgsApp i can pass any number of arguments
Argument:0 value i Argument:1 value
can Argument:2 value pass
Argument:3 value any Argument:4
value number Argument:5 value of
Argument:6 value arguments
Primitives vs Objects
·
Everything in Java is an "Object", as every class by default inherits from class
"Object" , except a few primitive data types, which are there for efficiency reasons.
·
Primitive Data Types
Primitive Data types of java
boolean, byte
1 byte
char, short
2 bytes
int, float
4 bytes
long, double
8 bytes
·
Primitive data types are generally used for local variables, parameters and instance
variables (properties of an object)
·
Primitive datatypes are located on the stack and we can only access their value, while objects
are located on heap and we have a reference to these objects
·
Also primitive data types are always passed by value while objects are always passed by
reference in java. There is no C++ like methods
18
img
Web Design & Development ­ CS506
VU
­
void someMethod(int &a, int & b ) // not available in java
Stack vs. Heap
Stack and heap are two important memory areas. Primitives are created on the stack while objects
are created on heap. This will be further clarified by looking at the following diagram that is
taken from Java Lab Course.
int num = 5;
Student s = new Student();
Stack
Heap
num
5
0F59
name ali
0F59
Wrapper Classes
Each primitive data type has a corresponding object (wrapper class). These wrapper classes
provides additional functionality (conversion, size checking etc.), which a primitive data type cannot
provide.
Wrapper Use
You can create an object of Wrapper class using a String or a primitive data type
·
Integer num = new Integer(4); or
·
Integer num = new Integer("4");
19
img
Web Design & Development ­ CS506
VU
Note: num is an object over here not a primitive data type
You can get a primitive data type from a Wrapper using the corresponding value function
·
int primNum = num.intValue();
Converting Strings to Numeric Primitive Data Types
To convert a string containing digits to a primitive data type, wrapper classes can help. parseXxx
method can be used to convert a String to the corresponding primitive data type.
String value = "532";
int d = Integer.parseInt(value);
String value = "3.14e6";
double d = Double.parseDouble(value);
The following table summarizes the parser methods available to a java programmer.
Data Type
Convert String using either ...
byte
Byte.parseByte(string )
new Byte(string ).byteValue()
short
Short.parseShort(string )
new Short(string ).shortValue()
int
Integer.parseInteger(string )
new Integer(string ).intValue()
long
Long.parseLong(string )
new Long(string ).longValue()
float
Float.parseFloat(string )
new Float(string ).floatValue()
double
Double.parseDouble(string )
new Double(string ).doubleValue()
Example Code: Taking Input / Output
So far, we learned how to print something on console. Now the time has come to learn how to print
on the GUI. Taking input from console is not as straightforward as in C++. Initially we'll study how to
take input through GUI (by using JOPtionPane class).
The following program will take input (a number) through GUI and prints its square on the console as
well on GUI.
1. import javax.swing.*;
2. public class InputOutputTest {
3. public static void main(String[] args) {
4. //takes input through GUI
5. String input = JOptionPane.showInputDialog("Enter number");
6. int number = Integer.parseInt(input);
7. int square = number * number;
20
img
Web Design & Development ­ CS506
VU
8. //Display square on console
9. System.out.println("square:" + square);
10. //Display square on GUI
11. JOptionPane.showMessageDialog(null, "square:"+ square);
12. System.exit(0);
13. }
14. }
On line 1, swing package was imported because it contains the JOptionPane class that will be used
for taking input from GUI and displaying output to GUI. It is similar to header classes of C++.
On line 5, showInputDialog method is called of JOptionPane class by passing string argument that
will be displayed on GUI (dialog box). This method always returns back a String regardless of whatever
you entered (int, float, double, char) in the input filed.
Our task is to print square of a number on console, so we first convert a string into a number by
calling parseInt method of Integer wrapper class. This is what we done on line number 6.
Line 11 will display square on GUI (dialog box) by using showMessageDialog method of JOptionPane
class. The first argument passed to this method is null and the second argument must be a String.
Here we use string concatenation.
Line 12 is needed to return the control back to command prompt whenever we use
JoptionPane class.
Compile & Execute
21
img
Web Design & Development ­ CS506
VU
Selection & Control Structure
The if-else and switch selection structures are exactly similar to we have in C++. All relational
operators that we use in C++ to perform comparisons are also available in java with same behavior.
Likewise for, while and do-while control structures are alike to C++.
Reference:
1- Java tutorial:
http://www.dickbaldwin.com/java
2- Example code, their explanations and corresponding figures for this handout are taken from the book
JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the
course Web Design and Development and not for any other commercial purpose without the consent of
author.
22