Showing posts with label Java basics. Show all posts
Showing posts with label Java basics. Show all posts

Saturday, February 17, 2024

What Are JVM, JRE And JDK in Java

This post gives a brief explanation of JVM, JRE and JDK in Java. Before going into that explanation you should also know what is bytecode in Java.

What is bytecode in Java

When a Java program is compiled, it is not directly compiled into machine language but into an intermediate code known as bytecode. Bytecode is platform independent and it still needs to be interpreted and executed by the JVM installed on the specific platform.

For example let's say you have a Java file called "Test.java". When you compile this file you get a file called "Test.class" which is the bytecode for your Java file. JVM interprets and executes this Test.class file.

JVM

JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on. JVM is platform dependent and different implementations of JVMs are available for specific platforms.

A Java program can run on a specific platform only when-

  • JVM has been implemented for a platform.
  • JVM has been installed on a platform.

The JVM doesn't understand Java program as we write it, it understands the ".class" file which we get by compiling the .java file. This ".class" file contains the bytecode understandable by the JVM. It is because of JVM that Java is called a "portable language" (write once, run anywhere)

Following figure shows the abstraction provided by JVM by sitting in between the bytecode and the specific platform.

Bytecode interpretation by JVM

JRE

JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. It is actually the JRE that enables Java bytecode to run on any platform. Bytecodes, which are interpreted by the JVM, simply call classes found in the JRE when they need to perform actions they cannot do by themselves

JVM and JRE in Java

JDK

JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

That's all for this topic What Are JVM, JRE And JDK in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Why main Method static in Java
  2. Why Class Name And File Name Should be Same in Java
  3. Java Pass by Value or Pass by Reference
  4. static Keyword in Java With Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Class in Java
  2. Object in Java
  3. Encapsulation in Java
  4. Constructor Chaining in Java
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. Difference Between Comparable and Comparator in Java
  7. Java Semaphore With Examples
  8. Spring Bean Life Cycle

Sunday, January 7, 2024

Java Basics Tutorial

Java, one of the most popular programming language, was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It was publicly released in 1995.

Java is an object oriented, high level language but what sets it apart is that Java is platform independent and it can run on a variety of platforms.

This Java beginners tutorial helps in understanding the basic concepts of Java programming language.

Java Getting Started

  1. How to Install Java in Ubuntu
  2. First Java Program - Hello World Java Program
  3. Primitive Data Types in Java
  4. Java Variable Types With Examples
  5. Literals in Java
  6. What Are JVM, JRE And JDK in Java
  7. Java is a Strongly Typed Language

Operators in Java

  1. Arithmetic And Unary Operators in Java
  2. Equality And Relational Operators in Java
  3. Conditional Operators in Java With Examples
  4. Ternary Operator in Java With Examples
  5. instanceof Operator in Java With Examples
  6. Difference Between equals() Method And equality Operator == in Java

Conditional Statements & Loops in Java

  1. if else Statement in Java With Examples
  2. Switch Case Statement in Java With Examples
  3. Switch Expressions in Java 12
  4. Java for Loop With Examples
  5. Java while Loop With Examples
  6. Java do-while Loop With Examples
  7. break Statement in Java With Examples
  8. continue Statement in Java With Examples
  9. return Statement in Java With Examples

Java Class And Object

  1. Class in Java
  2. Object in Java
  3. Object Creation Using new Operator in Java
  4. Object class in Java
  5. Type Wrapper Classes in Java
  6. Java Abstract Class and Abstract Method
  7. Java Nested Class And Inner Class
  8. Java Object Cloning - clone() Method
  9. Shallow Copy And Deep Copy in Java Object Cloning

Java Constructor

  1. Constructor in Java
  2. Constructor Chaining in Java
  3. Constructor Overloading in Java
  4. Initializer Block in Java

Java Basics

  1. Access Modifiers in Java - Public, Private, Protected and Default
  2. Package in Java
  3. Java Automatic Numeric Type Promotion
  4. Why Class Name And File Name Should be Same in Java
  5. Why main Method static in Java
  6. Java Pass by Value or Pass by Reference
  7. Java - Could not find or load main class error Fix
  8. this Keyword in Java With Examples
  9. super Keyword in Java With Examples
  10. final Keyword in Java With Examples
  11. strictfp in Java
  12. finalize() Method in Java
  13. Type Casting in Java With Conversion Examples
  14. Why no Multiple Inheritance in Java

static in Java

  1. static Keyword in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. static Import in Java With Examples
  4. static Reference to The Non-static Method or Field Error
  5. static Block in Java

Array in Java

  1. Array in Java With Examples

Java Math

  1. BigDecimal in Java With Examples
  2. BigInteger in Java With Examples

OOPS Concepts

  1. Encapsulation in Java
  2. Polymorphism in Java
  3. Abstraction in Java
  4. Inheritance in Java
  5. Difference Between Encapsulation And Abstraction in Java
  6. Method Overloading in Java
  7. Method Overriding in Java
  8. Association, Aggregation And Composition in Java

Interface in Java

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Difference Between Abstract Class And Interface in Java
  4. Interface Default Methods in Java
  5. Interface Static Methods in Java
  6. Private Methods in Java Interface

