Friday, January 29, 2021

Switch case java | Java Switch Statement-AapKiApniSchool

In this blog we will learn switch case java in details. We will discuss Java Switch Multiple Case. We will check java switch syntax,use of default case,how do exit switch case and create nested switch statement in java in details..

Table Of Content:

 1. switch case in java/java switch

2. java switch enum

3. java switch string

4.Is switch case faster than if else Java?

5. Can we use float in switch case in Java?

6. Does a switch statement need a default Java?

7. Can we create a nested switch statement in Java?

8.How do you exit a switch in Java?

9.Java Wrapper in Switch Statement

 

Switch case in java/java switch:

Switch case is like if-else-if statement. Switch case java execute one statement from multiple conditions.We can give expression of these type byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short. From Java 7 it accept String also.

 

Key Points:

  • Case value must be unique otherwise java compiler throw error.
  • The case value must be literal or constant. It doesn't allow variables.
  • Switch case type must be byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short types.
  • Switch case can have default case that is used if no case found.It is optional.
  • After each case we can put break keyword but it is optional.

 

 

Syntax:

switch(expression){ 
case value1: 
//code to be executed; 
break; //optional 
case value2: 
//code to be executed; 
break; //optional 
case value3:
break; 
...... 

default: 
code to be executed if all cases are not matched; 
}

 

 

Sample Code Without Break Keyword: 

Java Switch case execute all the statement after first match if break keyword not available.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="red";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
 
case "green":System.out.println("This is Green color.");
 
case "blue":System.out.println("This is Blue color.");
 
default:System.out.println("This is default color.");
}
 
}
 
}
 

OutPut:

 
This is Red color.
This is Green color.
This is Blue color.
This is default color.
 

Sample Code With Break Keyword:

It execute that particular case if break keyword is available.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="red";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
break;
 
case "green":System.out.println("This is Green color.");
break;
case "blue":System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
 
}
 

Output:

 
This is Red color.
 

Is switch case faster than if else Java?

Switch case is faster for multiple choice and complex conditions. Switch Case also increase readability. If Switch acse are very less than it will not impact performance. In that situation we can use if-else also.

Can we use float in switch case in Java?:

We can't use float in switch case. We will get complie time error if we try to use float in switch case.

Does a switch statement need a default Java?/Default Case Executions: 

Default case is optional in java switch case.Default case will be executed if switch expression value is not matching to any case.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="yellow";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
break;
 
case "green":System.out.println("This is Green color.");
break;
case "blue":System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
 
}
 

Output:

 
This is default color.
 

Java Enum in Switch Case/Java switch enum:

 In java switch case we can use Enum also.

 
package youtubeClass;
 
public class Test {
 
 public enum Colors { red,blue }
public static void main(String[] args) {
 
Colors[] colors = Colors.values();   
for(Colors color:colors) {
 
switch(color)
{
case red:System.out.println("This is Red color.");
break;
case blue:System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
}
}
 
 

Output:

 
This is Red color.
This is Blue color.
 

Java switch string: 

From Java 5 we can use String in Switch Case.

 

package youtubeClass;

public class SwitchCase {

public static void main(String[] args) {

String name="anil";

switch(name)
{
case "sunil":
System.out.println("My Full name is Sunil Sharma");
break;

case "anil":
System.out.println("My Full name is Anil Sharma");
break;
}

}

}

Output:

My Full name is Anil Sharma

Can we create a nested switch statement in Java?

Yes we ca create nested switch statement in java.

package youtubeClass;

public class SwitchCase {

public static void main(String[] args) {

int x=1,y=3;

switch(x)
{
case 1:
switch(y)
{
case 3:
System.out.println("Value is 3");
break;
}
break;
case 2:
System.out.println("Value is 2");
}

}

}


Java Wrapper in Switch Statement: 

 
We can use wrapper classes in Switch statement.
 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
Integer age = 18;
 
switch(age)
{
case 17:System.out.println("Sorry you are not eligable for DL.");
break;
case 18:System.out.println("you are eligable for DL.");
break;
default:System.out.println("Please provide valid age.");
}
 
}
}
 
 

Output:

you are eligable for DL.

Tuesday, January 26, 2021

Java list | Arraylist in java | Java ArrayList-AapKiApniSchool

 In this blog we will learn Java List and ArrayList in Java. Different Different type of List and Commonly used methods.


Java list | Arraylist in java


List: List is an interface in java that's implementation is given by ArrayList,LinkedList,Stack and Vector. List extends Collection interface.

Synatx for instantiate the List interface.

List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

Collection Interface Main Methods:

