Download COMPUTER SCIENCE DESIGN and more Exams Compilers in PDF only on Docsity!
Web Design and Development
CS
Lecture 1: Java Features
This handout is a traditional introduction to any language features. You might not be able to comprehend some of the features fully at this stage but don’t worry, you’ll get to know about these as we move on with the course.
1.1 Design Goals of Java
The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at development of software that can run on different platforms like Windows, Linux and Solaris etc.
1.1.1 Right Language, Right Time
Java came on the scene in 1995 to immediate popularity.
Before that, C and C++ dominated the software development o compiled, no robust memory model, no garbage collector causes memory leakages, not great support of built in libraries
Java brings together a great set of "programmer efficient" features o Putting more work on the CPU to make things easier for the programmer.
1.1.2 Java - Buzzwords (Vocabulary)
From the original Sun Java whitepaper: "Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multi- threaded, and dynamic language."
Here are some original java buzzwords.
1.1.3 Java -- Language + Libraries
Java has two parts. o The core language -- variables, arrays, objects The Java Virtual Machine (JVM) runs the core language The core language is simple enough to run on small devices phones, smart cards, PDAs. o The libraries Java includes a large collection of standard library classes to provide "off the shelf" code. (Useful built-in classes that comes with the language to perform basic tasks) Example of these classes is String, ArrayList, HashMap, StringTokenizer (to break string into substrings), Date ... Java programmers are more productive in part because they have access to a large set of standard, well documented library classes.
1.1.4 Simple
Very similar C/C++ syntax, operators, etc.
The core language is simpler than C++ -- no operator overloading, no pointers, no multiple inheritance
The way a java program deals with memory is much simpler than C or C++.
1.1.5 Object-Oriented
Java is fundamentally based on the OOP notions of classes and objects.
Java uses a formal OOP type system that must be obeyed at compile-time and run-time.
This is helpful for larger projects, where the structure helps keep the various parts consistent. Contrast to Perl, which has a more anything-goes feel.
1.1.6 Distributed / Network Oriented
Java is network friendly -- both in its portable, threaded nature, and because Common networking operations are built-in to the Java libraries.
1.1.7 Robust / Secure / Safe
Java is very robust o Both, vs. unintentional errors and vs. malicious code such as viruses. o Java has slightly worse performance since it does all this checking. (Or put the other way, C can be faster since it doesn't check anything.)
The JVM "verifier" checks the code when it is loaded to verify that it has the correct Structure -- that it does not use an uninitialized pointer, or mix int and pointer types. This is one-time "static" analysis -- checking that the code has the correct structure without running it.
The JVM also does "dynamic" checking at runtime for certain operations, such as pointer and array access, to make sure they are touching only the memory they should. You will write code that runs into
As a result, many common bugs and security problems (e.g. "buffer overflow") are not possible in java. The checks also make it easier to find many common bugs easy, since they are caught by the runtime checker.
You will generally never write code that fails the verifier, since your compiler is smart enough to only generate correct code. You will write code that runs into the runtime checks all the time as you debug -- array out of bounds, null pointer.
Java also has a runtime Security Manager can check which operations a particular piece of code is allowed to do. As a result, java can run untrusted code in a "sandbox" where, for example, it can draw to the screen but cannot access the local file system.
1.1.8 Portable
"Write Once Run Anywhere", and for the most part this works.
Not even a recompile is required -- a Java executable can work, without change, on any Java enabled platform.
1.1.9 Support for Web and Enterprise Web Applications
Java provides an extensive support for the development of web and enterprise
1.1.15 Microsoft vs. Java
Microsoft hates Java, since a Java program (portable) is not tied to any particular operating system. If Java is popular, then programs written in Java might promote non-Microsoft operating systems. For basically the same reason, all the non- Microsoft vendors think Java is a great idea.
Microsoft's C# is very similar to Java, but with some improvements, and some questionable features added in, and it is not portable in the way Java is. Generally it is considered that C# will be successful in the way that Visual Basic is: a nice tool to build Microsoft only software.
Microsoft has used its power to try to derail Java somewhat, but Java remains very popular on its merits.
1.1.16 Java Is For Real
Java has a lot of hype, but much of it is deserved. Java is very well matched for many modern problem
Using more memory and CPU time but less programmer time is an increasingly appealing tradeoff.
Robustness and portability can be very useful features
A general belief is that Java is going to stay here for the next 10-20 years
1.1.17 References
Majority of the material in this handout is taken from the first handout of course cs193j at Stanford.
The Java™ Language Environment, White Paper, by James Gosling & Henry McGilton - Java’s Sun site: http://java.sun.com - Java World : www.javaworld.com
When you write a program in C++ it is known as source code. The C++ compiler converts this source code into the machine code of underlying system (e.g. Windows) If you want to run that code on Linux you need to recompile it with a Linux based compiler. Due to the difference in compilers, sometimes you need to modify your code. Java has introduced the concept of WORA (write once run anywhere). When you write a java program it is known as the source code of java. The java compiler does not compile this source code for any underlying hardware system, rather it compiles it for a software system known as JVM (This compiled code is known as byte code). We have different JVMs for different systems (such as JVM for Windows, JVM for Linux etc). When we run our program the JVM interprets (translates) the compiled program into the language understood by the underlying system. So we write our code once and the JVM runs it everywhere according to the underlying system. This concept is discussed in detail below
2.1.1 Byte code
Java programs (Source code) are compiled into a form called Java bytecodes.
The Java compiler reads Java language source (.java) files, translates the source into Java bytecodes, and places the bytecodes into class (.class) files.
The compiler generates one class file for each class contained in java source file.
Java program normally go through five phases. These are
Edit,
Compile,
Load,
Verify and
Execute We look over all the above mentioned phases in a bit detail. First consider the following figure that summarizes the all phases of a java program.
Java API classes
Java Runtime Environment (JRE)
Java Virtual Machine
Operating Systems (Windows, UNIX, etc)
Hardware (Intel, Alpha, Motorola, etc)
2.2.1 Phase 1: Edit
Phase 1 consists of editing a file. This is accomplished with an editor program. The programmer types a java program using the editor like notepad, and make corrections if necessary.
When the programmer specifies that the file in the editor should be saved, the program is stored on a secondary storage device such as a disk. Java program file name ends with a .java extension.
On Windows platform, notepad is a simple and commonly used editor for the beginners. However java integrated development environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM’s Eclipse Java built-in editors that are smoothly integrated into the programming environment.
Note: j2se also called jdk (java development kit). You can also use the previous versions like jdk 1.4 or 1.3 etc. but it is recommended that you use either jdk1.4 or jdk5.
Install j2se5.0 on your system Note: For the rest of this handout, assume that j2se is installed in C:\Program Files\Java\jdk1.5.
2.3.2 Environment Setting
Once you successfully installed the j2se, the next step is environment or path setting. You can accomplish this in either of two ways.
2.3.2.1 Temporary Path Setting
Open the command prompt from Start -> Programs -> Accessories -> Command Prompt. The command prompt screen would be opened in front of you.
Write the command on the command prompt according to the following format path = < java installation directory\bin >
So, according to handout, the command will look like this path = C:\Program Files\Java\jdk1.5.0\bin
To Test whether path has been set or not, write javac and press ENTER. If the list of options displayed as shown in the below figure means that you have successfully completed the steps of path setting. The above procedure is illustrates in the given below picture.
Note: The issue with the temporary path setting is you have to repeat the above explained procedure again and again each time you open a new command prompt window. To avoid this overhead, it is better to set your path permanently
C:>path=C:\Programs Files\Java\jdk1.5.0\bin C:>javac Usage: javac Where possible options include: -g Generate all debugging info -g:none Generate no debugging info -g:{lines, vars, source} Generate only some debugging -nowarn Generate no warnings -verbose Output source messages about what t -deprecation Output source locations wher Sed -classpath Specify where to finde user c -cp Specify where to find user c -sourcepath Specify where to find input -bootclasspath Override location of bootstr -extdirs Override location of install
C:\ WINDOWS\system32\cmd.exe ‐ X
2.3.2.2 Permanent Path Setting
In Windows NT (XP, 2000), you can set the permanent environment variable.
Right click on my computer icon click on properties as shown below
A System Properties frame would appear as shown in the picture.
1./The HelloWorldApp class implements an application that 2.simply displays "Hello World!" to the standard output. 3./
public class HelloWorldApp { 5.public static void main(String[] args) { 6.//Display the string. No global main 7.System.out.println(“Hello World”);
}
}
To save your program, move to File menu and choose save as option.
Save your program as “HelloWorldApp.java” in some directory. Make sure to add double quotes around class name while saving your program. For this example create a folder known as “examples” in D: drive Note: Name of file must match the name of the public class in the file (at line 4). Moreover, it is case sensitive. For example, if your class name is MyClasS, than file name must be MyClasS. Otherwise the Java compiler will refuse to compile the program. For the rest of this handout, we assume that program is saved in D:\examples directory.
2.4.2 HelloWorldApp Described
Lines 1- o Like in C++, You can add multiple line comments that are ignored by the compiler.
Lines 4 o Line 4 declares the class name as HelloWorldApp. In java, every line of code must reside inside class. This is also the name of our program (HelloWorldApp.java).The compiler creates the HelloWorldApp.class if this program successfully gets compiled.
Lines 5 o Line 5 is where the program execution starts. The java interpreter must find this defined exactly as given or it will refuse to run the program. (However you can change the name of parameter that is passed to main. i.e. you can write String[] argv or String[] someParam instead of String[] args) o Other programming languages, notably C++ also use the main()declaration as the starting point for execution. However the main function in C++ is global and resides outside of all classes where as in Java the main function must reside inside a class. In java there are no global variables or functions. The various parts of this main function declaration will be covered at the end of this handout.
Lines 6 o Again like C++, you can also add single line comment
Lines 7 o Line 7 illustrates the method call. The println() method is used to print something on the console. In this example println() method takes a string argument and writes it to the standard output i.e. console.
Lines 8- o Line 8-9 of the program, the two braces, close the method main() and the classHelloWorldApp respectively.
2.4.3 Compiling and Running HelloWorldApp
Open the command prompt from Start -> Program Files -> Accessories. OR alternatively you can write cmd in the run command window.
Write cd.. to came out from any folder, and cd [folder name] to move inside the specified directory. To move from one drive to another, use [Drive Letter]: See figure given below
After reaching to the folder or directory that contains your source code, in our case HelloWorldApp.java.
Use “javac” on the command line to compile the source file ( “.java” file).
D:\examples> javac HelloWorld.java
If program gets successfully compiled, it will create a new file in the same directory named HelloWorldApp.class that contains the byte-code.
Use “java” on the command line to run the compiled .class file. Note “.class” would be added with the file name. - D:\examples> java HelloWorld
You can see the Hello World would be printed on the console. Hurrah! You are successful in writing, compiling and executing your first program in java
2.4.4 Points to Remember
Recompile the class after making any changes
Save your program before compilation
Only run that class using java command that contains the main method, because program executions always starts form main
2.5 An Idiom Explained
You will see the following line of code often: o public static void main(String args[]) { …}
About main() o “main” is the function from which your program starts o Why public?
C:\ Documents and Setting> cd.. C:>D: D:> cd examples D:\examples> javac HelloWorldApp.java D:\examples> java HelloWorldApp Hello World D:\examples> _
C:\ WINDOWS\system32\cmd.exe ‐ X
Lecture 3: Learning Basics
3.1 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.
3.1.1 String Concatenation
“+” operator is used to concatenate strings
o System.out.println(“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,
o int i = 4; o int j = 5;
System.out.println (“Hello” + i);// will print Hello 4 on screen
o However
System.out.println(i+j);//will print 9 on the console because both i and j are of type int.
3.1.2 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 Hello System.out.println(i + j); // will print 9 String s1 = new String (“pakistan”);
String s2 = “pakistan”; if (s1 == s2) { 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
3.2 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 {