String in Java

  1. String in Java Tutorial
  2. String Pool in Java
  3. Why Java String is Immutable
  4. Compact Strings in Java
  5. Check String Null or Empty in Java
  6. String Comparison in Java - compareTo(), equals()
  7. Java String charAt() Method With Examples
  8. Java String substring() Method - Getting Substring
  9. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  10. Java trim(), strip() - Removing Spaces From String
  11. Java split() Method - Splitting a String
  12. Java join() Method - Joining Strings
  13. intern() Method in Java String
  14. matches() method in Java String
  15. StringJoiner Class in Java With Examples
  16. StringBuffer Class in Java With Examples
  17. StringBuilder Class in Java With Examples
  18. String Vs StringBuffer Vs StringBuilder in Java
  19. Is String Thread Safe in Java
  20. How to Create Immutable Class in Java

Java Exception handling

  1. Java Exception Handling Tutorial
  2. try-catch Block in Java Exception Handling
  3. finally Block in Java Exception Handling
  4. Multiple Catch Blocks in Java Exception Handling
  5. Nested Try Statements in Java Exception Handling
  6. throw Statement in Java Exception Handling
  7. throws Keyword in Java Exception Handling
  8. Exception Propagation in Java Exception Handling
  9. Java Exception Handling And Method Overriding
  10. Difference Between Checked And Unchecked Exceptions in Java
  11. Difference Between throw And throws in Java
  12. final Vs finally Vs finalize in Java
  13. Creating Custom Exception Class in Java
  14. Multi-Catch Statement in Java Exception Handling
  15. Try-With-Resources in Java With Examples
  16. Best Practices For Exception Handling in Java
  17. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  18. java.lang.ClassCastException - Resolving ClassCastException in Java
  19. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  20. Difference Between StackOverflowError and OutOfMemoryError in Java

Tuesday, September 19, 2023

super Keyword in Java With Examples

The super keyword in java is essentially a reference variable that can be used to refer to class' immediate parent class.

Usage of super in Java

super keyword in Java can be used for the following-

  • Invoke the constructor of the super class. See example.
  • Accessing the variables and methods of parent class. See example.

First let's see how code will look like if super() is not used.

Let's say there is a super class Shape with instance variables length and breadth. Another class Cuboids extends it and add another variable height to it. When you are not using super(), constructors of these 2 classes will look like-

public class Shape {
 int length;
 int breadth;
 Shape(){
  
 }
 // Constructor
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 int height;
 //Constructor
 Cuboids(int length, int breadth, int height){
  this.length = length;
  this.breadth = breadth;
  this.height = height;
 }
}

It can be noticed there are 2 problems with this approach-

  • Duplication of code as the same initialization code in the constructor is used twice. Once in Cuboids class and once in Shape class.
  • Second and most important problem is super class instance variables can not be marked as private because they have to be accessed in child class, thus violating the OOP principle of Encapsulation.

So super() comes to the rescue and it can be used by a child class to refer to its immediate super class. Let's see how super keyword can be used in Java.

Using super to invoke the constructor of the super class

If you want to initialize the variables that are residing in the immediate parent class then you can call the constructor of the parent class from the constructor of the subclass using super() in Java.

Note: If you are using super to call the constructor of the parent class then super() should be the first statement inside the subclass' constructor. This ensures that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.

Java example code using super

public class Shape {
 private int length;
 private int breadth;
 Shape(){
  
 }
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 private int height;
 Cuboids(int length, int breadth, int height){
  // Calling super class constructor
  super(length, breadth);
  this.height = height;
 }
}

Here it can be noticed that the instance variables are private now and super() is used to initialize the variables residing in the super class thus avoiding duplication of code and ensuring proper encapsulation.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

That will happen when a constructor is explicitly defined for a class. Then the Java compiler will not insert the default no-argument constructor into the class. You can see it by making a slight change in the above example.

In the above example, if I comment the default constructor and also comment the super statement then the code will look like-

public class Shape {
  private int length;
  private int breadth;
  /*Shape(){
   
  }*/
  Shape(int length, int breadth){
   this.length = length;
   this.breadth = breadth;
  }
}

class Cuboids extends Shape{
  private int height;
  Cuboids(int length, int breadth, int height){
   // Calling super class constructor
   /*super(length, breadth);*/
   this.height = height;
  }
}

This code will give compile-time error. "Implicit super constructor Shape() is undefined".

Using super to access Super class Members

If method in a child class overrides one of its superclass' methods, method of the super class can be invoked through the use of the keyword super. super can also be used to refer to a hidden field, that is if there is a variable of the same name in the super class and the child class then super can be used to refer to the super class variable.

Java example showing use of super to access field

public class Car {
 int speed = 100;
 
}

class FastCar extends Car{
 int speed = 200;
 FastCar(int a , int b){
  super.speed = 100;
  speed = b;
 }
}

Here, in the constructor of the FastCar class super.speed is used to access the instance variable of the same name in the super class.

Example showing use of super to access parent class method

public class Car {
 void displayMsg(){
  System.out.println("In Parent class Car");
 }
}