public boolean add(E e)
public boolean addAll(Collection<? extends E> c)
public boolean remove(Object element)
public boolean removeAll(Collection<?> c)
default boolean removeIf(Predicate<? super E> filter)
public void clear()
public int size()
public Object[] toArray()
default Stream<E> stream()

ArrayList:

ArrayList implements List interface in java. It is a Array with dynamic size. It main inseration order and it is not thread safe. The elements stored in the ArrayList class can be randomly accessed. It can store duplicate data.


package com.mkyong;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new ArrayList<>();
list.add("Sunil");
list.add("anil");
list.add("Narendra");
System.out.println("List "+list);

}

}




arraylist




LinkedList: 

LinkedList implements List interface. It don't maintain insertion order. It can store duplicate data. We can't access random data from LinkedList.It is not thread safe. Adding new element in Linkedlist is fast as compare to ArrayList.It maintain the inseration order. Internally it use LinkedList for storing data.


package com.mkyong;

import java.util.LinkedList;
import java.util.List;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new LinkedList<>();
list.add("Sunil");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}



LinkedList



Vector: 

Vector is similar to ArrayList but it is thread safe. Vector also internally use dynamic array.


package com.mkyong;


import java.util.List;
import java.util.Vector;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new Vector<>();
list.add("Sunil1");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}


Stack:

Stack is a sub class of Vector. It contain all the methods of Vector and some additional methods like push,peek and pop. Push is used to insert data.Pop is used to remove data. Stack use First-In Last-Out DataStructure.


package com.mkyong;


import java.util.List;
import java.util.Stack;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new Stack<>();
list.add("Sunil1");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}



package com.mkyong;
import java.util.Stack;

public class ListDemo {

public static void main(String[] args) {
Stack<String> list= new Stack<>();
list.push("Sunil1");
list.push("anil");
list.push("Narendra");
list.push("Sunil");
System.out.println("List "+list);
list.pop();
System.out.println("List "+list);

}

}




Monday, January 25, 2021

Java object to xml | JAXB marshalling - convert java object to xml | Convert java object to xml in java

 In this blog we will discuss Java Object to xml.JAXB marshalling - convert java object to xml. Also we will check how to convert Java objet to xml file.


Java object to xml | JAXB marshalling - convert java object to xml | c


Maven Dependency:

<!-- https://mvnrepository.com/artifact/javax.xml/jaxb-api -->
<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.0</version>
</dependency>


Spring Boot Dependency:

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

