Wednesday, November 18, 2009

Core Java interview questions with Code Example

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


import java.io.*;

public class HelloWorld {
public static void main(String[] args) {
try {
PrintStream st = new PrintStream(new FileOutputStream("test.txt"));
System.setOut(st);
System.setErr(st);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


Question: Explain the usage of the keyword transient?

Answer: Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. Sometimes serialization is necessary. For example, when we transmit objects through network, we want them to be consistent, therefore these objects have to be sterilizable,

On the other hand, we don't want the value of some member variable to be sterilizable, for instance, the password, then we use the keyword transient. When the class will be de-serialized, the transient variable will be initialized to 0 or null.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Logon implements Serializable {
private transient String password;

public Logon(String pwd) {
password = pwd;
}

public String toString() {
return password;
}

public static void main(String[] args) throws Exception {
Logon a = new Logon("hello_world");
System.out.println("logon a = " + a);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"Logon.out"));
o.writeObject(a);
o.close();
Thread.sleep(1000); // Delay for 1 second
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"Logon.out"));
System.out.println("Recovering object at after 1 second");
a = (Logon) in.readObject();
System.out.println("logon a = " + a);
}
}


The output of the above example will be:

logon a = hello_world
Recovering object at after 1 second
logon a = null

Tuesday, November 17, 2009

Linux Commands - Hardware

* uname - print the OS information. "uname -a" display kernel-name, nodename, kernel-release, kernel version, machine, processor, hardware-platform, and operating system.
* dmesg - print comprehensive kernel and driver messages. For example, "dmesg >> file_to_mail_out.txt" output the information to a file for future trouble-shooting.
* top - display the system resources usage, and the updating processes.
* free - check memory usage.
* swapon - manage swap file or partition. "swapon -s" displays a summary of the swap usage.
* vmstat - display virtue memory information.
* lsof - list all the open files, sockets and pipes.
* tty - print the file name of the terminal connected to standard input.

* fdisk - manage disk partition. "fdisk -l" displays partition table.
* cfdisk - a easier progrom based on fdisk.
* fdformat - low-level format a floppy disk.

* eject - eject removable media.
* mount - unix file system is arranged in one big tree. mount attaches the file system found in some device into the big tree. "mount /dev/cdrom" mount the iso9660 file system found on the CDROM.
* unmount - unix file system is arranged in one big tree. unmount detaches the file system found in some device from the big tree. "unmount ./isoimage" unmount the iso9660 file system found on the file isoimage.

* import - "import screenshots" take a screen shots from x-window, save it to a file screenshots.

* ifconfig - displays the network interfaces.
* ifup - "ifup eth1" brings up a network interface eth1.
* ifdown - brings down a network interface.

* lpr - "lpr file.txt" sent the file.txt to default printer.
* lprm - remove the current printing job.
* pr - preformat a file for printing. "pr | lpr file.txt"

Monday, November 16, 2009

Linux Commands - Programming

* cksum - calculate the check sum of a file, used to verify if two files are identical. Example: "cksum file1.txt" returns a number as the finger print of the file1.txt.

* echo - "echo $PATH" displays the value of environment variable PATH.
* env - displays all environment variable.
* export - write a variable to harddis. Example: "export MYVAR=$HOME" assigns the value of HOME to MYVAR, then set MYVAR as an environment variable.
* declare - declare variables and give them attributes. Example: "declare MYVAR=$HOME" assigns the value of HOME TO MYVAR, but does NOT set MYVAR as environment variable.
* read - read input from standard input, assign it to a variable. Example: "read newvar", input a value for newval, then "echo $newvar".
* sleep - delay for a some time. Example: "sleep 2" delay 2 seconds.

* alias - allow users to create abbreviations for complex commands. Example: "alias" displays all the existing aliases. Example: "alias mycmd="pwd" "
* unalias - delete an alias. Example: "unalias mycmd".
* nohup - run a command immune to hungups. Example: "nohup ls" run the command ls, write the output to file nohup.out.
* tee - "ls | tee file.out" this command display the output of command ls at standard output, while write them to the file.out. "ls >> file.out" won't display the output at standard output.
* sed - search and replace patterns in a file. Example: sed 's/my/your/g' afile.txt --this command substitute all "my" to "your" in the afile.txt.
* cut - divide a file into several parts. Example: "cut -d, -f1,3 sample.txt" divide lines by delimiter :, then output the first and third columns.
* sort - sort text files.
* paste - merge lines of files.
* split - split a file into many parts. Example: "split -b 1024 example.data new" split example.data into file newaa, newab, newac... each file have 1024 byte.
* vi - text editor.

* top - display the system resources statistics, and the updating processes.
* ps - display the running processes. "ps -A" displays all the running processes.
* kill - stop a process from running. "kill -9 3214" stops the process with id 3214 immediately.

* watch - execute a program periodically. Example: "watch -n 5 free" execute command free every 5 second.
* crontab - schedule tasks running periodically. Example: "crontab -l" list all the scheduled tasks for the current user. "crontab -e" edit the scheduler. For example, a task record could be "2 12 * * 5 /sbin/ping -c 1 www.google.com >> /dev/null", which means, ping google every 2 minutes at 12 o'clock on every friday. "crontab -d" delete all the scheduled tasks for the current user.

* chkconfig - control services. "chkconfig" displays the states of all the system services. "chkconfig sshd on" turn on the ssh service.

Linux Commands - network