class FastCar extends Car{
 void displayMsg(){
  System.out.println("In child class FastCar");
  // calling super class method
  super.displayMsg();
 }
 public static void main(String[] args){
  FastCar fc = new FastCar();
  fc.displayMsg();
 }
}
public class Test {

 public static void main(String[] args){
  FastCar fc = new FastCar();
  fc.displayMsg();
 }
}

Output

In child class FastCar
In Parent class Car

Points to note-

  • super keyword in java is a reference variable to refer to class' immediate parent class.
  • super can be used to invoke the constructor of the immediate parent class, that's help in avoiding duplication of code, also helps in preserving the encapsulation.
  • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
  • super can also be used to access super class members.
  • If a variable in child class is shadowing a super class variable, super can be used to access super class variable. Same way if a parent class method is overridden by the child class method then the parent class method can be called using super.

That's all for this topic super Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. static Keyword in Java With Examples
  4. TypeWrapper Classes in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Method Overloading in Java
  2. Constructor Chaining in Java
  3. Inheritance in Java
  4. Covariant Return Type in Java
  5. How to Read Input From Console in Java
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Deadlock in Java Multi-Threading
  8. Java ThreadLocal Class With Examples

Sunday, November 27, 2022

Why no Multiple Inheritance in Java

Inheritance is one of the four fundamental OOP concepts. It can be defined as a mechanism, by which one class acquires, all the properties and behaviors of another class. Java being an object oriented language does support inheritance. Though with in inheritance there are several types like-

  • Single inheritance
  • Multi-level inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Hybrid inheritance

Out of these Java does not support multiple inheritance, in this post we'll see why multiple inheritance is not supported in Java.


Multiple inheritance support in Java

Multiple inheritance as the name suggests means inheriting from multiple sources, it may be classes or interfaces.

Out of these two sources Java doesn’t support multiple inheritance through classes. So you are not permitted to extend more than one class in Java. Though you can still implement several interfaces.

For example, if there are three classes- ClassA, ClassB and ClassC. Then-

public class ClassA extends ClassB, ClassC 

Where ClassA is trying to extend multiple classes; ClassB and ClassC is not permitted in Java.

At the same time-

public class ClassA implements InterfaceB, InterfaceC 

where InterfaceB and InterfaceC are interfaces that are implemented by the classA is permitted.

Why no multiple inheritance in Java through classes

Multiple inheritance by extending several classes is one feature omitted in the Java language as the designers of the Java language opined that multiple inheritance is a confusing feature and it causes more problems than it solves.

One of the reason given for omitting multiple inheritance in Java is to avoid “diamond problem” which is one of the classic multiple inheritance problem.

Multiple inheritance and Diamond problem

It is best to explain diamond problem with an example so let’s take an example where we have 4 classes. On top of the hierarchy is ClassA which is extended by two classes ClassB and ClassC and there is another class ClassD which extends both ClassB and ClassC. Because of the diamond shaped class structure it is known as diamond problem.

diamond problem in Java

Let’s assume in ClassA there is a method displayGreeting() which is inherited by ClassB and ClassC and they both override it and provide their own implementation of the displayGreeting() method. When ClassD extends both classes ClassB and ClassC there is an ambiguity. Which displayGreeting() method should it inherit or override.

So the ambiguity which multiple inheritance can bring in to parent-child class structure is one reason multiple inheritance is omitted in Java.

Multiple inheritance with interfaces

Java does allow multiple inheritance using several interfaces if not by extending several classes. Though a proper term would be multiple implementation not multiple inheritance as a class implementing interfaces is responsible for providing implementation.

Multiple Inheritance with Interfaces Java Example

There are two interfaces MyInterface1 and MyInterface2 with a method displayGreeting(), there is also a class MyClass which implements both these interfaces. With interfaces, even if there is a similar method in both the interfaces there is no ambiguity as the class that implements provide the implementation.

public interface MyInterface1 {
 public void displayGreeting(String msg);
}
public interface MyInterface2 {
 public void displayGreeting(String msg);
}
public class MyClass implements MyInterface1, MyInterface2{

 public static void main(String[] args) {
  MyClass myClass = new MyClass();
  MyInterface1 myInt1 = myClass;
  MyInterface2 myInt2 = myClass;
  myInt1.displayGreeting("Welcome");
  myInt2.displayGreeting("Hello");
 }

 @Override
 public void displayGreeting(String msg) {
  System.out.println(msg);
 }
}

Output

Welcome
Hello

Back to multiple inheritance ambiguity with default interfaces

In Java 8, interface default methods are added and the inclusion of default methods interfaces may result in multiple inheritance issues.

Let's see it with an example-

Let's assume there are two interfaces MyInterface1 and MyInterface2 and both have default method displayGreeting(). There is a class MyClass which implements both these interfaces MyInterface1 and MyInterface2.

Now consider the scenarios-

  • Which implementation of default method displayGreeting() will be called when MyClass is implementing both interfaces MyInterface1 and MyInterface2 and not overriding the displayGreeting() method.
  • Which implementation of displayGreeting() will be called when MyClass is implementing both interfaces MyInterface1 and MyInterface2 and overriding the displayGreeting() method and providing its own implementation.
  • If interface MyInterface1 is inherited by interface MyInterface2, what will happen in that case?

