Professional Documents
Culture Documents
Journel Dev Tutorials 1.java Tutorial 1 - Setting Up Java Environment On Windows
Journel Dev Tutorials 1.java Tutorial 1 - Setting Up Java Environment On Windows
Journel Dev Tutorials 1.java Tutorial 1 - Setting Up Java Environment On Windows
Name: JAVA_HOME
Value: C:\Program Files\Java\jdk1.6.0_25
After this, you need to edit the Path variable already present there. Just select Path variable and
click on Edit button. In the popup window value section, go to the end and add following
“;C:\Program Files\Java\jdk1.6.0_25\bin” (The colon ; is used as delimiter, so don’t miss that!)
Now your setup is done and you can check it by opening a command prompt and running
command “java – version”.
Step 4: Optional
If you want to get things done easily, you should install either Eclipse of NetBeans IDE that
helps a lot in development. Just download and install it with executable file.
Let me know if you face any issue in setting up the environment.
2.Java Tutorial 2 – Writing and Running First Java Program
In the last article, we saw how to setup Java environment on Windows, now we are ready to
write and run our first java program.
To keep things simple and working for newbie, here is the sample program that you can use.
MyFirstClass.java
public class MyFirstClass {
public static void main(String args[]){
System.out.println("Welcome to JournalDev.");
}
}
Save above program as MyFirstClass.java in any folder.
Open Command Prompt and go to the directory where this file is saved.
Command to Compile: javac MyFirstClass.java
Command to execute: java MyFirstClass
1 C:\Documents and Settings\admin\Desktop>javac MyFirstClass.java
2
3 C:\Documents and Settings\admin\Desktop>java MyFirstClass
4 Welcome to JournalDev.
Few Pointers:
1. Any java code can have multiple classes but can have only one public class.
2. The java code file name should be same as public class name.
3. When we compile the code, it generates byte code and save it as .class extension
4. When we execute the class file, we don’t need to provide full file name. We need to use only
the public class name.
5. When we run the program using java command, it loads the class into JVM and looks for main
function in the class and runs it. The main function syntax should be same as specified else it
won’t run and throw exception as “Exception in thread “main” java.lang.NoSuchMethodError:
main”.
That’s all for this post and you can start playing with your first class. In next post, I will get into
further details of classes, JDK, JVM and other features provided by java language.
Difference between JDK, JRE and JVM in Java
JDK, JRE and JVM are core concepts of Java programming language. Although they all look
similar and as a programmer we don’t care about these concepts a lot, but they are different and
meant for specific purposes. It’s one of the common java interview questions and this article will
explain each one of these and what is the difference between them.
Java Development Kit (JDK)
Java Development Kit is the core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program. JDK is a
platform specific software and thats why we have separate installers for Windows, Mac and Unix
systems. We can say that JDK is superset of JRE since it contains JRE with Java compiler,
debugger and core classes. Current version of JDK is 1.7 also known as Java 7.
Java Virtual Machine(JVM)
JVM is the heart of java programming language. When we run a program, JVM is responsible to
converting Byte code to the machine specific code. JVM is also platform dependent and provides
core java functions like memory management, garbage collection, security etc. JVM is
customizable and we can use java options to customize it, for example allocating minimum and
maximum memory to JVM. JVM is calledvirtual because it provides a interface that does not
depend on the underlying operating system and machine hardware. This independence from
hardware and operating system is what makes java program write-once run-anywhere.
Java Runtime Environment (JRE)
JRE is the implementation of JVM, it provides platform to execute java programs. JRE consists
of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t
contain any development tools like java compiler, debugger etc. If you want to execute any java
program, you should have JRE installed but we don’t need JDK for running any java program.
JDK vs JRE vs JVM
JDK is for development purpose whereas JRE is for running the java programs.
JDK and JRE both contains JVM so that we can run our java program.
JVM is the heart of java programming language and provides platform independence.
Just-in-time Compiler (JIT)
Sometimes we heard this term and being it a part of JVM it confuses us. JIT is part of JVM that
optimizes byte code to machine specific language compilation by compiling similar byte codes at
same time, hence reducing overall time taken for compilation of byte code to machine specific
language.
Java Access Modifiers – public, protected and private keywords
We will look into each of them separately and then we will show the accesses with simple
program.
public keyword
If class member is “public” then it can be accessed from anywhere. The member variable or
method is accessed globally. This is simplest way to provide access to class members, however
we should take care in using this keyword with class variables otherwise anybody can change the
values. Usually class variables are kept as private and getter-setter methods are provided to work
with them.
private keyword
If class member is “private” then it will be accessible only inside the same class. This is the most
restricted access and the class member will not be visible to the outer world. Usually we keep
class variables as private and methods that are intended to be used only inside the class as
private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same
package and to thesubclasses. This modifier is less restricted from private but more restricted
from public access. Usually we use this keyword to make sure the class variables are accessible
only to the subclasses.
default access
If class member doesn’t have any access modifier specified, then it’s treated with default access.
The access rules are similar as classes and the class member with default access will be
accessible to the classes in the same package only. This access is more restricted than public and
protected but less restricted than private.
(Least Accessible) private < default < protected < public (Most Accessible)
Let’s write some simple classes where we will see the access modifiers in action.
TestA.java
1 package com.journaldev.access;
2
3 class TestA {
4
5 public static void methodPublic(){
6 methodPrivate();
7 }
8
9 protected static void methodProtected(){
10 methodPrivate();
11 }
12
13 static void methodDefault(){
14 methodPrivate();
15 }
16
17 private static void methodPrivate(){}
18 }
Note that TestA class has default access and the private class method is accessible to all other
parts of the same class.
TestB.java
1 package com.journaldev.access;
2
3 import com.journaldev.access.TestA;
4
5 public class TestB {
6
7 public static void main(String args[]){
8 TestA.methodPublic();
9 TestA.methodProtected();
10 TestA.methodDefault();
11
12 }
13
14 public static void methodPublic(){
15
16 }
17
18 protected static void methodProtected(){
19
20 }
21
22 static void methodDefault(){
23
24 }
25
26 private static void methodPrivate(){}
27
28
29 }
Note that TestB is in the same package as TestA class and hence it is able to access it’s
class members. private members are not accessible but all other members are accessible
because of the same package.
TestC.java
1 package com.journaldev.access.child;
2
3 import com.journaldev.access.TestB;
4
5 public class TestC {
6
7 public static void main(String[] args) {
8 TestB.methodPublic();
9 }
10
11 }
TestB class is accessible because it’s public. Only public members of TestB class is accessible
because TestC class is not in the same package nor it’s subclass of TestB.
TestE.java
1. package com.journaldev.util;
2. import com.journaldev.access.TestB;
Thats all for the access modifiers in java, it’s simple to understand. Just don’t confuse with
default and protected access. Easy way to remember is that default access is more restricted than
protected and protected members are accessible in subclasses.
What is static in Java? Java Static methods, variables, static block and class
static is a keyword in java and we can’t create a class or package name as static. Java
static keyword can be used in four cases.
1. Java static variables: We can use static keyword with a class level variable. A static
variable is a class variable and doesn’t belong to Object/instance of the class. Since static
variables are shared across all the instances of Object, they are not thread safe. Usually static
variables are used with final keyword for common resources or constants that can be used
by all the objects. If the static variable is not private, we can access it
with ClassName.variableName
1 //static variable example
2 private static int count;
3 public static String str;
4 public static final String DB_USER = "myuser";
2. Java static methods: Same as static variables, static methods belong to class and not to
class instances. A static method can access only static variables of class and invoke only
static methods of the class. Usually static methods are utility methods that we want to
expose to be used by other classes without the need of creating an instance; for
example Collections class. Java Wrapper classesand utility classes contains a lot of static
methods. The main() method that is the entry point of a java program itself is a static
method.
1 //static method example
2 public static void setCount(int count) {
3 if(count > 0)
4 StaticExample.count = count;
5 }
6
7 //static util method
8 public static int addInts(int i, int...js){
9 int sum=i;
10 for(int x : js) sum+=x;
11 return sum;
12 }
From Java 8 onwards, we can have static methods in interfaces too, for more details please
read Java interface static methods.
3. Java static Block: Java static block is the group of statements that gets executed when
the class is loaded into memory by Java ClassLoader. It is used to initialize static variables
of the class. Mostly it’s used to create static resources when class is loaded. We can’t access
non-static variables in static block. We can have multiple static blocks in a class, although it
doesn’t make much sense. Static block code is executed only once when class is loaded into
memory.
1 static{
2 //can be used to initialize resources when class is loaded
3 System.out.println("StaticExample static block");
4 //can access only static variables and methods
5 str="Test";
6 setCount(2);
7 }
4. Java Static Class: We can use static keyword with nested classes. static keyword can’t
be used with top-level classes. Static nested class is same as any other top-level class and is
nested for only packaging convenience.
StaticExample.java
1. package com.journaldev.misc;
2. public class StaticExample {
3. //static block
4. static{
5. //can be used to initialize resources when class is loaded
6. System.out.println("StaticExample static block");
7. //can access only static variables and methods
8. str="Test";
9. setCount(2);
10. }
11. //multiple static blocks in same class
12. static{
13. System.out.println("StaticExample static block2");
14. }
15. //static variable example
16. private static int count; //kept private to control it's value through setter
17. public static String str;
18. public int getCount() {
19. return count;
20. }
21. //static method example
22. public static void setCount(int count) {
23. if(count > 0)
24. StaticExample.count = count;
25. }
26. //static util method
27. public static int addInts(int i, int...js){
28. int sum=i;
29. for(int x : js) sum+=x;
30. return sum;
31. }
32. //static class example - used for packaging convenience only
33. public static class MyStaticClass{
34. public int count;
35. }
36. }
Let’s see how to use static variables, methods and classes in a test program.
TestStatic.java
1. package com.journaldev.misc;
2.
3. public class TestStatic {
5. StaticExample.setCount(5);
7. StaticExample.str = "abc";
8. StaticExample se = new StaticExample();
9. System.out.println(se.getCount());
10. //class and instance static variables are same
11. System.out.println(StaticExample.str +" is same as "+se.str);
12. System.out.println(StaticExample.str == se.str);
13. //static nested classes are like normal top-level classes
14. StaticExample.MyStaticClass myStaticClass = new StaticExample.MyStaticClass();
15. myStaticClass.count=10;
16. StaticExample.MyStaticClass myStaticClass1 = new StaticExample.MyStaticClass();
17. myStaticClass1.count=20;
18. System.out.println(myStaticClass.count);
19. System.out.println(myStaticClass1.count);
20. }
21. }
Output of the above test program is:
Java nested classes are defined as class inside the body of another class. A nested class can
be declared private, public, protected, or with default access whereas an outer class can
have only public or default access.
Nested classes are further divided into two types:
1. static nested classes: If the nested class is static, then it’s called static nested class. Static
nested classes can access only static members of the outer class. Static nested class is same as
any other top-level class and is nested for only packaging convenience.
Static class object can be created with following statement:
1 OuterClass.StaticNestedClass nestedObject =
2 new OuterClass.StaticNestedClass();
2. java inner class: Any non-static nested class is known as inner class. Inner classes are
associated with the object of the class and they can access all the variables and methods of the
outer class. Since inner classes are associated with instance, we can’t have any static variables in
them. Object of inner class are part of the outer class object and to create an instance of inner
class, we first need to create instance of outer class.
Inner classes can be instantiated like this:
1.
1 OuterClass outerObject = new OuterClass();
2 OuterClass.InnerClass innerObject = outerObject.new InnerClass();
1. local inner class: If a class is defined in a method body, it’s known as local inner class. Since
local inner class is not associated with Object, we can’t use private, public or protected access
modifiers with it. The only allowed modifiers are abstract or final. A local inner class can access
all the members of the enclosing class and local final variables in the scope it’s defined.
Local inner class can be defined as:
OuterClass.java
1 package com.journaldev.nested;
2
3
4 import java.io.File;
import java.io.FilenameFilter;
5
6
7
public class OuterClass {
8
9
private static String name = "OuterClass";
10
private int i;
11
protected int j;
12
int k;
13
public int l;
14
15 //OuterClass constructor
16 public OuterClass(int i, int j, int k, int l) {
17 this.i = i;
this.j = j;
18
this.k = k;
19
this.l = l;
20
}
21
22
23
public int getI() {
24
return this.i;
25 }
26
27
28 //static nested class, can access OuterClass static variables/methods
30 private int a;
31 protected int b;
int c;
32
public int d;
33
34
35
public int getA() {
36
return this.a;
37
}
38
39
40
public String getName() {
41 return name;
42 }
}
43
44
45
//inner class, non static and can access all the variables/methods of outer clas
46
class InnerClass {
47
private int w;
48
protected int x;
49
int y;
50
public int z;
51
52
53 public int getW() {
54 return this.w;
55 }
56
57
59 this.w = i;
this.x = j;
60
this.y = k;
61
this.z = l;
62
}
63
64
65
@Override
66 public String toString() {
}
68
69
70
public String getName() {
71
return name;
72
}
73
}
74
75
76
//local inner class
77 public void print(String initial) {
79 class Logger {
80 String name;
81
82
this.name = name;
84
}
85
86
87
public void log(String str) {
88
System.out.println(this.name + ": " + str);
89
}
90
}
91
93 logger.log(name);
logger.log("" + this.i);
94
logger.log("" + this.j);
95
logger.log("" + this.k);
96
logger.log("" + this.l);
97
}
98
99
100
//anonymous inner class
101
public String[] getFilesInDir(String dir, final String ext) {
102 File file = new File(dir);
105
106 @Override
115
116
117
118
119
120
121
122
Here is the test program showing how to instantiate and use nested class in java.
NestedClassTest.java
1 package com.journaldev.nested;
2
3 import java.util.Arrays;
15
16 System.out.println(staticNestedClass.getName());
17
18 staticNestedClass.d=10;
19 System.out.println(staticNestedClass.d);
20 System.out.println(staticNestedClass1.d);
21
32 System.out.println(Arrays.toString(outer.getFilesInDir("src/com/journaldev/ne
33
34 System.out.println(Arrays.toString(outer.getFilesInDir("bin/com/journaldev/ne
35 }
36
}
37
38
1 OuterClass
2 10
3
0
4
OuterClass
5
w=0:x=0:y=0:z=0
6 w=1:x=2:y=3:z=4
7 Outer: OuterClass
8 Outer: 1
9 Outer: 2
Outer: 3
10
Outer: 4
11
[NestedClassTest.java, OuterClass.java]
12
[NestedClassTest.class, OuterClass$1.class, OuterClass$1Logger.class, OuterClass$Inne
13
Notice that when OuterClass is compiled, separate class files are created for inner class,
local inner class and static nested class.