Program for Converting Java Object to xml String:


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ConvertJavaObjectToXml {

public static void main(String[] args) {
Person person= new Person("Sunil",24,"India");
try {
JAXBContext contextObj = JAXBContext.newInstance(Person.class);
Marshaller marshallerObj = contextObj.createMarshaller(); 
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshallerObj.marshal(que, new FileOutputStream("question.xml"));
 
StringWriter sw = new StringWriter();
 
marshallerObj.marshal(person,sw);
 
String xmlString=sw.toString();
 
System.out.println("xmlString "+xmlString);
 
marshallerObj.marshal(person, new FileOutputStream("person.xml"));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  

}


package com.mkyong;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {

private String name;
//@XmlElement
private int age;
//@XmlElement
private String address;
public Person() {
super();
// TODO Auto-generated constructor stub
}

public Person(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
@XmlElement
public void setAddress(String address) {
this.address = address;
}
}



Program for Converting Java Object to Xml File



import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ConvertJavaObjectToXml {

public static void main(String[] args) {
Person person= new Person("Sunil",24,"India");
try {
JAXBContext contextObj = JAXBContext.newInstance(Person.class);
Marshaller marshallerObj = contextObj.createMarshaller();

//This line is used to format xml file
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 
StringWriter sw = new StringWriter();
 
marshallerObj.marshal(person,sw);
 
 
marshallerObj.marshal(person, new FileOutputStream("person.xml"));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  

}

}


Note: your xml willbe stored in same location where your project existing.

Saturday, January 23, 2021

Java if else | Ternary operator java | Conditional operator in java-AapKiApniSchool

 In this blog i will explain you how to use java if else. We will change if else to ternary opertaor java.


Java if else | Ternary operator java | Conditional operator in java | Conditional statements in java


Java if else is used to check boolean condition true or false. There are diffent types of if else statements

1. if statement
2. if else statement
3. nested if else
4. if else if


Java if Statement:

Java if statement execute if the given condition is true.

Syntax:

if(condition)
{
code will be executed
}

Java if else statement:

In Java if else statement code written inside if block will be executed if given condition is true.Otherwise else block code will be executed.

if(Condition)
{
 //This code will be executed if condition is true
}
else{
  //This code will be executed if condition is false
}


Java nested if else:


In Java nested if else will be executed if outer if condition is true.

if(condition)
{
   if(Condition)
{
   //This code will be executed if outer and inner conditions are true.

}
else{
 //This code will be executed if outer if condition is true aand inner conditions is false.
}
}
else{

}


Java if-else-if:

In Java if else if statement first if condition is checked if first if condition is false then else if condition will be checked if else if condition is true then else if block will be executed otherwise else block will be executed.

if(Condition1)
{}
else if(Condition2)
{}
else{
}


Ternary operator java:

We can convert if else statement to ternary operator statement.

if else statement:

if(2<5)
{
  return true;
}
else{
 return false;
}

Ternary Operator:

boolean x=2<5?true:false;

Operators in java-AapKiApniSchool

 In this blog we will discuss what is Operators in Java?What is the types of Operators in Java?


Operators in java:

Operators is nothing, it is just a symbol that is used to perform operations. Like +,-,* etc.


Types Of Operators:





Operators

Symbol

Unary Operator

exp++,exp--,--exp,++exp

Arithmetic Operator

* / % + -

Shift Operator

<< >> >>>

Relational Operator

< > <= >= instanceof,!=

Bitwise Operator

&,|,^

Logical Operator

&&,||,

Ternary Operator

? :

Assignment Operator

=,+=,-=,*= 





Java Unary Operator:

Java Unary need only one operand.It is used to increment or decrement value of Operand by 1.


class UnaryOperatorExample{
public static void main(String args[]){
int x=11; 
System.out.println(x++);//11 (12)
System.out.println(++x);//13
System.out.println(x--);//13 (12) 
System.out.println(--x);//11 
}}


Java Arithmetic Operators:

Java Arithmetic operatores are used to perform Maths operations like addition,Sub,Multiply,Modules and Divison.


class  ArithmeticsOperatorExample{
public static void main(String args[]){
int a=10;
int b=2; 

System.out.println(a/b);//5 
System.out.println(a%b);//0  
System.out.println(a+b);//12
System.out.println(a-b);//8
System.out.println(a*b);//20
}}

Java Shift Operator:

 

Java Left Shift Operator: The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.



class LeftShiftOperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Java Right Shift Operator: The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right operand.



class RightShiftOperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}


Java AND Operator Example: Logical && and Bitwise &:

Main differnce between logical && and Bitwise & is Bitwise & will check all conditions but logical && will check 2nd condition if 1st condition is true otherwise it will not be checked.


class AndOperatorExample{
public static void main(String args[]){
int x=10;
int y=5;
int z=20;
System.out.println(x<y&&x<z);//false && true = false
System.out.println(x<y&x<z);//false & true = false
}}

Java OR Operator Example: Logical || and Bitwise |:

Main difference between logical || and Bitwise | is that Bitwise will check all the condition if 1st condition is true or false but logical || will check 2nd condition if 1st is true otherwise it will not be checked.


class OrOperatorExample{
public static void main(String args[]){
int x=15;
int y=10;
int z=30;
System.out.println(x>y||x<z);//true || true = true
System.out.println(x>y|x<z);//true | true = true
}
}


Java Ternary Operator:

Java Ternary operator is one line replacement of If-Else. It contains 3 operands. It is very important for java as it is used a lot in java.


class TernaryOperatorExample{
public static void main(String args[]){
int x=5;
int y=8;
int min=(a<b)?a:b; //5
System.out.println(min);
}}

Syntax: condition?(returned if condition is true):(returned if condition is false);

Java Assignment Operator:

Assignment operator is most commonly used operator. It is used to assign value to variable.

int a=10;

value 10 is assigned to variable a that is type of Integer.


Java variables | Class variable in java | Types of variables in java-AapKiApniSchool

 In this blog we will discuss What is Java Variable?How to use Java Variables?Types of variables in java in details.


Java variables | Class variable in java | Types of variables in java


VariableImg

What is Java Variables?

Java variable is a tempory mempry where we can store values. Name of that variable is the reference of that memory area. With the help of reference we access the vales of that variable.

int x=10;

int: int is type. Type is mentioning which type of data we can store. In above given example we can store only Integer value,not other than Integer.
x: This is the variable name.
10: This is the value that stored in memory for temporay purpose.


Global Variable: 

Global variable is a variable that is declared on place and it is accessible in entire code. But Java is a object oriented language where everything is Class. We can declare variables on class name like static or instance variable.

Types of variables in java

Java Variables are three types:
 1. Local Variables
 2. Static Variables
 3. Instance Variables


variabletypes


 Local Variables:

Local variables are the variables which are defined inside any method or block. It is accessible only in that block or method. We can't define static variable inside method.

Static Variables:

Static variables are those variables which is defined on class level with static keyword. These variable can be access by class name. Static variable defined only once for all objects. It consume memory only once.It doesn't matter hoe many objects we are creating. As this is common for all object if any object change vale of this variable then it will impact all objects.

Instance Variables:

A variable declared inside class and outside method is called Instance Variable. Instance variable belongs from Object. It can be access by Object. For each object instance variables take different different memory. If one object change value of varaibles then it will not impact other objects.



Program for Types of Variables:



class Test{
int x=50;//instance variable
static int y=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class


Friday, January 22, 2021

Difference between JDK, JRE, and JVM-AapKiApniSchool

 In this blog we will dicsuss "difference between jdk and jre". I will explain you what is the use of jdk jre jvm in details.



JDkJREJVMImage


JavaCodeFlow




JDK(Java Development Kit):

JDK is used to develop Java applications. It contain JRE and Other development tool Like JAVAC,interpreter/loader (Java).It take Source Code and compile the code. After compilation it convert the java source code into byte code which also known for .class file.

JRE(JAVA Runtime Environment):

JRE is used to run the java program. It can JVM and other library which required for running Java Program. JRE take byte code and convert into  machine language that is also known for binary code.
It physically exist.

JVM(Java Virtual Machine):

JVM is a specifications. It is like Interface where we define our rules. It's implementation is given by JRE.Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line hence it is also known as interpreter.JVM physically doesn't exist.

Hello world program in java-AapKiApniSchool

In this blog i will explain you. How to write Hello World Program in java? I will explain you in details the flow of Hello World Program in Java? I will explain you each keyword use for this program.


How do you code in Java? | How do you write Hello World in Java? | What is a Hello World program in Java?|what is the command used to retrieve the java files along with the hello world in it?


How to create Java Project?

Open ECLIPSE-> Go To File-> Click on 'New'->Select 'Java Project' (If Java Project is not showing then click on Others and search Java Project)-> Provide Project Name ->Click on Finish.


OpenFileForJavaProject


CreateJavaProject


ProjectNameGiven


How to create Class?

Go to the project which is created now->Src->Right Click on Src->Click on New ->Click on Class->Give Class Name -> Select Public Static Check Box->Click On Finish.



CreateClass


ClassName


How do you code in Java? | How do you write Hello World in Java? | What is a Hello World program in Java?

public class HelloWorldTest {

public static void main(String[] args) {

System.out.println("Hello World");

}

}


Explanation Of Java Code:

public-> It is a modifier those scope is everywhere. In same package,different package etc.
static-> static is keyword in Java. When we using static keyword then without any object we can access that method or variable.
main-> This is the main method of Java from where java program run.
System.out.println-> It is a method in Java which is used to print message on console.    



Monday, January 18, 2021

Java Tutorial | Learn Java Programming-AapKiApniSchool

Contents: 

1. What is Java?

2. Use of Java?

3. Advantage of Java?

4. Why Java is popular?


1.  Java is a programming language which is created by Sun Micro system. It is the most popular language for software development. 

Almost 3billions devices using java. Currently is owned by Oracle Company.


2. Uses Of Java:

  • Web Developemnt
  • Desktop application
  • Enterprise Applications like Banking applications,irctc
  • Mobile applications
  • Games Development


3. Advantages of Java:

  • Platform Independent
  • Object Oriented Programming Language
  • Simple it does not have complex features like pointers, operator overloading, Multiple inheritance, Explicit memory allocation. 
  • Secure
  • It is open-source and free
  • It is secure, fast and powerful
  • It has a huge community support 
4. Java is so popular as write one program and run on any platform. Suppose we are writing program on Window and we want to run on Mac or Linux then we can run without any changes but in previous language like C,C++ if you write program on Window then it will run only on Window.For Linkux and Mac again you have to write program.


Thursday, January 14, 2021

Java Interview Questions (2021) - AapKiApniSchool

 Top 10 Core Java Interview Questions:


1. Write a program for singleton class in java.

2. Write a program in java for printing 1-10 numbers without loop.

3. What is the difference between jdk and jre in java.

4. Difference between String and String builder in java.

5. Difference between String builder and String buffer.

6. What is the use of final keyword in java?

7. What is the use of this keyword in java?

8. What is the use of static keyword in java?

9. Why main method is static in java?

10. Can we create main method without static keyword?


Note: Please let me know in comment box if you need answers for these questions.

Featured Post

Interface in java-AapKiApniSchool

Interface in java:  interface is a blueprint of class in java that is used to define contracts. It can contain static constant and abstract ...

Popular Posts