To handle these kinds of scenarios, Java defines a set of rules for resolving default method conflicts.

  • When class implements both interfaces and both of them have the same default method, also the class is not overriding that method then the error will be thrown.
    "Duplicate default methods named displayGreeting inherited from the interfaces"
  • If implementing class overrides the default method and provides its own functionality for the default method then the method of the class takes priority over the interface default methods.

    As Example, if MyClass provides its own implementation of displayGreeting(), then the overridden method will be called not the default method in MyInterface1 or MyInterface2.

  • In case when an interface extends another interface and both have the same default method, the inheriting interface default method will take precedence. Thus, if interface MyInterface2 extends MyInterface1 then the default method of MyInterface2 will take precedence.
public interface MyInterface1 {
 // default method
 default void displayGreeting(String msg){
  System.out.println("MyInterface1 " + msg);
 }
}
public interface MyInterface2 {
 // default method
 default void displayGreeting(String msg){
  System.out.println("MyInterface2 " + msg);
 }
}
public class MyClass implements MyInterface1, MyInterface2{

 public static void main(String[] args) {
  MyClass myClass = new MyClass();
  MyInterface1 myInt1 = myClass;
  MyInterface2 myInt2 = myClass;
  myInt1.displayGreeting("Welcome");
  myInt2.displayGreeting("Hello");
 }

 @Override
 public void displayGreeting(String msg) {
  System.out.println(msg);
 }
}

Output

Welcome
Hello

Usage of super with default method

There is one more option to use super in order to call default method. If you want to call the default method of any of the interfaces from the implementing class super can be used to resolve the conflict.

If you use the same class structure as above and you want to call the default displayGreeting() method of the MyInterface1 then it can be done as follows-

public class MyClass implements MyInterface1, MyInterface2{

 public static void main(String[] args) {
  MyClass myClass = new MyClass();
  MyInterface1 myInt1 = myClass;
  myInt1.displayGreeting("Welcome");
  /*MyInterface2 myInt2 = myClass;
  
  myInt2.displayGreeting("Hello");*/
 }

 @Override
 public void displayGreeting(String msg) {
   MyInterface1.super.displayGreeting(msg);
 }
}

That's all for this topic Why no Multiple Inheritance in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Encapsulation in Java
  2. Polymorphism in Java
  3. Abstraction in Java
  4. Inheritance in Java
  5. interface static methods in Java 8

You may also like-

  1. Object Creation Using new Operator in Java
  2. instanceof Operator in Java
  3. Difference Between equals() Method And equality Operator == in Java
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Difference Between CountDownLatch And CyclicBarrier in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  8. Externalizable Interface in Java

Monday, September 26, 2022

Java - Could not find or load main class error Fix

In this post we'll see when you can get "Could not find or load main class error" in Java and how to resolve it. From the error itself it is evident when you are trying to run the program JVM is not able to find a class with main method and start the execution.

Could not find or load main class error and resolution

Two scenarios where you may encounter this error are-

  1. Not using the correct class name while executing the program.
  2. Not using the fully qualified class name and from the correct path.

Let's try to see both scenarios with an example.

Here is a simple Java program written in a class named "MyJavaClass" and saved in a file name "MyJavaClass.java"

public class MyJavaClass{
	public static void main(String[] args){
		System.out.println("This is my Java program");
	}
}

You can compile this Java program using the javac command and passing the full file name.

javac MyJavaClass.java

Once the file is compiled a .class file with the exact same name as the class name in your Java program is generated in the same directory where the java file resides.

In order to run the program, you will have to use the java command and passing the name of the .class file. That's when you can make a mistake where you can get "Could not find or load main class error"

1. Not using the correct class name

Since the generated class file has the exact same name as the class name which means class file in our example is generated as MyJavaClass.class. If you need to run your program, you will have to use the following command.

C:\>java MyJavaClass
This is my Java program

If you deviate in any way from this name you will get the error.

C:\>java Myjavaclass
Error: Could not find or load main class Myjavaclass
Caused by: java.lang.NoClassDefFoundError: MyJavaClass (wrong name: Myjavaclass)

Here name is given as Myjavaclass instead of MyJavaClass thus the error.

2. Even the extension .class is not required.

As you can see while executing the program you have to give the name of the class with out the extension .class. Giving the full name while trying to execute also results in an error.

C:\>java MyJavaClass.class
Error: Could not find or load main class MyJavaClass.class
Caused by: java.lang.ClassNotFoundException: MyJavaClass.class

Class in a package

In the above example we have not used any package but having a class within a package may also cause the "Could not find or load main class error" if fully qualified class name is not used and from the correct path.

Let's try to include a package in our example program.

package com.netjstech;

public class MyJavaClass{
	public static void main(String[] args){
		System.out.println("This is my Java program");
	}

}

You can use the following command to compile it so that the correct folder structure as per the package name given is created.

C:\>javac -d . MyJavaClass.java

With this command you will see that the .class file is created with in the folder com\netjstech. You may think that by going to that location you should be able to run the program.

C:\com\netjstech>java MyJavaClass
Error: Could not find or load main class MyJavaClass
Caused by: java.lang.NoClassDefFoundError: com/netjstech/MyJavaClass (wrong name: MyJavaClass)