* vncpasswd - create a passwd for the vnc server.
* vncserver - create x-window display so that vncclient can remote login. Example: "vncserver :10 -geometry 1280x960" create a display :10 with size 1280x960. "vncserver -kill :10" stops the display :10.
* ftp - connect to a ftp server and is useful to manage your webpage hosting site. Example."ftp youracount.x10hosting.com".
* telnet - remote login to a host, not secure, use ssh instead.
* ssh - open an ssh session on a remote host. Example: "ssh guy@192.168.1.100" will login host 192.168.1.100 with user guy.
* scp - copy files from/to remote host using ssh. Example: "scp guy@192.168.1.100:test.txt /some/local/directory/" will copy file test.txt from site 192.168.1.100 to local machine.
* wget - Retrieve web pages or files via HTTP, HTTPS or FTP. Example: "wget http://www.google.com/index.html" will download the webpage index.html from google site.

* netstat - powerful network debug tool. Example: "netstat" displays all sockets. "netstat -r" displays routing table. "netstat -s" displays summary of protocols.
* ping - ping a remote host. Example: "ping -c 3 www.google.com" send 3 ping packets to google.
* traceroute - trace the route to a remote host. Example "traceroute www.google.com" will find all the router hops to google.
* iptables - administration tool for IPv4 packets filtering and NAT. Exmple: "iptables -l" list all rules for all chains.

* write - send message to a user loging into the machine. Example: "send guy" will open a sending box to pass a message to user guy. Control + D to close the message window.
* mail - send smtp mail. You should have a MTA such as postfix installed on your host in order to send mail. Example: "echo This will go into the body of the mail. | mail -s “Hello world” you@youremailid.com".

* hostname - display or set the host name for local machine.
* host - simple dns loop up. Example: "host www.google.com" get the ip address of google. "host 204.228.150.3" reverse loop up the domain for ip address.
* dig - detailed dns look up. Example: "dig kl2217.x10hosting.com" shows the A, CNAME, NS records of the dns loopup. "dig kl2217.x10hosting.com MX" shows the mail server loopup records.
* nslookup - interactive dns look up tool.

Linux Commands - system administration

* su - log into root account.
* df - quick check for the disk space. "df -h -T" -h let output human readable, -T shows the file system type.
* du - quick check for file size. "du -h" shows the size of folders and files under current directory in a more readable format.
* finger - check who is on the system. fingure followed by user id shows detail history of a user.
* passwd - change the passwd of the current user. type in passwd then enter, you will be asked for old password then new password.
* dd - disk duplicate. "dd if=/dev/hdb1 of=/backup/", if stands for input file, of stands for output file.
* shutdown - shutdown the system. -h flag means halt, -r indicates reboot. For example "shutdown -h +120" will put the system into hibernate after 120 min.
* tar - zip and unzip files or directory. "tar cvfz tarball.tar.gz ./directory/" archive and compress the directory "dir" into file "tarball.tar.gz", "tar xvf tarball.tar.gz" unzip it. c means create new, x means untar, v means berbose, f means file.
* chmod - change file permission. "chmod 777 filename" give read, write, execute permission to owner, group and world. 7 = 4 + 2 + 1 = r + w + x.
* chown - change file's owner. "chown me file1" change file1's owner to "me".
* chgrp - change file's group. "chown users file1" changes file1's group to "users".
* id - print user and group id.
* groups - view the groups a user belongs to. "groups root" display all the groups root belongs to.
* groupadd - create new group. "groupadd mygroup" create a new group mygroup.
* groupmod - modify a group. "groupmod -n testgroup mygroup" change the name of mygroup to testgroup.
* groupdel - delete a group. "groupdel testgroup" delete the group testgroup.
* useradd - add a user. "useradd -g mygroup myuser" add the user myuser to group mygroup.
* usermod - modify a user. "usermod -g users myuser" change the group of myuser to users.
* userdel - delete a user. "userdel myuser" delete the user myuser.

Linux Commands - basic commands

* ls - files in the current directory.
* cd - working directory. If your current path is /home/username/Trash for instance, typing "cd" will bring you back to /home/username.
* mkdir - a new directory
* rmdir - a directory (must be empty)
* touch - "touch filename" create a new file "filename".
* cp - such as "cp currentFile newFile", and is used to copy files.
* diff - compares two files, "diff file1 file2" compares each line of file1 and file2, displays the difference.
* mv - such as "mv currentLocation newLocation". This is used to either move or rename files.
* rm - such as "rm myFile"; it is used to delete files permanently. "rm -r existingdir" will remove the existing directory named 'existingdir' and all directories and files below it.
* ln - create a shortcut. For example "ln -s orignial symlink" create a symbolic file "symlink" pointing to the file "original"
* pwd - the working (current) directory.
* cat - files (can be used to join them together), and prints its output to standard output (the terminal screen). Used like: "cat myFile".
* less - for file viewing in the shell, and is most useful for text files; invoked like "less myFile".
* tail - show the last 10 lines of a file, and is very useful to view a updating file. For example: "tail -f /var/log/messages" shows the last 10 lines of changing log file messages.
* whereis - show where the binary, source and manual page files are for a command. For example "whereis ifconfig".
* find - be used to find files via the command line. Example usage could be: "find . -name toc", which looks at the current directory (defined by ".") for any files with the name "toc".
* grep - be used to find lines contains a specific pattern. For example : "grep root /etc/passwd" find all lines contains string "root" in the file passwd.
* date - the current date! This can also be used to set the date of the system (but administrator privileges are required).For example: # date -s "2 OCT 2006 18:00:00"
* history - in shell command for the BASH environment that shows the last run commands.

meta.ai impression

Meta.ai is released by meta yesterday, it is super fast you can generate image while typing! You can ask meta.ai to draw a cat with curvy fu...