Archive for the ‘Language’ Category

EXPORTED NAMES

 

After importing a package, you can refer to the names it exports.

In Go, a name is exported if it begins with a capital letter.

Foo is an exported name, as is FOO. The name foo is not exported.

Run the code. Then rename math.pi to math.Pi and try it again.

Example :

package main

import (
“fmt”
“math”
)

func main() {
fmt.Println(math.pi)
}

output:

prog.go:9: cannot refer to unexported name math.pi
prog.go:9: undefined: math.pi

after renaming math.pi to math.Pi

package main

import (
“fmt”
“math”
)

func main() {
fmt.Println(math.Pi)
}

output:

3.141592653589793
Advertisements

IMPORTS

 

This code groups the imports into a parenthesized, “factored” import statement. You can also write multiple import statements, like:

	import "fmt"
	import "math"

but it’s common to use the factored form to eliminate clutter.

Example :

package main

import (
“fmt”
“math”
)

func main() {
fmt.Printf(“Now you have %g problems.”,
math.Nextafter(2, 3))
}

output:

Now you have 2.0000000000000004 problems.

PACKAGES

 

Every Go program is made up of packages.

Programs start running in package main.

This program is using the packages with import paths "fmt" and"math".

By convention, the package name is the same as the last element of the import path.

Example:

package main

import (
“fmt”
“math”
)

func main() {
fmt.Println(“Happy”, math.Pi, “Day”)
}

output :

Happy 3.141592653589793 Day

This tour is also available as a stand-alone program that you can use without access to the internet.

The stand-alone tour is faster, as it builds and runs the code samples on your own machine. It also includes additional exercises not available in this sandboxed version.

To run the tour locally first install Go, then use go get to install gotour:

    go get code.google.com/p/go-tour/gotour

and run the resultant gotour executable.

Welcome to a tour of the Go programming language.

The tour is divided into three sections. At the end of each section is a series of exercises for you to complete.

The tour is interactive. Click the Run button now (or type Shift-Enter) to compile and run the program on a remote server. The result is displayed below the code.

These example programs demonstrate different aspects of Go. The programs in the tour are meant to be starting points for your own experimentation.

Edit the program and run it again.

Whenever you’re ready to move on, click the Next button or type the PageDown key.

Example:

package main

import “fmt”

func main() {
fmt.Println(“Hello, 世界”)
}

output :

Hello, 世界
* Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?

 

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

 

Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);

 


* Q2. What’s the difference between an interface and an abstract class?

 

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

 


* Q3. Why would you use a synchronized block vs. synchronized method?

 

A. Synchronized blocks place locks for shorter periods than synchronized methods.

 


* Q4. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

 

 

A. You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

 


* Q6. How do you know if an explicit object casting is needed?

 

A. If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:

 

Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

 

 


* Q7. What’s the difference between the methods sleep() and wait()

 

A. The code sleep(1000); puts thread aside for exactly one second. The codewait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

 


* Q8. Can you write a Java class that could be used both as an applet as well as an application?

 

A. Yes. Add a main() method to the applet.

 


* Q9. What’s the difference between constructors and other methods?

 

A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

 


* Q10. Can you call one constructor from another if a class has multiple constructors

 

A. Yes. Use this() syntax.

 


* Q11. Explain the usage of Java packages.

 

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

 


* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

 

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you’d need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

 

c:\>java com.xyz.hr.Employee

 


* Q13. What’s the difference between J2SDK 1.5 and J2SDK 5.0?

 

A.There’s no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables – the operator == or the method equals()?

A. I’d use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this method?
A. It’s possible if these variables are final.
* Q17. What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {…}

A. A single ampersand here would lead to a NullPointerException.

* Q18. What’s the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

* Q20. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

For senior-level developers:

** Q21. What’s the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
** Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
** Q23. What comes to mind when you hear about a young generation in Java?
** Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
** Q25. If you’re overriding the method equals() of an object, which other method you might also consider?
A. hashCode()
** Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList
** Q27. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
** Q28. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.
** Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
A. If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;

class ReadAttachment{
public static void main(String [] args)throws Exception{

String host=”mail.javatpoint.com”;
final String user=”sonoojaiswal@javatpoint.com”;
final String password=”xxxxx”;//change accordingly

Properties properties = System.getProperties();
properties.setProperty(“mail.smtp.host”,host );
properties.put(“mail.smtp.auth”, “true”);

Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});

Store store = session.getStore(“pop3”);
store.connect(host,user,password);

Folder folder = store.getFolder(“inbox”);
folder.open(Folder.READ_WRITE);

Message[] message = folder.getMessages();
for (int a = 0; a < message.length; a++) {
System.out.println(“————-” + (a + 1) + “———–“);
System.out.println(message[a].getSentDate());

Multipart multipart = (Multipart) message[a].getContent();

for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));

while (br.ready()) {
System.out.println(br.readLine());
}
System.out.println();
}
System.out.println();
}

folder.close(true);
store.close();
}
}

LOAD THE JAR FILE :  C:\> set classpath=mail.jar;activation.jar;

COMPILE THE SOURCE FILE: C:\> javac ReadAttachment.java

RUN BY :C:\> java ReadAttachment

JDK (JAVA DEVELOPMENT KIT)

 

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…

 

Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.

 

You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.

 

JRE is targeted for execution of Java files

 

i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.

 

JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file

JRE (JAVA RUNTIME ENVIRONMENT)

 

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system

 

The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.

 

If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.

JVM (JAVA VIRTUAL MACHINE)

 

As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

 

The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.

 

There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class sendMail
{
public static final String MAIL_SERVER = “smtp.gmail.com”;
public static final String USERNAME = “Your gmail user name should be here”;
public static final String PASSWORD = “gmail password“;
public static String fromAddress = null;
public static String toAddress = null;

public static void main(String[] args)
{
try
{
fromAddress = “gmail email id”;
String toAddress = “xyz@psdf.com”;
String subject = “This is a test Message”;
String message = “Hello Hows u?”;

Properties properties = System.getProperties();
properties.put(“mail.smtps.host”, MAIL_SERVER);
properties.put(“mail.smtps.auth”, “true”);

Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setText(message);

Transport tr = session.getTransport(“smtp”);
tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();

}
catch (AddressException ex)
{
System.out.println(“in addressException”);
System.out.println(ex.getMessage());

}
catch (MessagingException ex)
{

System.out.println(ex.getMessage());
}
System.out.println(“message successfully sent”);
}

}