As you can see now even after providing the correct class name (java MyJavaClass) still there is an error.

Class is in the package now, so you need to use the fully qualified class name (package + class name) to locate the class. Fully qualified class name in our case is- com.netjstech.MyJavaClass

C:\com\netjstech >java com.netjstech.MyJavaClass
Error: Could not find or load main class com.netjstech.MyJavaClass
Caused by: java.lang.ClassNotFoundException: com.netjstech.MyJavaClass

As you can see even that results in an error because you are already at the location (com\netjstech) and then you are using the fully qualified class name too. When you use the fully qualified class name Java itself tries to use that full name to find the correct location.

In our case when we give the fully qualified name (java com.netjstech.MyJavaClass), Java tries to look for the class MyJavaClass with in com\netjstech from the current path which itself is C:\com\netjstech.

So, you need to go two levels up and then use the fully qualified name to run this program successfully.

C:\> java com.netjstech.MyJavaClass
This is my Java program

That's all for this topic Java - Could not find or load main class error Fix. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Reference to The Non-static Method or Field Error
  2. Why Class Name And File Name Should be Same in Java
  3. Why main Method static in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Difference Between StackOverflowError and OutOfMemoryError in Java
  2. final Keyword in Java With Examples
  3. Deadlock in Java Multi-Threading
  4. HashMap Vs LinkedHashMap Vs TreeMap in Java
  5. Interface Static Methods in Java
  6. Compare Dates in Java
  7. Angular @Input and @Output Example
  8. Spring JdbcTemplate Insert, Update And Delete Example

Monday, September 19, 2022

Java is a Strongly Typed Language

One thing about Java which you should know before you dig any deeper is that Java is a strongly typed language. What it means is that every variable must be declared with a proper type before those variables can be used.

<type> <variable>;

Here type may be a primitive data type or a non-primitive data type (user defined type i.e. a class).

Here are some examples of variable declaration using primitive types

int x;
float f;

Here are some examples of variable declaration using non-primitive types (some class)

Employee e;
ArrayList numList;
Scanner sc;

But that is not all that makes Java strongly typed, each assignment and parameter passing to the method is checked for type compatibility.

For example, a variable once declared as int can only be assigned an Integer value.

int x = 5; // correct assignment is compatible to variable type
x = 10;  // correct new assignment is compatible to variable type
x = 10.92; // error trying to assign decimal value to an int type variable
x = "test"; // error trying to assign String value to an int type variable

Same way for classes where assignment is a bit different because you actually create an object of the class but still it has to be of compatible type.

Employee emp = new Employee();

Refer Class in Java for more clarity on how class is created and how object of a class is defined.

Same way as an example let's say you have a method sum in a class as defined below

public class Test {

	public static void main(String[] args) {
		Test t = new Test();
		t.sum(5.6, 6.7);
		t.sum("a", "b"); // Error trying to pass parameters of incompatible type
		t.sum(4, 5);
	}
	
	public void sum(double a, double b){
		double r = a + b;
		System.out.println("Sum is- " + r);
	}
}

As you can see method sum takes two arguments of type double so first call to the method is correct but second call where two parameters of type String are passed results in an error.

You may wonder why third call where two parameters of type int are passed works? That is because both int and double are ultimately numbers and there is something called widening type conversion which takes care of this parameter passing.

Refer Type Casting in Java With Conversion Examples to know more about type conversion in Java.

Advantages of strongly typed language

One of the main advantages of strongly typed language is having strict type checking at the compile time itself. So that at run time you don't have exceptions thrown for incompatible types.

Java 10 introduced a new feature called local variable type inference where the type of the variable is inferred from the variable initializer. A new reserved type name "var" is added in Java to define and initialize local variables, read more about var type here- Var type in Java - Local Variable Type Inference

That's all for this topic Java is a Strongly Typed Language. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java Pass by Value or Pass by Reference
  2. Java Automatic Numeric Type Promotion
  3. Why Class Name And File Name Should be Same in Java
  4. Why main Method static in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Object Creation Using new Operator in Java
  2. super Keyword in Java With Examples
  3. Difference Between Abstract Class And Interface in Java
  4. Check Given Strings Anagram or Not Java Program
  5. ArrayList in Java With Examples
  6. Spring Java Configuration Example Using @Configuration
  7. Angular First App - Hello world Example
  8. Python continue Statement With Examples

Sunday, July 17, 2022

Type Wrapper Classes in Java

As explained in the post primitive data types in Java there are eight primitive data types and most of the time you will use the primitive types in your code as it reduces the object creation overhead making it more efficient to use primitive types. But there are scenarios when you would want to use objects in place of primitives for that Java platform provides wrapper classes for each of the 8 primitive data types. These classes "wrap" the primitive in an object thus the name wrapper classes. Note that all the wrapper classes in Java are immutable.

Java Wrapper Classes

Eight wrapper classes used to wrap primitive data types are as given below-

Primitive TypeType Wrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

Note that 6 of these are numeric and numeric wrapper classes are subclasses of the abstract class Number class in Java:

Wrapper classes in Java

When do we need wrapper classes in Java

