JAVA-CS270-UNIT-1&2
JAVA-CS270-UNIT-1&2
Definition of Programming
We can also define the term programming as it is the process that models
or structure the set of instructions that instruct the machine how to perform
a task and what to perform. It can be done using a variety of programming
languages such as C, C++, C#, Python, Java, etc.
Advantages of Programming
Programming Paradigms
It differs in the concepts and methods that are used to represent the elements
(such as objects, variables, functions, and constraints) of a program. And
the steps that involve a calculation (like assignations, evaluation,
continuations, and data flows). The lowest programming paradigm
is machine code.
There are lots of things for programming languages that are known.
However, every one of them needs to follow some procedure when they are
executed and this approach/methodology is a paradigm.
Features of Java
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:
Object-oriented
Secured
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because
JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).
What is JVM
It is:
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
What is Java Bytecode?
Java bytecode is the instruction set for the Java Virtual Machine. It acts
similar to an assembler which is an alias representation of a C++ code. As
soon as a java program is compiled, java bytecode is generated. In more apt
terms, java bytecode is the machine code in the form of a .class file. With
the help of java bytecode we achieve platform independence in java.
Install Java
Click the below link to download jdk 1.8 for you windows 64 bit system.
DK Downloads
Open the executable file which you have just downloaded and follow the
steps.
To execute Java applications from command line, we need to set Java Path.
To set the path, follow the following steps.
Right click on "this PC". It can be named as "My Computer" in some
systems. Choose "properties" from the options.
The screen look alike the above image will open. Click on "Advanced
system settings" to continue.
Above window will open. Click on "Environment Variables" to continue.
Enter "path" in variable name and enter the path to the bin folder inside your
JDK in the variable value. Click OK.
Now Java Path has been set up. Open the Command prompt and
type "javac" In case you have already open up the command prompt, I
suggest you to close the existing window and reopen it again.
The Java has been installed on our system. Now, we need to configure IDEs
like NetBeans or Eclipse in order to execute JavaFX applications.
What is Java?
Java Example
Simple.java
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Test it Now
Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
The File class have several methods for working with directories and files
such as creating new directories or files, deleting and renaming directories or
files, listing the contents of a directory etc.
Let's see which elements are included in the structure of a Java program. A
typical structure of a Java program contains the following elements:
o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors
Documentation Section
1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends
with */. For example:
In this section, we learn how to compile and run java program step by step.
Step 1:
Write a program on the notepad and save it with .java (for example,
DemoFile.java) extension.
1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello!");
6. System.out.println("Java");
7. }
8. }
Step 2:
Step 3:
Set the directory in which the .java file is saved. In our case, the .java file is
saved in C:\\demo.
Step 4:
Step 5:
1. java DemoFile
Execution
The class files generated by the compiler are independent of the machine or
the OS, which allows them to be run on any system. To run, the main class
file (the class that contains the method main) is passed to the JVM and then
goes through three main stages before the final machine code is executed.
These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
tokens.
A lexical token may consist of one or more characters, and every single
character is in exactly one token.
White Space
White space can contain the characters for tabs, blanks, newlines, and form
feeds. These characters are ignored except when they serve to separate other
tokens. However, blanks and tabs are significant in strings.
Comments
1. Single line comments begin with the token // and end with a carriage
return.
For example, //this is the single-line syntax.
2. Multi-Line comments begin with the token /* and end with the token
*/
For example, /* this is multiline syntax*/
Identifiers in Java
Identifiers in Java are symbolic names used for identification. They can be a
class name, variable name, method name, package name, constant name, and
more. However, In Java, There are some reserved words that can not be used
as an identifier.
For every identifier there are some conventions that should be used before
declaring them. Let's understand it with a simple Java program:
Literals in Java
In Java, literal is a notation that represents a fixed value in the source code.
In lexical analysis, literals of a given type are generally known as tokens. In
this section, we will discuss the term literals in Java.
Literals
In Java, literals are the constant values that appear directly in the program. It
can be assigned directly to a variable. Java has various types of literals. The
following figure represents a literal.
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Java Comments
Comments can be used to explain Java code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.
Single-line Comments
Any text between // and the end of the line is ignored by Java (will not be
executed).
1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
A class can also be called a logical template to create the objects that share
common properties and methods.
For example, an Employee class may contain all the employee details in the form
of variables and methods. If the class is instantiated i.e. if an object of the class is
created (say e1), we can access all the methods or properties of the class.
Example 1:
Let's consider the following example to understand how to define a class in Java
and implement it with the object of class.
Calculate.java
1. // class definition
2. public class Calculate {
3.
4. // instance variables
5. int a;
6. int b;
7.
8. // constructor to instantiate
9. public Calculate (int x, int y) {
10. this.a = x;
11. this.b = y;
12. }
13.
14. // method to add numbers
15. public int add () {
16. int res = a + b;
17. return res;
18. }
19.
20. // method to subtract numbers
21. public int subtract () {
22. int res = a - b;
23. return res;
24. }
25.
26. // method to multiply numbers
27. public int multiply () {
28. int res = a * b;
29. return res;
30. }
31.
32. // method to divide numbers
33. public int divide () {
34. int res = a / b;
35. return res;
36. }
37.
38.
39. // main method
40. public static void main(String[] args) {
41. // creating object of Class
42. Calculate c1 = new Calculate(45, 4);
43.
44. // calling the methods of Calculate class
45. System.out.println("Addition is :" + c1.add());
46. System.out.println("Subtraction is :" + c1.subtract());
47. System.out.println("Multiplication is :" + c1.multiply());
48. System.out.println("Division is :" + c1.divide());
49.
50.
51. }
Output:
Student.java
Output:
7) There are many ways to create object in java There is only one way
such as new keyword, newInstance() method, to define class in java
clone() method, factory method and using class keyword.
deserialization.
Let's see some real life example of class and object in java to understand the
difference well:
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
Using the new keyword is the most popular way to create an object or instance of
the class. When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns
the reference of that object to that memory. The new keyword is also used to
create an array. The syntax for creating an object is:
CreateObjectExample1.java
Output:
Welcome to javaTpoint
By using the new keyword, we can also invoke the constructor (default or
parametrized) of the class.
Constructors in Java
. Types of constructors
. Default Constructor
. Parameterized Constructor
. Constructor Overloading
. Does constructor return any value?
. Copying the values of one object into another
. Does constructor perform other tasks instead of the initialization
Every time an object is created using the new() keyword, at least one constructor
is called.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
There are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Nesting Of Methods in Java
In Java, methods and variables that are defined within a class can only be accessed
by creating an instance of that class or by using the class name if the methods are
static. The dot operator is used to access methods and variables within a class.
However, there is an exception to this rule: a method can also be called by another
method using the class name, but only if both methods are present in the same
class. Efficient code organization and simplified method calls within a class are
possible through nesting of methods. Understanding how methods can call other
methods within the same class is an important aspect of Java programming.
Syntax:
1. class Main
2. {
3. method1(){
4.
5. // statements
6. }
7.
8. method2()
9. {
10. // statements
11.
12. // calling method1() from method2()
13. method1();
14. }
15. method3()
16. {
17. // statements
18.
19. // calling of method2() from method3()
20. method2();
21. }
22. }
In simple words, a class that has no name is known as an anonymous inner class in
Java. It should be used if you have to override a method of class or interface. Java
Anonymous inner class can be created in two ways:
TestAnonymousInner.java
Output:
nice fruits
But there are many differences between abstract class and interface that are given
below.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
The java command-line argument is an argument i.e. passed at the time of running
the java program.
The arguments passed from the console can be received in the java program and it
can be used as an input.
So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
In this example, we are receiving only one argument and printing it. To run this
java program, you must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its name
differs.
So, we perform method overloading to figure out the program quickly.
Recursion in Java
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Output:
hello
hello
...
java.lang.StackOverflowError
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.
Advantages of static variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
Syntax
Suggestion: If you are beginner to java, lookup only three usages of this keyword.