Learn Java Step By Step Fast and Free
We need to learn Java as Java is one of the best and finest languages in the world. Java programming language has been on the top-rated chart due to the fact its introduction in the ’90s. Most of the world’s renowned providers use Java to construct their cellular and desktop applications and also their webs.
Likewise, Java can operate just about all systems. Wow! That is big! Also, they are the most well-known language for Android devices. Little question of why Android apps are Java-centered designed. Java has something extremely peculiar and appealing.
The long-time and seemingly old-fashioned rendition of languages can run without the need of worry on it since more recent variations have released. What a programming language Java is! This straightforward characteristic of Java has and will generally set a smile on the people experience as they will not have to hassle themselves with any code rewrite after newer versions of Java are out.
Introduction to Java
Goals Let’s touch on a few important goals of these tutorials before we get started. or instance, books will skip programming style sections, common pitfalls, debugging, good /bad programming practices and debugging. This tutorial covers best programming practice exercises and programs for you to learn and understand easily.
- This Blog Tutorial consists of a lot of daily life example programs for the understanding of concepts, which helps learners to understand in an effective and better way.
- Provide practice programs at the end of tutorial documents.
Introduction
Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA),[15] meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java is similar to C and C++, but it has fewer low-level facilities than either of them. As of 2019, Java was one of the most popular programming languages in use according to GitHub particularly for client-server web applications, with a reported 9 million developers.
Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle) and released in 1995 as a core component of Sun Microsystems’ Java platform. The original and reference implementation Java compilers, virtual machines, and class libraries were originally released by Sun under proprietary licenses. As of May 2007, in compliance with the specifications of the Java Community Process, Sun had relicensed most of its Java technologies under the GNU General Public License. Meanwhile, others have developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java (bytecode compiler), GNU Classpath (standard libraries), and IcedTea-Web (browser plugin for applets).
Language designers: James Gosling
Installation of Compiler
Java can be downloaded and install from Oracle’s site.
Other Software for JAVA:
- Notepad − You can use any simple word editor on Windows machine.
- Netbeans − An open-source, free Java IDE which can be downloaded.
- Eclipse − A Java IDE developed by the open-source eclipse community.
- Vi and Emacs- This is for Unix and Linux.
- Forte For Java
- Borland JBuilder
- Symantec’s visual café
- IBM Visual Age.
Versions of Java
VERSION CODE NAME RELEASE DATE
JDK 1.1.4 Sparkler Sept 12, 1997
JDK 1.1.5 Pumpkin Dec 3, 1997
JDK 1.1.6 Abigail April 24, 1998
JDK 1.1.7 Brutus Sept 28, 1998
JDK 1.1.8 Chelsea April 8, 1999
J2SE 1.2 Playground Dec 4, 1998
J2SE 1.2.1 (I don’t know) March 30, 1999
J2SE 1.2.2 Cricket July 8, 1999
J2SE 1.3 Kestrel May 8, 2000
J2SE 1.3.1 Ladybird May 17, 2001
J2SE 1.4.0 Merlin Feb 13, 2002
J2SE 1.4.1 Hopper Sept 16, 2002
J2SE 1.4.2 Mantis June 26, 2003
J2SE 5.0 (1.5.0)Tiger Sept 29, 2004
Follow the below links for better understanding on versions
- https://www.quora.com/What-are-the-different-versions-of-Java
- https://www.javatpoint.com/java-versions
Types of Application Java Supports
- Standard application (Just like C, C++)
- Applet(No more applicable)
- Web Application (URL, JSP, servlet are some core term).
- Distributed application(RMI)
How Java is a win-win situation for everybody?
- Analysts and Designer find it a Simple model process and advocate to produce a clean and manageable design.
- Programmers write elegance code with the power of object-oriented tools. Java provides the required Clarity and several other Library support thus increases productivity.
Features of Java
Difference between procedural and object-oriented approach:-
Procedural Approach | Object-Oriented Approach |
Ø Process centric | Ø Data-centric |
Ø They are organized around the process, hence the execution is sequential. | Ø These programs are organized around data and objects. They can express real objects better way. |
Ø Reusability and extensibility is less. | Ø Reusability and extensibility is high. |
Ø They are tough to maintain. They are complex and huge in size. | Ø They are cost-effective, easy to maintain, less complex, smaller in size. |
Ø Follows top-down methodology | Ø Follows bottom-up methodology |
Tools available in java
Tool | Comments |
---|---|
JDK | Java development kit |
Javac | The java compiler |
java | The java interpreter |
JavaDoc | Generates the API documentation in plain HTML format from Java source code |
appletviewer | A java interpreter that executes java applet |
jdb | The java debugger-it helps in finding and fixing bugs |
javap | The java disassembler-displays the accessible functions and data in a compiled class file. It also displays the meaning of the byte codes. |
javah | Creates c header files that can be used to make c routines that can call java routines or make c routines that can be called by java program. |
Basic Syntax of JAVA
When we consider a Java program, it can be defined as a collection of objects that also communicate by invoking the techniques of each other. Let us now look briefly at what variables of class, object, methods, and instance make sense.
setup
information found in the iostream file. The programmer could type all this information
into the program, but it would be very time-consuming. So that’s why we use this approach to make a less and efficient way of programming for the developer.
Object − Objects have individual states and behaviours. Example: A dog has statements-colour, name, breed and behaviour such as wagging its tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behaviour/state that the object of its type supports.
Methods − A method is a behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
− Each object has its unique set of instance variables. An object’s state is created by the values assigned to these instance variables.
How A Java Program Looks Like?
Class is the heart of java way of development. So when we talk about a structure of java code we will look at how a class is structured.
The class contains data members and methods to operate on those data members of the class. Methods contain data type deceleration and executable statements.
A dot operator is used to access the variables and methods of the class.
Structure of a java program:
#Documentation section
#package section
#import statements
#Interface Statements
#class definition
#class member deceleration
#method declaration
#local variable deceleration
A java source code may contain multiple class definitions, multiple member variables, multiple methods, multiple local variables.
All Java code must be saved with Java extension. Java is a case sensitive Programming Language. The best practice says to save the Java program with the same file name and class name (If a class is declared as public , then , in that case, It is compulsory. Otherwise, it is not mandatory.
All Java code must be saved with Java extension. Java is a case sensitive Programming Language. The best practice says to save the Java program with the same file name and class name (If a class is declared as public , then , in that case, It is compulsory . Otherwise, it is not mandatory.
A Java class can contain one public class and many non-public classes. After compilation, Java creates separate class files for each class.
A Java class can contain one public class and many non-public classes. After compilation, Java creates separate class files for each class.
Documentation Section:
A set of comment lines that gives the name of the program, the author information and other details. refer to this link for information. These are the details the programmers like to refer at a later stage.
Comments must explain why and what of classes and how of algorithms. This improves the greater maintainability. The Javadoc comment style (/**…..*/) is used for generating documentation automatically. It is optional though.
The documentation section is the non-necessary section containing a series of comments for the developers and users. Mainly it is used to create Java doc.
Package Statement:
The first valid statement of the program. This statement declares a package name and informs the compiler that the classes defined here belong to this package. However if our program does not refer to any other classes, it must be part of the default package. This statement is not required then. It is also optional.
Import Statement:
After the package statement next comes import statements. This statement instructs the interpreter to load the correct class/classes in the package specified. A Java code may have zero or number of import statements.
Interface Statement:
An interface is like a class but includes a group of methods decelerations. This is important when we wish to implement multiple inheritances. However, it is also optional.
keywords Statement:
Rest all in the java are 90% keywords. Java keywords have a specific meaning so we can not use them as names for variables, classes, methods, libraries or any other user-defined forms. All keywords need to be written in lower case form(lower case letters). Since java is case sensitive, one can use these words as identifiers by changing one or more letters to uppercase or lower case. However, this should be avoided.
Main method
A class may or may not have a main method. But while mapping one of them will surely have main( ) method.
Syntax:
Class
{
Public static void main( string args[ ])
//or
Public static void main( string[ ] args){
-
-
-
-
}
}
- Public – Public indicates that the method can be accessed from anywhere. The main ( ) method always needs to be public. This method is the entry point of the JVM( An outside program of our application)
- Static:– Static indicates that the main ( ) method is a class-level function and there is no need to create an object to call this function. ( Actually, there exist no objects before calling main( ).
- Void:– Void indicates that the main does not return any value.
- string args[ ] or string[ ] args:- It indicates that the main( ) method accepts an array of strings to the function. It is mainly useful when calling from the command line and wants to pass some initial values to the main ( ) method.
Java First Program
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World Animesh"); // prints Hello World Animesh
}
}
Output on Screen:
Hello World Animesh
Java Language Details
- Tokens- In Java , the smallest individual units are known as Tokens. (like-Keywords, identifiers, Constants, Strings, Operators)
- Keywords:-Keywords are the reserved names of a language. They cannot be reused as names of other variables, functions, class names etc.
- Identifier:-Identifier refers to the name of variables, classes, interfaces, arrays or any attributes that need a name in Java.
- Constant /Literals:– Constants refers to fixed values which cannot be changed during run time.
- Operators:-Operators operate on variable and constants to form and expression.
- Separators:-Separators are such special characters that are used to separate statements. They are – “{ },[ ],;,( ), ,.”
What Is Method Signature In Java
The understanding method signature is an important aspect of java programming.
The rules are:
- Method signature consists of the name of the method and argument type.
public void method1(float f,int i,char ch)
its method signature will be method1(float, int, char)
- In java return type is not a part of the method signature. The compiler will always use method signature while resolving method calls. In java in the same class two methods with the same signature not allowed. We will get a compile-time error.
Class TestTwoMethods{
public static void method1(String st)
{
}
public static void method1(int val)
{
//this is allowed
}
public static int method1(String st)
{
return 0;
//not allowed as both the methods method1 are having same signature
}
}
Check more about methods in java.
Check out more about Jar and Jar Creation
What Is The Difference Between Parameters and Argument in Java?
A method uses parameter but a calling method passes argument. So arguments are those which are passed to methods. Parameters are those values that try to catch the arguments sent by the caller/calling methods and assign it to a local variable. A parameter is a part of the method signature whereas the arguments are expressions used to call a method.
The argument sent by the calling method goes and sit the same order in the parameter list. Arguments can be of variable type
Exp:
int val=add(3,5);
int val=add(a,b);
//here we are passing arguments to the method add.
public int add(int a,int b)
// int a,int b are parameters for this method
{
return a+b;
}
By this way, the values can be passed to the called method. This is called pass by value.
Basic Syntax of JAVA:
Case Sensitivity − Java is case sensitive, meaning Hello and hello identifiers would have different meanings in Java.
Class Names − For all class names, the first letter should be in Upper Case. If multiple words are used to form a class name, the first letter of each interior word should be in Upper Case. Read more here for the nested inner class.
Example:
class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word’s first letter should be in Upper Case.
Example: public void myMethodName() Program File Name − Name of the program file should exactly match the class name.
Program File Name − The program file name should correspond exactly to the class name.
- You should save the file using the class name (Remember Java is case sensitive) and append’.java’ to the end of the name (if the name of the file and the name of the class do not match, your program will not compile).
- But please make a note that in case you do not have a public class present in the file then file name can be different than a class name. It is also not mandatory to have a public class in the file.
JAVA Identifiers
- All components required for Java require names. Class names, variables, and methods are called identifications
- There are several points to remember regarding identifiers in Java. They are as follows− A letter (A to Z or a to z), currency character) ($or underscore) (should all identifiers start with. Identifiers can have any combination of characters after the first character.
- Unable to use a keyword as an identifier.
- Most importantly, identifiers are case sensitive.
See also Abstract Class TimeZone in JavaPowered by Inline Related PostsExamples of legal identifiers: age, $salary, value, 1 value.
Examples of illegal identifiers: 123abc,-salary.
Identifier naming Convention:-
- A Java identifier must begin with a letter, a dollar sign or underscore. It cannot begin with a number.
- The subsequent character can be digitized.
- There is no restriction on the length of identifiers.
- Java allows Unicode characters in the identifiers as they are treated as letters in Unicode( ASCII is replaced by Unicode in java.
Best practices of the naming convention:-
- Class and interface name starts with an uppercase letter and each subsequent word starts with an uppercase letter. All remaining letters must be lower case.
- Public data members, methods start with a leading lowercase character. If more than one word is used, the second letter onwards, each letter starts with uppercase.
- Constants always need to be in uppercase letters and there may be underscored in it.
Constant/Literals :
A literal that represents a constant value cannot be changed during execution. Hence a literal cannot be placed in the left side of an assignment operator.
Example of Literals:-
- Integer Literals:-7,-9, 0X 7A,012
- Floating Point Literals:-5.23,-7.56,3.43f,8.9F,6.9D,1.8E-04 (d, D is double precision.)
- Character literals:- ‘a’,’x’,’z’,’\138’,’\u0058’
- String literals:- “xyz”
- Baskan Literals- True , False.
Java Datatypes in Java
Java Datatypes is discussed here. Also, check the Casting of datatypes.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −
- Access Modifiers − default, public, protected, private
- Non-access Modifiers − final, abstract, strict
We will be looking into more details about modifiers in the next section.
Java Variables
Following are the types of variables in Java −
- Local Variables
- Class Variables (Static Variables)
- Instance Variables (Non-static Variables)
Here is more details on variables in java.
JAVA Enum
In Java 5.0 Enums were introduced. Enums restricts one variable to only have one of a few predefined values. The enumerated values in this list are called enums.
Read more about enum.
With the use of enums, the number of bugs in your code can be reduced.
class FreshJuice { enum FreshJuiceSize{ SMALL, MEDIUM, LARGE } FreshJuiceSize size; } public class FreshJuiceTest { public static void main(String args[]) { FreshJuice juice = new FreshJuice(); juice.size = FreshJuice.FreshJuiceSize.MEDIUM ; System.out.println("Size: " + juice.size); } }
Output:
Size: MEDIUM
Keywords in JAVA
Keywords are the words whose meaning has been already explained to the C compiler. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the compiler. Java has 50 keywords.
Read more on keyword and Identifier.
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ public static void main(String []args) { // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); } }
Output:
Hello world
JAVA Operators:
Operators are symbols which is use to perform some specific operations. Java has a rich set of operators. Java operator is divided into the following four groups:
Arithmetic operator:
It is used to perform mathematical operations on numbers. The following table lists the arithmetic operators. Here variables M and N are defined as integer type of variables which holds an integer value.
Logical operator:
Use to perform a logical operation on two or more Boolean values. The operand is one on which we operate. Here variables A and B are defined as the Boolean type of variables which holds Boolean value.
boolean A=true, B=false;Check more on Java Operator
Class Concept in Java
A class represents an Abstract Data type(ADT). A class is a logical construct and An object is a physical reality ( as it occupies memory)
JAVA IF Statement
The syntax of the if-then statement in Java is:
if (expression) { // statements }
The expression here is boolean (returns either true or false).
If the expression is evaluated to true, if (statements inside parenthesis) are executed within the body of the statement(s).
If the expression is evaluated to false if it is skipped from execution, state(s) inside the body.
If Example Using Class:
class IfStatement { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Number is positive."); } System.out.println("This statement is always executed."); } }
Output:
The number is positive.
This statement is always executed.
If the test expression is evaluated to true the if statement executes a certain section of code. The if statement can have another block optional. Statements are executed inside the body of another statement if the expression of the test is evaluated to be false.
The if-then-else statement syntax is:
if (expression) { // codes } else { // some other code }
This is if-else detailed example:
class IfElse { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is not positive."); } System.out.println("This statement is always executed."); } }
Output:
Number is positive.
This statement is always executed.
How it all works?
Let’s make a syntax of this if/else statement as below:
if (expression1) { // codes } else if(expression2) { // codes } else if (expression3) { // codes } else { // codes } class Ladder { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("Number is positive."); } else if (number < 0) { System.out.println("Number is negative."); } else { System.out.println("Number is 0."); } } }
Output:
The number is 0.
Nested if in JAVA
class Number { public static void main(String[] args) { Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber1; if (n1 >= n2) { if (n1 >= n3) { largestNumber1 = n1; } else { largestNumber = n3; } } else { if (n2 >= n3) { largestNumber1 = n2; } else { largestNumber = n3; } } System.out.println("Largest number is " + largestNumber1); } }
Output:
The largest number is 4.5
To make this easier, we have assigned the value of variables in the above programs ourselves. These values may, however, come from user input data, log files, form submission etc. in real-world applications.
Looping in JAVA
In programming languages, loops are used to repeatedly execute a set of instructions/functions when certain conditions become true. Java offers three types of loops.
- For Loop
- While Loop
- Do-While Loop
- For Loop
The Java for loop is a control flow statement that repeatedly iterates a part of the programs. If the iteration number is fixed, use for loop is recommended.
A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
- Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
- Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return Boolean value either true or false. It is an optional condition.
- Statement: The statement of the loop is executed each time until the second condition is false.
- Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Syntax:
for(init;condition;incr/decr) { // code to be executed }
Example:
//for loop
for(int i=1;i<=10;i++) { System.out.println(i); }
Output:
1 2 3 4 5 6 7 8 9 10
Note:
This is the syntax for infinite loop in JAVA.
for(;;){ //code to be executed }
This is enhanced for loop in JAVA
Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand. This is one of the major benefits of using Enhanced for loop which helps the programmer to understand and code much easier.
Let’s take the same example that we have written above and rewrite it using enhanced for loop.
class ForLoopExample3 { public static void main(String args[]){ int arr[]={2,11,45,9}; for (int num : arr) { System.out.println(num); } } }
Output:
2
11
45
9
While loop in JAVA
The Java while loop is a control flow statement that repeatedly executes a part of the programs based on a given boolean condition. If the number of iterations is not fixed, it is recommended to use while looping.
Basic Syntax:
while(condition) { //code to be executed }
Example:
//while loop int i=1; while(i<=10) { System.out.println(i); i++; }
Output:
1 2 3 4 5 6 7 8 9 10
Infinite While loop syntax is as below:
while(true) { //code to be executed }
Do while
The Java do-while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given Boolean condition. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax:
do { //code to be executed }while(condition);
Example:
//do-while loop int i=1; do{ System.out.println(i); i++; }while(i<=10);
This is the proper syntax
Do { //code to be executed } while(true);
Nested For loop in java
If a loop exists inside the body of another loop, it’s called nested loop. Here’s an example of nested for loop.
Basic Syntax:
for (int i = 1; i <= 5; ++i) { // codes inside the body of outer loop for (int j = 1; j <=2; ++j) { // codes inside the body of both outer and inner loop } // codes inside the body of outer loop }
Example:
class NestedForLoop { public static void main(String[] args) { for (int i = 1; i <= 5; ++i) { System.out.println("Outer loop iteration " + i); for (int j = 1; j <=2; ++j) { System.out.println("i = " + i + "; j = " + j); } } } }
Output:
Outer loop iteration 1
i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2
Example 2:
class NestedLoop { public static void main(String[] args) { int i = 1; while (i <= 5) { System.out.println("Outer loop iteration " + i); for (int j = 1; j <= 2; ++j) { System.out.println("i = " + i + "; j = " + j); } ++i; } } }
This is perfect example which shows how to use nested for loop for pattern drawing.
class Pattern { public static void main(String[] args) { int rows = 5; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { System.out.print(j + " "); } System.out.println(""); } } }
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
This is another example
public class PyramidExample2 { public static void main(String[] args) { int term=6; for(inti=1;i<=term;i++){ for(int j=term;j>=i;j--){ System.out.print("* "); } System.out.println();//new line } } } Output: * * * * * * * * * * * * * * * * * * * * *
Java Labelled For Loop
For loop, we can have a name for every Java. We use the label before the loop to do so. If we have nested for loop so we can break/continue specifically for loop it is useful. Break and continue keywords usually break/continue the innermost for loop only.
Example:
//A Java program to demonstrate the use of labeled for loop public class LabeledForExample B { public B static B void B main (String[] B args) B { //UsingB LabelB forB outerB andB forB loopB B B B B B aa: for (int B i = 1; i & lt; = 3; i++) { bb: for (int B j = 1; j & lt; = 3; j++) { if (i == 2 & amp; & j == 2) { break B aa; } System.out.println (i + "B " + j); } } } }
Output:
1 1
1 2
1 3
2 1
Example 2:
public class LabeledForExample2 { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break bb; } System.out.println(i+" "+j); } } } }
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Break Statement
Next pre-Java Break Statement When a break statement is found inside a loop, the loop is terminated immediately and the program control resumes after the loop at the next statement.
The Java break statement is used to break the state of loop or switch. It breaks the program’s current flow at stated condition. In the event of an inner loop, it only breaks the inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
//Java Program to demonstrate the use of break statement
//inside the for a loop.
public class BreakExample { public static void main(String[] args) { //using for loop for(int i=1;i<=10;i++){ if(i==5){ //breaking the loop break; } System.out.println(i); } } }
1
2
3
4
Break Statement with the inner loop
It breaks the inner loop only if you use break statement inside the inner loop
/Java Program to illustrate the use of the break statement
//inside an inner loop
public class BreakExample2 { public static void main(String[] args) { //outer loop for(int i=1;i<=3;i++){ //inner loop for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using break statement inside the inner loop break; } System.out.println(i+" "+j); } } } }
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Break Statement with Labeled for loop
We can use a label with a break statement. This feature has been introduced as of JDK 1.5. So, we can break any Java loop now, whether it’s outer loop or inner loop.
Example:
public class BreakExample3 { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using break statement with label break aa; } System.out.println(i+" "+j); } } } }
Output:
1 1
1 2
1 3
2 1
JAVA Break Statement with While loop
public class BreakWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using break statement i++; break;//it will break the loop } System.out.println(i); i++; } } }
Output:
JAVA Switch Statement
A switch statement allows equality testing of a variable against a list of values. Each value is called a case, and each case checks the variable being switched on.
Basic Syntax:
switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements }
- Only integers, Convertable integers (byte, short, char), strings, and enums can be the variable used in a switch statement.
- Within a switch you can get any number of case statements. Each case is followed by the value and a colon to be compared with.
- The value for a case must be the same type of data as the switch variable, and must be a constant or a literal.
- When the variable to be switched on is equal to a case, the statements after that case will be executed until a break statement has been reached.
- When a break statement is reached, the switch will terminate, and the control flow will jump to the next line after the switch statement.
- Not every case needs a break in it. If no break appears, the control flow will descend into subsequent cases until a break is reached.
- An optional default case may have a switch statement, which must appear at the end of the switch. When none of the cases is true, the default case may be used to perform a task. No break is needed in the default case.
Example:
public class Test { public static void main(String args[]) { // char grade = args[0].charAt(0); char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }
Output:
Well done
Your grade is C
Detailed Example of Switch Statement which shows switching between Months in a year
public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } }
Read more on Java Switch Statement.
Java Continue Statement
The continuation statement is used in loop control structure when you need to immediately jump to the next loop iteration. It may be used with looping or while loop.
The statement Java Continue is used to continue the loop. It continues the program’s current flow and skips the rest of the code at the condition specified. In the case of an inner loop, the inner loop only continues.
Example:
//Java Program to demonstrate the use of continue statement //inside the for loop. public class ContinueExample { public static void main(String[] args) { //for loop for(int i=1;i<=10;i++){ if(i==5){ //using continue statement continue;//it will skip the rest statement } System.out.println(i); } } }
Output:
1
2
3
4
6
7
8
9
10
Java Continue Statement with Inner Loop
It continues the inner loop only if you use the continue statement inside the inner loop.
public class ContinueExample2 { public static void main(String[] args) { //outer loop for(int i=1;i<=3;i++){ //inner loop for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using continue statement inside inner loop continue; } System.out.println(i+" "+j); } } } }
Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
Java Continue Statement in while loop
public class ContinueWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using continue statement i++; continue;//it will skip the rest statement } System.out.println(i); i++; } } }
Output:
1
2
3
4
6
7
8
9
10
Java Arrays
Arrays are used instead of declaring separate variables for each value, to store multiple values in a single variable.
Defines the type of variable that has square brackets to declare an array:
Syntax:
String[] cars;
We have now declared a variable which holds a string array. We can use a literal array to insert values to it-place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write
int[] myNum = {10, 20, 30, 40};
The following program, ArrayDemo, creates an array of integers, puts some values in the array and prints these elements
class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // and so forth anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } }
Output:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Passing Arrays to Methods/How Array is Passed in Java Functions?
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array.
The technique is called Pass by reference. Java Arrays are passed to the function by reference or as a pointer to the original Array. This means anything we do to the Array inside the function affect the original. Here is an example of how Array elements affect when we pass by reference.
class MyArray{ public static void main(String args[]) { String b[]={"Love","Lovely","Lovable"}; System.out.println("Before change"+b[0]); MyArray.passByReference(b); System.out.println("After change"+b[0]); } public static void passByReference(String a[]){ a[0]="Loving"; } }
The output of the code:
Lovingpublic static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
In this way, we can pass an array into methods in JAVA.
Returning an Array from a Method
An Array may also be returned by a method. The following method, for example, returns an array that is the inversion of another array.
Example:
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; }
Multidimensional Arrays in JAVA
In such a case, data is stored in a row and column-based index this can be very helpful for graphics designing and programmer can use this approach to store data in rows and columns operation. Mostly, it can be used to draw graphs and trees for implementation which can be broadly used in networking.
Various Methods to Define Arrays:
- dataType[][] arrayRefVar; (or)
- dataType [][]arrayRefVar; (or)
- dataType arrayRefVar[][]; (or)
- dataType []arrayRefVar[];
Example:
int[][] arr=new int[3][3];//3 row and 3 column Output: arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; Example 2: class TestJaggedArray{ public static void main(String[] args){ //declaring a 2D array with odd columns int arr[][] = new int[3][]; arr[0] = new int[3]; arr[1] = new int[4]; arr[2] = new int[2]; //initializing a jagged array int count = 0; for (int i=0; i<arr.length; i++) for(int j=0; j<arr[i].length; j++) arr[i][j] = count++; //printing the data of a jagged array for (int i=0; i<arr.length; i++){ for (int j=0; j<arr[i].length; j++){ System.out.print(arr[i][j]+" "); } System.out.println();//new line } } }
Output:
0 1 2
3 4 5 6
7 8
Program to copy one array into another
class TestArrayCopyDemo { public static void main(String[] args) { //declaring a source array char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; //declaring a destination array char[] copyTo = new char[7]; //copying array using System.arraycopy() method System.arraycopy(copyFrom, 2, copyTo, 0, 7); //printing the destination array System.out.println(String.valueOf(copyTo)); } }
Output:
caffein
Program to check if two arrays are a clone of each other or not?
class Testarray1 { public static void main(String args[]){ int arr[]={33,3,4,5}; System.out.println("Printing original array:"); for(int i:arr) System.out.println(i); System.out.println("Printing clone of the array:"); int carr[]=arr.clone(); for(int i:carr) System.out.println(i); System.out.println("Are both equal?"); System.out.println(arr==carr); } }
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Addition of Two Matrices in Two Dimensional Arrays
class Testarray5{ public static void main(String args[]){ //creating two matrices int a[][]={{1,3,4},{3,4,5}}; int b[][]={{1,3,4},{3,4,5}}; //creating another matrix to store the sum of two matrices int c[][]=new int[2][3]; //adding and printing addition of 2 matrices for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.println();//new line } } }
Output:
See also Class ServerSocket in JavaPowered by Inline Related Posts2 6 8
6 8 10
Multiplication of 2 Arrays in JAVApublic class MatrixMultiplicationExample{ public static void main(String args[]){ //creating two matrices int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //multiplying and printing multiplication of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; }//end of k loop System.out.print(c[i][j]+" "); //printing matrix element }//end of j loop System.out.println();//new line } } }
Output:
6 6 6
12 12 12
18 18 18
Java Methods
- A method is a block of code that runs only when called
- You can pass the data into a method, known as parameters.
- Methods are used to perform some actions, and they are also called functions.
- Why do you use methods? To reuse code: define the code once, and use it as many times as you want.
Basic Syntax:
public class MyClass1 { static void myMethod1() { // code to be executed } }
- myMethod1() is the name of the method
- static means that the method belongs to the MyClass1 class and not an object of the MyClass1 class. You will learn more about objects and how to access methods through objects later in this tutorial.
- void means that this method does not have a return value.
Parameters and Arguments
Information may be passed as a parameter to the methods. Inside the method parameters act as variables.
Parameters are specified within the parentheses, after the name of the method. You can add as many parameters as you like, just divide them by a comma.
- The following example has a method which takes as a parameter a string named frame. When calling the method, we pass a first name which is used to print the full name inside the method:
Example:
public class MyClass static void myMethod(String fname, int age) { System.out.println(fname + " is " + age); public static void main(String[] args) { myMethod("Liam", 5) myMethod("Jenny", 8); myMethod("Anja", 31); } }
Note: We can use any type of loop and if/else or switch statement in the method body.
Example:
public class MyClass { // Create a checkAge() method with an integer parameter called age static void checkAge(int age) { // If age is less than 18, print "access denied" if (age < 18) { System.out.println("Access denied - You are not old enough!"); // If age is greater than 18, print "access granted" } else { System.out.println("Access granted - You are old enough!"); } } public static void main(String[] args) { checkAge(20); // Call the checkAge method and pass along an age of 20 } }
Output:
Access granted – You are old enough!
Method Overriding and Overloading
With method overloading, multiple methods can have the same name with different parameters:
int myMethod(int x) float myMethod(float x) double myMethod(double x, double y)
Overloading in JAVA
Overloading allows different methods to have the same name but different signatures where the number of input parameters or type of input parameters or both may differ. Compile-time (or static) polymorphism is related to overloading.
// Java program to demonstrate working of method // overloading in Java. public class Sum { // Overloaded sum(). This sum takes two int parameters public int sum(int x, int y) { return (x + y); } // Overloaded sum(). This sum takes three int parameters public int sum(int x, int y, int z) { return (x + y + z); } // Overloaded sum(). This sum takes two double parameters public double sum(double x, double y) { return (x + y); } // Driver code public static void main(String args[]) { Sum s = new Sum(); System.out.println(s.sum(10, 20)); System.out.println(s.sum(10, 20, 30)); System.out.println(s.sum(10.5, 20.5)); } }
Output:
30
60
61.6
Object-Oriented Programming in Java
History:
We’ll learn about the fundamentals of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.
Smalltalk is considered the first truly object-oriented programming language. We’ll learn about the fundamentals of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.
Smalltalk is considered the first truly object-oriented programming language.
- JAVA class and object:
- JAVA supports both functional and object-based programming.JAVApromotes features such as higher-order functions, function types and lambdas, makes it a great choice for working in a functional programming style.
- What is OOP?
In the object-oriented style of programming, you can divide a complex problem into smaller sets by creating objects.
Benefits:
Re-usability
It means reusing some of the facilities rather than building them again and again. This is done by using a class. We can use ‘ n ‘ so many times as we need.
Data Redundancy
This is a condition created at the data storage area (you can say Databases) where the same piece of data is processed in two separate places. Data redundancy is, therefore, one of the greatest advantages of OOP. If a user wants similar functionality in multiple classes, he/she can go ahead by writing and inherit common class definitions for similar functionalities.
Code Maintenance
This feature is more necessary for any programming language, it helps users to rework in many ways. Maintaining and modifying existing codes with new changes is always easy and time-saving.
Security
Using the mechanism of data hiding and abstraction, we filter out limited exposure data, which means that we maintain security and provide the necessary data to view.
Design Benefits
If you are practising OOPs, the design benefit that the user will have is to design and fix things easily and eliminate (if any) risks. After a time when the program has reached some critical limits, it is easier to program all non-OOPs separately.
Reuse of code through inheritance
How to make a JAVA class?
In JAVA, you need to define a class before you create objects.
A class is an Object Template.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
Since, many houses can be made from the same description, we can create many objects from a class.
Object Properties
Any entity having condition and behaviour is known as an object. A chair, pen, table, keypad, bike, etc., for example. That can be either physical or logical.
An Object can be defined as an instance of a class. An object has an address and takes up some memory space. Objects can communicate without knowing the particulars of the data or code of each other. The only thing necessary is the type of message that is accepted, and the type of response that the objects return.
Class Properties in JAVA
A class can be considered a blueprint that can be used to create as many objects as you want. We have a class website, for example, which has two data members (also known as fields, instance variables, and object state). This is just a blueprint, it does not represent any website, however, we can create Website objects (or instances) representing the websites using this. We created two objects, and we provided separate properties to the objects using constructor while creating objects.
Example:
public class Website { //fields (or instance variable) String webName; int webAge; // constructor Website(String name, int age){ this.webName = name; this.webAge = age; } public static void main(String args[]){ //Creating objects Website obj1 = new Website("Animesh ", 5); Website obj2 = new Website("google", 18); //Accessing object data through reference System.out.println(obj1.webName+" "+obj1.webAge); System.out.println(obj2.webName+" "+obj2.webAge); } }
Output:
Animesh 5
google 18
Constructor in JAVA
The constructor looks like a method but it’s not a method. The name is identical to the name of the class and it does not return any value. You have to have seen this statement in nearly all the programs I shared above
public class ConstructorExample { int age; String name; //Default constructor ConstructorExample(){ this.name="Chaitanya"; this.age=30; } //Parameterized constructor ConstructorExample(String n,int a){ this.name=n; this.age=a; } public static void main(String args[]){ ConstructorExample obj1 = new ConstructorExample(); ConstructorExample obj2 = new ConstructorExample("Steve", 56); System.out.println(obj1.name+" "+obj1.age); System.out.println(obj2.name+" "+obj2.age); } }
Output:
Chaitanya 30
Steve 56
Pillars of JAVA Object-Oriented Programming
- Encapsulation
- Inheritance
- Polymorphism
Encapsulation
Encapsulation simply means binding object state and behaviour together. If you are creating class, you are doing encapsulation. The concept by which an oops code binds the code and data together. Encapsulation also helps in data hiding.
Abstraction:-
This feature of oops, reduce the complexity by hiding details. Abstraction identifies the essential properties and behaviours of an object without many details.
Example:
class EmployeeCount { private int numOfEmployees = 0; public void setNoOfEmployees (int count) { numOfEmployees = count; } public double getNoOfEmployees () { return numOfEmployees; } } public class EncapsulationExample { public static void main(String args[]) { EmployeeCount obj = new EmployeeCount (); obj.setNoOfEmployees(5613); System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees()); } }
Output:
No Of Employees: 5613
Benefits
So what’s the benefit of encapsulation in java programming Well, if you want to change the implementation details of the EmployeeCount class at some point, you can do so freely without affecting the classes that use it.
Inheritance
It is called inheritance by the process by which one class acquires the properties and functionalities of another. Inheritance provides the idea of code reusability and each subclass defines only those characteristics that are unique to it, the rest of the characteristics can be inherited from the parent class.
This feature of oops enables the subclasses or derived classes to avail the data and methods of the superclass. Inheritance provides better code reusability.
Inheritance is a process of defining a new class by extending its common data members and methods, based on an existing class.
Heritage enables us to reuse code, enhancing the reusability of your java application.
In inheritance, properties of one class get transferred to another class. From the source class, the properties get transferred to destination class. The source class is called as superclass, or a base class or child class.
A child class will contain all features of the base class but it may also contain new features. Defined in the extended class.Java does not support multiple inheritances. But using multiple interface inheritance we can achieve the same.
The class of parents is called the class of base, or superclass. The child class extending the base class is referred to as the derived class or subclass or child class.
Syntax:
class A extends B { }
Example:
class Teacher { String designation = "Teacher"; String college = "Beginnersbook"; void does(){ System.out.println("Teaching"); } } public class MathTeacher extends Teacher{ String mainSubject = "Maths"; public static void main(String args[]){ MathTeacher obj = new MathTeacher(); System.out.println(obj.college); System.out.println(obj.designation); System.out.println(obj.mainSubject); obj.does(); } }
Output: Beginnersbook Teacher Maths Teaching Example 2
class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); } public static void main(String args[]) { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); } }
Output:
javac My_Calculation.java
java My_Calculation
Types of Inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class. For example, class A extends class B and class B extends class C.
Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extend the same class. For example, class B extends class A and class C extends class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a child class has two parent classes. Java doesn’t support multiple inheritances.
Member Hiding:-
If a child class has a member same name as the parent class, then after extension it hides the parent class member. The member can be a variable or a method with the same signature.
Technically, both the members are amiable to the child class, but if we use member name, the child class’s member can be accessed. This is called member hiding.
Polymorphism
Polymorphism- this feature of oops allows same interface to be used for a general class of actions.
Most oops use polymorphism via –
- Method Overloading
- Method Overriding
- Operator overloading
Polymorphism is an object-oriented programming feature that enables us to perform one action in various ways. For example, let’s say we have an animal class that has an animalSound() (method, because we don’t know which animal class would extend the animal class, we can’t implement this method.
So, we make this method abstract like this:
Syntax:
public abstract class Animal{ ... public abstract void animalSound(); }
Example:
public class Lion extends Animal{ ... @Override public void animalSound(){ System.out.println("Roar"); } } public class Lion extends Animal{ ... @Override public void animalSound(){ System.out.println("Roar"); } }
Types of Polymorphism
- Static Polymorphism
- Dynamic Polymorphism
Static Polymorphism
The polymorphism is known as static polymorphism, which is resolved during compiler time. The overloading of methods can be considered an example of static polymorphism.
Method Overloading: This allows us to have more than one method in a class that differs in the signature, with the same name.class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { } System.out.println(c + " "+num); { } public class ExampleOverloading { } public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } }
Output:
a
a 10
Dynamic Polymorphism
it is also known as Dynamic Dispatch Method. Dynamic polymorphism is a process in which at runtime rather a call to an overridden method is resolved, which is why it is called polymorphism in runtime.
class Animal{ public void animalSound(){ System.out.println("Default Sound"); } } public class Dog extends Animal{ public void animalSound(){ System.out.println("Woof"); } public static void main(String args[]){ Animal obj = new Dog(); obj.animalSound(); } }
Output:
Woof
IS-A & HAS-A Relationships
A Car IS-A Vehicle and HAS-A License then the code would look like this:
public class Vehicle { } public class Car extends Vehicle { } private License myCarLicense; { }
Interfaces in Java
Read more on Interface in Java
Access Specifiers in JAVA
Well, in the examples I shared above, you have to have seen a public, private keyword They are called access specifiers because they decide on the scope of a member, method/class of the data.
In java, there are four types of access specifications public: accessible to all. Other objects can access the variable or function of this member too.
Private: Not accessible through any other object. Private members in the same class can only be accessed through the methods. An object that is only accessible in the class they are declared to.
Protected: The scope of the protected variable is within the class that declares it, and within the class that inherits it (Scope is class and subclass).
Default: Package level is scope. We don’t need to explicitly mention the default as it is considered default when we don’t mention any access specification.
Read Package concept.
How To Use Inner Class or Nested Class in Java? How To Use Inner Class or Nested Class in Java?
Inner Class is popularly known as nested class. As the name suggested, inner class means a class or a group of classes within a class. Basically these are helper class.
An example could be-
class mainClass{ ...... class subClass1{ ...... } class subclass2{ ...... }
Nested classes are mainly two types-
1. Static-those inner classes declared as static called static nested classes
2. Non-Static-those inner classes are declared as other than static called inner class.
Read in details of Static and Non-static Inner classes hereNon Static class can be further divided into 3 types
1. Instance Inner class:
2. Local Inner class
3. Anonymous inner classAbove given code is an example of a non-static inner class.
A static inner class example could be-
class mainClass{ ...... static class subClass1{ ...... } class subclass2{ ...... } }
What is the difference between the two classes?
Well, non-static nested classes popularly called inner classes can access to other members of the enclosing classes but a static class can’t. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.
Nesting classes are nothing but to create a relationship between classes.Static Member Classes Instance Inner Classes Local classes Anonymous Classes A static member class can access all static methods of the parent class These are local classes that have no name Static Member class does not have an implicit reference to the outer class as it is static. These classes can have some implicit reference to the outer class object once instantiated These classes can have some implicit reference to the outer class object once instantiated Then why we will use Nested Classes?
if you are doing complex UI design and implementing complex algorithms nested class allows you to do —
1. Logical grouping-all classes in one place so it increases the maintainability.
2. More encapsulation-more hiding but create a great package organization
3. White box testing becomes easy and code becomes truly object-oriented.
4. Provides a classic callback to the methods defined inside these classes.To instantiate an inner class, we must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
For static class, the mechanism will be
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Most popular Inner class example..
public class OuterClass { private String outerString="Hello from outer"; class inner { String innerString="Hi from inner" ; void callBack() { System.out.print("Calling from Inner"+innerString); } } }
Now let me create the main class from where I will access the inner class…
public class TestClass { public static void main(String[] args) { OuterClass oC = new OuterClass(); OuterClass.inner ii=oC.new inner(); ii.callBack(); } }
This will call the callback method to perform the activity.
Now let us come to the second most used inner class.
Do you remember the code, we used to memorize during our fist assignment…to add an action listener to a button…Button1.addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent e ) { //do some activities here } } )
Disadvantages:
- From the novice programmer’s point of view, these type of classes and callback method may be tough to understand.
- Maintainability becomes tough if the code is created in one java editor and opened in another editor. This is due to the editor’s incompatibilities.
Class Identifiers:
All classes produce a .class file after compilation. So as the Inner classes. It follows a strict formula to identify the inner class. The formula is as given below:
outerClass$innerclass.class // so in the same location where the outer class exists there will be two classes: outerClass.class outerClass$innerclass.class
These classes are also platform-independent in nature.
What Is Return Statement In Java??
Methods can send some value to the calling method. Now how JVM will understand that the calling function is expecting some value??
Well if JVM encounters a “return” statement it will understand that the calling function is expecting something and the called method is suppose to send something.int a=10; int b=20; int val=add(a,b) //called the function named as add with two arguments public int add(int x,int y) //called method add will accept two parameters { return (x+y); //this will return addition of two variables. }
There might be a case where the called method is of type void. here the return keyword is used only to exit the method and it is not mandated to give return statement here.
But when we have a proper return statement for a method we also need to take care of the type of the return.
Now if we want to send more than one value from the called method then what will be our approach??
Well …for that case we need to create an array and will return the array to the calling method.
Annotation Concept Simplified in Java
Annotation is known as metadata for a code. We can use this feature to merge additional java elements with programming code like in classes, methods, parameters, local variables, packages, fields etc. Annotations viz metadata are stored in java class file(source file)by the compiler.
These class files are used by the JVM or by the program to find out the metadata for interacting with the code elements.Java.lang.annotation package contains all annotation classes.
The classes that implement the Annotation element interface are:
- java.lang.reflect.accesibleObject
- java.lang. class
- java.lang.reflect.Constructor
- java.lang.reflect.field
- java.lang.package
- java.lang.reflect.method
Standard Annotation:
Annotation Comments @Depreciated The compiler warns when deprecated java elements are used in non-deprecated program or context. @Overrides Compiler generated error when the method uses this annotation type does not override the methods present in the superclass @Documented Indicates annotation of this type to be documented by Javadoc @Inherited Indicates that this type is automatically inherited @Retention Indicates the extended period using the annotation type. @Target Indicates to which program element the annotation is applicable The annotation declaration is similar to the interface declaration. we need to use @<annotation name> or keyword and we need to use @before keyword interface.
package myPackage.annotation; import java.lang.annotation*; @Retention(Retentionpolicy.RUNTIME); @Target(ElementType.METHOD) public @interface MyTest{ Integer calculate(); }
//Meta annotations which declare that the @MyTest annotations must be stored in a class file.
@Target meta-annotation is used to declare the @MyTest annotation which annotates the methods in the java class file.
@interface meta-annotation is used to declare the @MyTest annotation with the member called calculate which returns Integer as an object.
Generic Guideline to Create Annotation:- Do not use extends clause. It automatically extends the market interface java.lang.annotation.Annotation.
- Do not use any parameter for the method
- Do not use generic methods
- Do not use throws clause
Annotations are majorly used to test the class, method, variable etc.
import junit.annotation.*; public class TestMyMethods{ @UnitTest(value="Test positive") public void positiveTest(int no) { assert no>0; } @UnitTest(value="Test negative") public void negativeTest(int no) { assert no<0 }
We can merge annotation with code elements. We can also use the methods available in the marker interface, java.lang.reflect.Annotated element query about the existence of the programming element and get their values.
The methods of the Annotated Element interface are:- IsAnnotationPresent();
- getAnnotations();
- getAnnotation();
- getDectaredAnnotations()
Use of Annotation in real code:
import java.lang.annotation.*; import java.lang.reflect.*; @Retention(RetentionPolicy.RUNTIME) @interface MySingle{ int value(); } public class Single{ //annotate a method using a marker @MySingle(100) public static void myMethod(){ Single ob=new Single(); try{ Method m=ob.getClass().getMethod("myMethod"); MySingle assno=m.getAnnotation(MySingle.class); System.out.println("The value is"+assno.value());//displays 100 } catch(NoSuchMethodException e) { System.out.println("Metod not found"); } } public static void main(String args[]) { MyMethod(); } }
What is the difference between Java Applications and Java Applets?
Below are the differences between a java application and java applets. They are as follows:
Application-Java Application-Applet The application needs a main() method to start execution. The applet does not need main() method instead it requires to init() method for the start-up. The application can take inputs from the command line and GUI. Applet parameters are embedded into HTML browser document. Can accept inputs from these or GUI Applications can be loaded from the file system or any class library(custom) Codes are transported via HTTP and fit into the browser’s predefined area. It can work on minimum memory Applet codes need to calculate the code memory plus the browser’s memory Application’s User graphics mode is optional hence they can sustain without any graphics viz GUI Applet depends on GUI hence it graphical. The application can work on file I/O and Sockets The applet does not support file I/O and sockets(other than host platform) Application need not be a subclass of any particular class. (By default the classes are a subclass of Object class) The applet must be a subclass of java. Applet class. The application can have menus Applet can not have menus Concept Of Infinity in Java Arithmetic Exception vs Display of Infinity
Learn java Concept Of Infinity in Java Have you ever heard of infinity concept in java? if no, this post is for you.
In mathematics x/y =infinity when y=0
in our normal computation, there is no way to show infinity. Normal computation means when we use integral arithmetic(data type-int,short,char,byte,long)So any of these datatype’s variable divided by zero, we are going to get an Arithmetic exception:: divided by zero error.
MostlyLet’s see how…
public class operatortest { public static void main(String[] Args) { int x=10; System.out.print(x/0); } }
Exact Error code:
Exception in thread “main” java.lang.ArithmeticException: / by zero at operatortest.main(operatortest.java:6)But when we will use double and float point arithmetic computation, we have a way to represent infinity.
public class operatortest { public static void main(String[] Args) { double x=10.00; System.out.print(x/0); } }
output: Infinity
In mathematics, we can have positive infinity and negative infinity. Similarly in java computation, we can have positive infinity and negative infinity.
The above-written code produces positive infinity.public class operatortest { public static void main(String[] Args) { double x=-10.00; System.out.print(x/0); } }
output: – Infinity
So please remember any number divided by zero does not necessarily give an arithmetic exception. There can be infinity too.
The corresponding definition can be found here
o POSITIVE_INFINITY
public final static double POSITIVE_INFINITY
Positive infinity.
o NEGATIVE_INFINITY
public final static double NEGATIVE_INFINITY
Negative infinity.
So for integral arithmetic, we will get Run time Error of Divide by Zero but for floating-point arithmetic, we will get positive or negative infinity rather than getting Run time error.Command Line Argument Simplified in Java
Command-line arguments are the information that we pass to the Java program during runtime. Mostly when we write java code in a standalone mode or non-GUI mode, we use Command line arguments to pass information to our program during run time. Java developers tried to create an interface between the code and the users by providing inputs to the programs instead of hard coding.
Standalone codes are mainly used to build the following.
- a prototype
- a stub
- a driver
- proof of concepts
- command-based coding
- configuration information for launching some application especially games.
In all the above cases we don’t need a full phased GUI to work with. We need some piece of code that shows the working model is correct. This is also applicable to the old days of coding when GUI coding did not flourish that much, coder used to provide all necessary information via command-line arguments. So there are a lot of data goes back and forth in command-line programming.
Lets us look at the main method declaration for java: It says “public static void main(String args[]) ” this means the main() method will take an argument called args. args is an array and it is of String type.
But array -args size is not defined. This says that main() can take N number of arguments from the user. In another word, the arguments are stored in an array and passed to the main() method for execution. The arguments are of type String and space is used as a separator. Who does all these transformations for us? Well, it is JVM. It reads the String, splits with space returns args array to main.
class myClass{ public static void main(String args[]) { System.out.println(args[0]); System.out.println(args[1]); } }
to execute this,(after compilation) in command prompt we need to provide the command to execute this code along with the arguments that need to be passed to the main() method.
java myClass Test arguments The output of the code will be Test argument
We can certainly make the code better by providing some logic to it.class myClass{ public static void main(String args[]) { if(args.length>0){ System.out.println("argument/arguments found"); for(int i=0;i<args.lenth;i++) System.out.println(args[i]); //or for (String myArgValue:args) System.out.println(myArgValue); } else { System.out.println("argument/arguments not found"); } } }
let’s check one more example with While loop:
class myClass{ public static void main(String args[]) { int count,i=0; String myString; count=args.length; while(i<count) { myString=args[i]; System.out.println("The input from the user is"+myString); } } }
Wrapper Class in Java:
Traditional containers like vector can not handle primitive data types like int,float, long, char and double. Primitive data types can be converted to objects using the wrapper classes. Wrapper classes are contained in the java.lang package.
Wrapper classes:
Simple type Wrapper class boolean Boolean char Character double Double float Float int Integer long Long Wrapper classes have a number of unique methods for handling primitive data types and objects.
Converting primitive numbers to object:Constructor calling conversion action Integer intval=new Integer(i); primitive integer i to Integer Object Float floatval=new Float(f); primitive float f to Float Object Double doubleval=new Double(d); primitive double d to Double Object Long longval=new Long(l) primitive long l to Long Object i,f,d,l are primitive data values denoting int,float,double,long data type. They may be constant or any variable.
Converting object numbers to primitive numbers using typeValue() method:Method Action int i=intVal.intValue() Object to primitive integer float f=floatVal.floatValue() Object to primitive float long l=longVal.longValue() Object to primitive long double d=doubleVal.doubleValue() Object to primitive double Converting numbers to String using toString() method:
Method Action String str=Integer.toString(i); primitive integer to String String str=Float.toString(f); primitive float to String String str=Double.toString(d); primitive double to String String str=Long.toString(l) primitive long to String Converting String objects to Numeric objects using static valueOf() method:
Method Action intVal=Integer.valueOf(str); String to an integer object longval=Long.valueOf(str); String to long object floatVal=Float.valueOf(Str); String to float object doubleVal=Double.valueOf(str) String to double object Converting Numeric Strings to primitive Numbers:
Method Action int intVal=Integer.parseInt(str) String to primitive integer long longval=Long.parseLong(str); String to primitive long float floatVal=Float.parseFloat(str) String to primitive float double doubleVal=Double.parseDouble(str) String to primitive double All these methods may throw the NumberFormatException if the value of the String(str) does not represent the proper number.
An Example:public class InterestCalculate{ public static void main(String []args){ //converting Number to object Float principalAmount=new Float(0); Float interestRate=new Float(0); int numYears=0; try{ DataInputStream in=new DataInputStream(System.in); System.out.println("Enter Principal Amount:"); System.out.flush(); String principalString=in.readLine(); //converting string to float object principalAmount=Float.valueOf(principalString); System.out.println("Enter rate of interest :"); System.out.flush(); String interestString=in.readLine(); //converting string to float object interestRate=Float.valueOf(interestString); System.out.println("Enter number of years :"); System.out.flush(); String yearString=in.readLine(); //converting string to int numYears=Integer.parseInt(yearString); } catch(IOException e) { System.out.println("I/O Error has occured"); } catch(NumberFormatException e) { System.out.println("Number format is not correct"); } float value=total(principalAmount,interestRate,numYears); System.out.println(); System.out.println("The final amount you will get"+value); } static float total(float p,float r,int n) { int year=1; float sum=p; while(year<=n) { sum=sum(1+r); year=year+1; } return sum; } }
Threads in Java
In general, processes mainly occupy different memory space. When CPU changes from one process to another, the state of the currently executing process is saved and the next process’s state is reloaded. During this switching operating system cannot do anything. This switching is referred to as context switching. This content switching should be as less possible to maximize CPU utilization.
On the other hand, threads are like independent processes. The main differences between the thread and processes are as follows:-
- Threads share same memory and state.
- The state contains mainly- Program counter and Stack pointer.
So context switching is significantly faster. So the CPU utilization is high if multiple threads are running.
Process-based multitasking:
The newly launched operating systems can run two or more programs at the same time. This phenomenon is called Process-based multitasking, like running Excel and a swing program. The process-based multitasking makes sure the priority of the program execution so that CPU utilization can be maximized.
In this process, CPU treats the programs as the smallest unit of code that can be dispatched by the scheduler.
Thread based multitasking:
In the pure multitasking process, CPU treats the threads as the smallest unit of execution. The whole process is divided into several numbers of threads executing concurrently. This helps us to handle multitasks concurrently with a single program or process.
So we can say process-based multitasking deals with actual user demands and thread-based multitasking handles the finer details.
Read more on Threads
Few Advanced topics
The Advantages of Java:
- Rich Feature of java
- Platform/System independent.-read more here
- Multithreaded-read more here
- Secure-read more here
- Easy development for large applications.
- Simple-Java API’ can simply be accessed by the Java developers.
- Portable-Java often allocates the objects on the stack.
- Robust(No memory-related tasks)-read more here
- High performance-The most commands of one CPU machine matches with mostly others.read more here. So java developers have come up with basic building blocks of assembly programming, which makes interpreter faster.
- Support Internet Access Capabilities
- Good language syntax and compiler friendly code.
- Well designed and inclusion of libraries
- New object creation and refuse of old objects.
- Support distributed computing.
- Java has no pointer for users. The referencing and dereferencing of objects is handled by compiler and garbage collector automatically.Java does not allow us to manipulate pointers or memory address. It does not allow us to cast object or array references into integers or vice versa. It does not allow us to do pointer arithmetic and also does not allow us to compute the size of bytes of any primitive type or object.
- Java being a free form language, does not need an indentation. It always looks for the line separator (;) a semicolon to divide the statements. However we must write a human-readable format while coding, hence we need an indentation.
- Great Exception handling
Downside of Java
- Huge learning curve.
- Change in the mentality thinking object orientation from procedural language.
- It is hard to design an object well.
Practice Question for Exercise which can be solved by JAVA
Analyse the problem, design unambiguous and precise algorithm and code for each of the following problems.
- Compute the cost per square foot of living space for a house, given the dimensions (Length, Width) of the house, the number of stories, the size of the non-living space (garage, closets), the total cost of the house.
- Given a positive integer number, find whether the number is even or odd.
- Given a positive integer number, find display if the number is a prime number.
- Find the slope of a line through two points using formula m =. The values of y1, y2, x1 and x2 are given. If x1 equals x2, the line is vertical and the slope is undefined. If y1 equals y2, the line is horizontal.
- Write code to calculate and print the diameter, the circumference, or the area of a circle given the radius. The input is two data items. The first is a character – ‘D’ (for diameter), ‘C’ for circumference, or ‘A’ for the area – to indicate the calculation needed. The next data value is a floating-point number indicating the radius of the particular circle.
- A company manufactures a line of traffic cones. It requires painting its cones in different colours. The company has hired you to write a program that will compute the surface area of the cone, and the cost of painting it, given its radius, height and the cost per square foot of three different colours of paint. The surface area of the cone can be calculated using formula
- Mother had just filled the cookie jar when the three children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 5 cookies in the jar. How many cookies were in the jar, to begin with? Find a generic solution to this problem.
- Find and display the sum of numbers from 1 to n where n is input by the user.
- Display a line of n stars.
- Input an integer value and if the input value is equivalent to the value of a British coin, print it out in words. Otherwise, it should print an error message.
Input Print
1 One Penny
2 Two Penny
5 Five Penny
10 Ten Pence
50 Fifty Pence
- Add a series of numbers input by the user and find the average of these numbers. It is not known in advance how many values will be input.
- Display the status of the students (Pass or Fail) based on the marks entered by the user. It is not known in advance how many marks will be entered.
- Find the hypotenuse of the right-angled triangle given its two sides using Pythagorean Theorem.
- Write a program that reads the lengths of the sides of a triangle from the user and computes and displays the area of the triangle using Heron’s formula. The Heron’s formula is:
Where A, B, C are three sides of a triangle and S is half perimeter and is calculated by
- Given the cost of a sales item, calculate the amount of sales tax and total cost of the sales item including tax assuming 7% sales tax.
- A person’s weekly pay is Rs. 2500/-. He is scheduled to receive a 3% pay raise next week. Calculate the amount of his new salary.
- In a video store, a daily rental fee of a video is Rs. 50/-. Customers are charged a late fee of Rs. 20/- per day when the video is returned past the due date. Assume that a customer can return only one video at a time, calculate the amount the customer owes when he/she returns the video.
- Given a positive integer number N, find display all the prime number that are less than or equal to N.
- A woman is going shopping to buy fifteen items only. Find the total cost of these fifteen items given the price of each item. Also, display the highest price and the lowest price.
- A perfect number is a positive integer such that the sum of proper divisors equals the number. Thus 28 = 1 + 2 + 4 + 7 + 14 is a perfect number. If the sum of proper divisors is less than the number, it is deficient. If the sum exceeds the number, it is abundant. Write a program that allows the user to enter a positive integer N and then displays all perfect, deficient, and abundant numbers less than or equal to N.
- You can also refer here for more.