You need to use wrapper classes when you want an object holding primitive data, some of the scenarios where you will need wrapper classes are–

  1. You want to add primitive value in an Object[] array.
  2. You want to add primitive type to any collection like ArrayList, HashMap as you can add only objects to collection classes.
  3. You want to use any of the utility function provided by the wrapper classes for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Java Wrapper classes examples

  1. If you want to convert int to a float number.

    In Integer class there is a floatValue() method that can be used for the purpose.

    int num = 25;
    Integer i = new Integer(num);
    float fNum = i.floatValue();
    System.out.println("float Value " + fNum);
  2. If you want to convert double value to a string.
    double d = 25.67;
    String str = Double.toString(d);
    System.out.println("string " + str);
    
  3. If you want to know the min and max range of any type, like for integer
    System.out.println("Integer min value " + Integer.MIN_VALUE);
    System.out.println("Integer max value " + Integer.MAX_VALUE);
    

    Output

    Integer min value -2147483648
    Integer max value 2147483647
    

    For double

    System.out.println("Double min value " + Double.MIN_VALUE);
    System.out.println("Double max value " + Double.MAX_VALUE);
    

    Output

    Double min value 4.9E-324
    Double max value 1.7976931348623157E308
    

Autoboxing and unboxing

Here autoboxing and unboxing in Java should get an honorable mention; autoboxing and unboxing feature was added in Java 5 and it converts primitive into object and object into primitive automatically. In many cases now you don’t need to convert using utility methods as it will happen automatically.

As example you can directly assign int value to an Integer object–

Integer i = 25;

Now conversion and method call (valueOf()) in this case will be done by compiler.

Equivalent code if you were converting yourself–
int num = 25;
Integer i = Integer.valueOf(num);

That's all for this topic Type Wrapper Classes in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Primitive Data Types in Java
  2. Object Creation Using new Operator in Java
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. Convert String to float in Java
  5. Convert int to String in Java

You may also like-

  1. Type Casting in Java With Conversion Examples
  2. static Reference to The Non-static Method or Field Error
  3. Constructor Overloading in Java
  4. Java Exception Handling And Method Overriding
  5. How HashMap Works Internally in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Factorial Program in Java
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Monday, July 4, 2022

continue Statement in Java With Examples

When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue statement and break statement. In this tutorial you’ll learn about Java continue statement along with usage examples.

When to use continue statement in Java

During the repeated execution of the loop if you don’t want to execute statements with in the loop body for some particular condition you can force the next iteration of the loop using continue statement.

If there is a continue statement in a loop statements after the continue are not executed and control jumps to the beginning of the loop.

If continue statement is there in while loop or do-while loop control transfers to the condition of the loop.

In case of for loop, continue statement causes the control to transfer to the iteration part first and then to condition part.

Continue statement Java examples

1- Using continue statement with while loop. In the example you want the user to enter an even number when such a number is entered then only control comes out of the loop otherwise loop continues.

public class ContinueJava {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int number;
    while(true){
      System.out.print("Enter a number: ");
      number = scanner.nextInt();
      // checking entered number even or not
      if(number%2 != 0) {
        System.out.println("Please enter even number...");
        continue;
      }else {
        break;
      }
    }
    scanner.close();
    System.out.print("Entered number is- " + number);
  }
}

Output

Enter a number: 5
Please enter even number...
Enter a number: 7
Please enter even number...
Enter a number: 8
Entered number is- 8

2- Using continue statement in for loop.

public class ContinueJava {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++) {
      if (i == 1)
        continue;
      System.out.println(i);
    }
  }
}

Output

0
2
3
4

As you can see when value of i is 1 continue statement is encountered so the statement after the continue statement is not executed and the control transfers to the beginning of the loop for next iteration.

3- Using continue statement in do-while loop. In the example odd numbers between 1..10 are displayed using do-while loop.

public class ContinueJava {
  public static void main(String[] args) {
    int i = 1;
    do {
      // check if even number
      if(i%2 == 0)
        continue;
      System.out.println(i);
    }while(++i < 10);
  }
}

Output

1
3
5
7
9

Labelled continue statement in Java

Just like labeled break statement there is also a labeled continue statement to let you decide which loop to continue.

Labelled continue statement Java example

In the example a pattern (triangle) is displayed using labeled continue statement.

public class ContinueJava {
  public static void main(String[] args) {
    outer:
    for (int i = 0; i < 6; i++) {
      for(int j = 0; j < 6; j++) {
        if(j > i) {
          System.out.println();
          continue outer;
        }
        System.out.print("*");
      }
    }
  }
}

Output

*
**
***
****
*****
******

In the example whenever value of j is greater than i control is transferred to the outer for loop for next iteration.

That's all for this topic continue Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java With Examples
  2. Java Variable Types With Examples
  3. super Keyword in Java With Examples
  4. Access Modifiers in Java - Public, Private, Protected and Default
  5. Java Abstract Class and Abstract Method

You may also like-

  1. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  2. Method Overloading in Java
  3. Linear Search (Sequential Search) Java Program
  4. Bubble Sort Program in Java
  5. HashMap in Java With Examples
  6. Difference Between Thread And Process in Java
  7. pass Statement in Python
  8. Spring Component Scan Example

Saturday, July 2, 2022

return Statement in Java With Examples

In previous tutorials we have already seen continue statement which is used to continue the iteration of a loop and break statement which is used to break out of a loop, in this post we’ll learn about return statement in Java which is used to explicitly return from a method.

Java return statement

When a return statement is encountered in a method that method’s execution is terminated and control transfers to the calling method. A return statement may or may not return a value to the calling method.

Rules for using Java return statement

  1. If no value is returned from the method then the method signature should signify it by having void in method signature. For example- void methodA()
  2. If a method is not returning any value i.e. its a void method then having return statement in that method is not mandatory. Though an empty return can still be there which can be used as a control statement to terminate execution of the method for given condition.
  3. If a method is returning a value then return type should be signified in the method signature. For example a method that returns int should have it in its method signature- int methodA()
  4. The return type of the method and actual value returned should be compatible.

Java return keyword example

1- A method returning int value.

public class ReturnExample {

 public static void main(String[] args) {
  ReturnExample obj = new ReturnExample();
  int sum = obj.add(6,  7);
  System.out.println("Sum is- " + sum);
 }
 
 int add(int a, int b) {
  int sum = a + b;
  return sum;
 }
}

Output

Sum is- 13

2- A void method with return statement as a control statement to terminate method execution when the condition is satisfied.

public class ReturnExample {
  public static void main(String[] args) {
    ReturnExample obj = new ReturnExample();
    obj.display();
    System.out.println("After method call...");
  }
    
  void display() {
    for(int i = 1; i <= 10; i++) {
      // method execution terminates when this 
      //condition is true
      if (i > 5)
        return;
      System.out.println(i);
    }
  }
}

Output

1
2
3
4
5
After method call...

In the example, there is a for loop in method with a condition to return from the method. When the condition is true, method execution is terminated and the control returns to the calling method.

One point to note here is that in a method return statement should be the last statement or it should be with in a condition. Since method execution terminates as soon as return statement is encountered so having any statements after return results in “Unreachable code” error.

public class ReturnExample {

 public static void main(String[] args) {
  ReturnExample obj = new ReturnExample();
  obj.display();
  System.out.println("After method call...");
 }
 
 void display() {
  int i;
  return;
  i++; // error
 }
}

In the example there is code after the return statement which is never going to be executed thus the “Unreachable code” compile time error.

That's all for this topic return Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java do-while Loop With Examples
  2. Conditional Operators in Java
  3. Why Class Name And File Name Should be Same in Java
  4. Object Creation Using new Operator in Java
  5. Literals in Java

You may also like-

  1. Method Overriding in Java
  2. Interface in Java With Examples
  3. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  4. try-catch Block in Java Exception Handling
  5. Split a String in Java Example Programs
  6. Java Program to Reverse a Number
  7. Serialization and Deserialization in Java
  8. Nested Class And Inner Class in Java

Friday, June 24, 2022

break Statement in Java With Examples

When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue statement and break statement. In this tutorial you’ll learn about Java break statement along with usage examples.

Where do you use break statement in Java

break statement in Java can be used in following scenarios-

  1. For terminating a loop– If there is a break statement with in a for loop, while loop or do-while loop the loop is terminated and the control moves to the statement immediately following the loop.
  2. For terminating switch statement– In Java switch statement if a case is followed by a break statement then the switch statement is terminated. For usage of break statement with switch statement in Java refer this post- Switch-Case Statement in Java
  3. Using labeled break statement– You can use labeled break statement to exit out of a labelled block.

break statement Java examples

1- Using break statement to break out of a for loop. In the example a list of cities is iterated and searched for a specific city. If the city is found loop is terminated using a break statement.

public class BreakJava {
  public static void main(String[] args) {
    List<String> cities = Arrays.asList("Beijing", "London", "Santiago", "St. Petersburg", "Helsinki");
    for(String city : cities) {
      if(city.equals("Santiago")) {
        System.out.println("Found city - " + city);
        // terminate loop
        break;
      }                
    }
    System.out.println("Out of for loop");
  }
}

Output

Found city - Santiago
Out of for loop

2- Using break statement to terminate an infinite while loop.

public class BreakJava {
  public static void main(String[] args) {
    int i = 1;
    while(true){
      // terminate loop when i is greater than 5
      //display i's value otherwise
      if(i > 5)
        break;
      System.out.println("i- " + i);
      i++;
    }
  }
}

Output

i- 1
i- 2
i- 3
i- 4
i- 5

3- When break statement is used with nested loops, break statement terminates the innermost loop in whose scope break is used.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 3; i++){
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
        // terminate inner loop
        if(j == 6)
          break;
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- *******
2- *******
3- *******
Out of loop

Here break statement is used in the scope of outer loop so outer for loop is terminated.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 6; i++){
      if(i == 4)
        break;
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- **********
2- **********
3- **********
Out of loop

4- With unlabeled break statement you can come out of the innermost loop. If you want to come out of a deeply nested loop you can use labeled break statement which helps in coming out of more than one blocks of statements.

For example in the following code two for loops are there and labeled break statement helps in coming out of both the loops.

public class BreakJava {

  public static void main(String[] args) {
    int[][] array = { 
      {1, 2, 3 },
      {4, 5, 6 },
      {7, 8, 9 }
    };
    int searchedNum = 5;
    boolean flag = false;
    int i = 0, j = 0;
    // label
    outer:
    for (i = 0; i < array.length; i++) {
      for (j = 0; j < array[i].length; j++) {
        if (array[i][j] == searchedNum) {
          flag = true;
          // lebeled break
          break outer;
        }
      }
    }
    if(flag) {
      System.out.println("Found element " + searchedNum + " at index " + i + " and " + j );
    }else {
      System.out.println("Element " + searchedNum + " not found in the array" );
    }
  }
}

Output

Found element 5 at index 1 and 1

That's all for this topic break Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. if else Statement in Java With Examples
  2. Arithmetic And Unary Operators in Java
  3. this Keyword in Java With Examples
  4. Constructor in Java
  5. Java Abstract Class and Abstract Method

You may also like-

  1. BigInteger in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Map.Entry Interface in Java
  4. Deadlock in Java Multi-Threading
  5. Selection Sort Program in Java
  6. How to Display Pyramid Patterns in Java - Part1
  7. Python First Program - Hello World
  8. How MapReduce Works in Hadoop

Saturday, June 18, 2022

if else Statement in Java With Examples

To control the execution flow Java programming language provides two types of conditional statements if-else and switch-case statement. In this post we'll talk about Java if and if-else statements in detail along with usage examples.

if-else statement in Java

The Java if statement is used to test a condition and take the execution path based on whether the condition is true or false. There are many combinations in which if statement can be used in Java.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

if statement in Java

Syntax of the Java if statement is as follows-

if(condition){
  //statement(s)
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then the block of code enclosed in curly braces is executed. If the condition evaluates to false then the if block is skipped.

If there is only a single statement with in the if condition then the curly braces are optional.

Java if statement flow

if condition java

Java if statement examples

1- Testing a condition to check if passed number is greater than 5 or not.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    if(i > 5) {
      System.out.println("Value of i is greater than 5");
    }
    System.out.println("After if statement");
  }
}

Output

Value of i is greater than 5
After if statement

2- You can also use conditional operators like Conditional-AND (&&) and Conditional-OR (||) to create a condition.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 5 && test.equals("Hello"))
      System.out.println("Inside if");
    System.out.println("After if statement");
  }
}

Output

Inside if
After if statement

Java if-else statement

Syntax of the Java if-else statement is as follows-

if(condition){
  // if block
}else{
  // else block
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then if block is executed. If the condition evaluates to false then the else block is executed.

Java if-else statement flow

if else Java

Java if-else statement examples

public class IfDemo {

  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 20 && test.equals("Hello")) {
      System.out.println("Inside if");
    }else {
      System.out.println("Inside else");
    }
    System.out.println("After if-else statement");
  }
}

Output

Inside else
After if-else statement

In the example condition fails therefore else block is executed.

Java if-else-if ladder

You can also have an if statement followed by one or more else-if statements and an optional else statement at the end. Each if and else-if statement has a condition and a particular block is executed if the condition associated with that block evaluates to true. If none of the conditions evaluate to true then the else block (if present) is executed.

Syntax of Java if-else-if syntax is as follows-

if(condition1){
  statement(s);
}else if(condition2){
  statement(s);
}else if(condition3){
  statement(s);
}
.
.
.
else{
  statement(s);
}

Java if-else-if examples

Suppose you have requirement to add 10% to amount if amount is greater than 5000.
Add 15% if amount is more than 3000 but less than or equal to 5000.
Add 20% if amount is more than 1000 but less than or equal to 3000.
Otherwise add 25% to the amount.

public class IfDemo {
  public static void main(String[] args) {
    int amount = 5000;
    if(amount > 5000) {
      // add 10%
      amount = amount + (amount*10/100);
    }else if (amount > 3000 && amount <= 5000) {
      // add 15%
      amount = amount + (amount*15/100);
    }else if (amount > 1000 && amount <= 3000) {
      // add 20%
      amount = amount + (amount*20/100);
    }else {
      //add 25%
      amount = amount + (amount*25/100);
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 5750

Java nested if-else statements

It is possible to have an if-else statement inside a if-else statement in Java. It is known as a nested if-else statement.

public class IfDemo {

  public static void main(String[] args) {
    int amount = 8000;
    if(amount > 5000) {
      if(amount > 7000 && amount <=10000) {
        amount = amount + (amount*10/100);
      }else {
        amount = amount + (amount*5/100);
      }    
    }else {
      if (amount > 3000 && amount <= 5000) {
        amount = amount + (amount*15/100);
      }else {
        amount = amount + (amount*20/100);
      }
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 8800

That's all for this topic if-else Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java for Loop With Examples
  2. Equality And Relational Operators in Java
  3. String in Java Tutorial
  4. static Block in Java
  5. Marker Interface in Java

You may also like-

  1. finally Block in Java Exception Handling
  2. BigDecimal in Java With Examples
  3. How to Loop or Iterate an Arraylist in Java
  4. Java Collections Interview Questions And Answers
  5. Producer-Consumer Java Program Using ArrayBlockingQueue
  6. How to Convert String to Date in Java
  7. Operator Overloading in Python
  8. Data Access in Spring Framework