SlideShare a Scribd company logo
1 of 53
JAVA PROGRAMS
Display message on computer screen.
class First
{
public static void main(String args[])
{
System.out.println("Let's do something using
Java technology.");
}
}
OUTPUT
Print integers
class Integers
{
public static void main(String[] arguments)
{
int c; //declaring a variable /* Using for loop to repeat
instruction execution */
for (c = 1; c <= 10; c++)
{
System.out.println(c);
}
}
}
Output
If else control instructions:
class Condition
{
public static void main(String[] args)
{
boolean learning = true;
if (learning)
{
System.out.println("Java programmer");
}
Else
{ System.out.println("What are you doing here?");
}
}
}
OUTPUT
Command line arguments:
class Arguments
{
public static void main(String args[])
{
for (String t: args)
{
System.out.println(t);
}
}
}
output
Java if else program
import java.util.Scanner;
class IfElse
{
public static void main(String args[])
{
int marksObtained, passingMarks;
passingMarks = 40;
Scanner input = new Scanner(System.in);
System.out.println("Input marks scored by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks)
{
System.out.println("You passed the exam.");
}
else { System.out.println("Unfortunately, you failed to pass the exam.");
}
}
}
OUTPUT
Nested If Else statements
import java.util.Scanner;
class NestedIfElse
{
public static void main(String args[])
{
int marksObtained, passingMarks;
char grade;
passingMarks = 40;
Scanner input = new Scanner(System.in);
System.out.println("Input marks scored by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks)
{
if (marksObtained > 90) grade = 'A';
else if (marksObtained > 75) grade = 'B';
else if (marksObtained > 60)
grade = 'C';
else grade = 'D';
System.out.println("You passed the exam and your grade is " +
grade);
}
else
{
grade = 'F'; System.out.println("You failed and your grade
is " + grade);
}
}
}
Infinite for loop
for ( ; ; )
{
System.out.println("Java programming");
}
Simple for loop example in Java
class ForLoop
{
public static void main(String args[])
{
int c;
for (c = 1; c <= 10; c++)
{
System.out.println(c);
}
}
}
Java while loop example
import java.util.Scanner;
class WhileLoop
{
public static void main(String args [])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0)
{
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
}
Java program to print multiplication
table
import java.util.Scanner;
class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer to print it's multiplication
table");
Scanner in = new Scanner(System.in);
n = in.nextInt(); System.out.println("Multiplication table of " + n + " is : ");
for (c = 1; c <= 10; c++)
System.out.println(n + "*" + c + " = " + (n*c));
}
}
• A constructor in Java is a method which is
used used to initialize objects.
• Constructor method of a class has the same
name as that of the class,
• Constructor can't be called explicitly
Constructor
class Programming
{
Programming()
{
System.out.println("Constructor method called.");
}
public static void main(String[] args)
{
Programming object = new Programming();
}
}
Creating class and object
public class Puppy
{
public Puppy(String name)
{
System.out.println("Passed Name is :" + name );
}
public static void main(String args[])
{
myPuppy = new Puppy( "tommy" );
}
}
Types of java constructors
• There are two types of constructors in java:
• 1.Default constructor (no-arg constructor)
• 2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it
doesn't have any parameter.
Example of default constructor
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
OUTPUT
Bike is created
Example of default constructor that
displays the default values
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
OUTPUT
0 null
0 null
parameterized constructor
• Parameterized constructor is used to provide different values to the distinct objects.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Java - Methods
• A Java method is a collection of statements
that are grouped together to perform an
operation.
• When you call the System.out.println()
method.
• For example, the system actually executes
several statements in order to display a
message on the console.
Methods
import java.io.*;
class Addition
{
int sum = 0;
public int addTwoInt(int a, int b)
{
// adding two integer value.
sum = a + b;
//returning summation of two values.
return sum;
}
class GFG
{
public static void main (String[] args)
{
// creating an instance of Addition class
Addition add = new Addition();
// calling addTwoInt() method to add two integer using instance created in above step.
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}
}
OUTPUT:
Sum of two integer values :3
Access Specifiers
• In java we have four Access Specifiers and
they are listed below.
1. public
2. private
3. protected
4. default(no specifier)
Real Time Example for Access Specifier
private:
• Private members of class in not accessible
anywhere in program these are only
accessible within the class. Private are also
called class level access modifiers.
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
//Compile Time Error, you can't access private data
obj.show();
//Compile Time Error, you can't access private methods
}
}
public:
Public members of any class are accessible
anywhere in the program in the same class
and outside of class, within the same package
and outside of the package. Public are also
called universal access modifiers.
class Hello
{
public int a=20;
public void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); obj.show();
}
}
• Output
• 20
• Hello Java
protected:
• Protected members of the class are accessible
within the same class and another class of the
same package and also accessible in inherited
class of another package. Protected are also
called derived level access modifiers.
//save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B(); obj.show();
}
}
Output
Hello Java
default:
• Default members of the class are accessible only within the same class and another class of the same package. The default
are also called package level access modifiers.
//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java package pack2; import pack1.*; c
lass B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show();
//Compile Time Error, can't access outside the package
}
}
Java static variable
• f you declare any variable as static, it is known
static variable.
• The static variable can be used to refer the
common property of all objects (that is not
unique for each object) e.g. company name of
employees,college name of students etc.
• The static variable gets memory only once in class
area at the time of class loading.
• Advantage of static variable
• It makes your program memory efficient (i.e it
saves memory).
Understanding problem without static
variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.All
student have its unique rollno and name so instance data member
is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.
Example of static variable
/Program of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Static variable
Java Comments
There are 3 types of comments in java.
Single Line Comment
Multi Line Comment
Documentation Comment
• Java Single Line Comment
• The single line comment is used to comment only one line.
• Syntax:
• //This is single line comment
• Example
• public class CommentExample1 {
• public static void main(String[] args) {
• int i=10;//Here, i is a variable
• System.out.println(i);
• }
• }
Java Multi Line Comment
The multi line comment is used to comment multiple lines of code.
/*
This
is
multi line
comment
*/
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
10
Java Documentation Comment
The documentation comment is used to create
documentation
Syntax:
/**
This
is
documentation
comment
*/
Data Types in Java
• Data types classify the different values to be stored in the variable. In java,
there are two types of data types:
• Primitive Data Types
• Non-primitive Data Types
• byte (1 byte)
• short (2 bytes)
• int (4 bytes)
• long (8 bytes)
• float (4 bytes)
• double (8 bytes)
• char (2 bytes)
• boolean (1 byte) (true/false)
Variables in Java
A variable is the name given to a memory location. It is the basic unit of
storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done
on the variable effects that memory location.
In Java, all the variables must be declared before they can be used.
How to declare variables?
We can declare variables in java as follow
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Java Programs

More Related Content

What's hot

Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java ProgramsAravindSankaran
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arraysmanish kumar
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classessidra tauseef
 

What's hot (20)

Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Java programs
Java programsJava programs
Java programs
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java ppt
Java pptJava ppt
Java ppt
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 

Similar to Java Programs

Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Palak Sanghani
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New FeaturesJussi Pohjolainen
 
Java practical
Java practicalJava practical
Java practicalwilliam otto
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab FileKandarp Tiwari
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptxKishanMishra44
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptxKarthik Rohan
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2Aram Mohammed
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 

Similar to Java Programs (20)

Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Unit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docxUnit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docx
 
Java practical
Java practicalJava practical
Java practical
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Java practical
Java practicalJava practical
Java practical
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Core java
Core javaCore java
Core java
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 
C#2
C#2C#2
C#2
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 

Recently uploaded

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 

Recently uploaded (20)

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 

Java Programs

  • 2. Display message on computer screen. class First { public static void main(String args[]) { System.out.println("Let's do something using Java technology."); } }
  • 4. Print integers class Integers { public static void main(String[] arguments) { int c; //declaring a variable /* Using for loop to repeat instruction execution */ for (c = 1; c <= 10; c++) { System.out.println(c); } } }
  • 6. If else control instructions: class Condition { public static void main(String[] args) { boolean learning = true; if (learning) { System.out.println("Java programmer"); } Else { System.out.println("What are you doing here?"); } } }
  • 8. Command line arguments: class Arguments { public static void main(String args[]) { for (String t: args) { System.out.println(t); } } }
  • 10. Java if else program import java.util.Scanner; class IfElse { public static void main(String args[]) { int marksObtained, passingMarks; passingMarks = 40; Scanner input = new Scanner(System.in); System.out.println("Input marks scored by you"); marksObtained = input.nextInt(); if (marksObtained >= passingMarks) { System.out.println("You passed the exam."); } else { System.out.println("Unfortunately, you failed to pass the exam."); } } }
  • 12. Nested If Else statements import java.util.Scanner; class NestedIfElse { public static void main(String args[]) { int marksObtained, passingMarks; char grade; passingMarks = 40; Scanner input = new Scanner(System.in); System.out.println("Input marks scored by you"); marksObtained = input.nextInt(); if (marksObtained >= passingMarks) { if (marksObtained > 90) grade = 'A'; else if (marksObtained > 75) grade = 'B';
  • 13. else if (marksObtained > 60) grade = 'C'; else grade = 'D'; System.out.println("You passed the exam and your grade is " + grade); } else { grade = 'F'; System.out.println("You failed and your grade is " + grade); } } }
  • 14.
  • 15. Infinite for loop for ( ; ; ) { System.out.println("Java programming"); }
  • 16. Simple for loop example in Java class ForLoop { public static void main(String args[]) { int c; for (c = 1; c <= 10; c++) { System.out.println(c); } } }
  • 17.
  • 18. Java while loop example import java.util.Scanner; class WhileLoop { public static void main(String args []) { int n; Scanner input = new Scanner(System.in); System.out.println("Input an integer"); while ((n = input.nextInt()) != 0) { System.out.println("You entered " + n); System.out.println("Input an integer"); } System.out.println("Out of loop"); } }
  • 19.
  • 20. Java program to print multiplication table import java.util.Scanner; class MultiplicationTable { public static void main(String args[]) { int n, c; System.out.println("Enter an integer to print it's multiplication table"); Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println("Multiplication table of " + n + " is : "); for (c = 1; c <= 10; c++) System.out.println(n + "*" + c + " = " + (n*c)); } }
  • 21.
  • 22. • A constructor in Java is a method which is used used to initialize objects. • Constructor method of a class has the same name as that of the class, • Constructor can't be called explicitly Constructor
  • 23. class Programming { Programming() { System.out.println("Constructor method called."); } public static void main(String[] args) { Programming object = new Programming(); } }
  • 24.
  • 25. Creating class and object public class Puppy { public Puppy(String name) { System.out.println("Passed Name is :" + name ); } public static void main(String args[]) { myPuppy = new Puppy( "tommy" ); } }
  • 26. Types of java constructors • There are two types of constructors in java: • 1.Default constructor (no-arg constructor) • 2. Parameterized constructor
  • 27. Java Default Constructor A constructor is called "Default Constructor" when it doesn't have any parameter. Example of default constructor class Bike1 { Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike1 b=new Bike1(); } } OUTPUT Bike is created
  • 28. Example of default constructor that displays the default values class Student3{ int id; String name; void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } } OUTPUT 0 null 0 null
  • 29. parameterized constructor • Parameterized constructor is used to provide different values to the distinct objects. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } }
  • 31. Java - Methods • A Java method is a collection of statements that are grouped together to perform an operation. • When you call the System.out.println() method. • For example, the system actually executes several statements in order to display a message on the console.
  • 33. import java.io.*; class Addition { int sum = 0; public int addTwoInt(int a, int b) { // adding two integer value. sum = a + b; //returning summation of two values. return sum; } class GFG { public static void main (String[] args) { // creating an instance of Addition class Addition add = new Addition(); // calling addTwoInt() method to add two integer using instance created in above step. int s = add.addTwoInt(1,2); System.out.println("Sum of two integer values :"+ s); } } OUTPUT: Sum of two integer values :3
  • 34. Access Specifiers • In java we have four Access Specifiers and they are listed below. 1. public 2. private 3. protected 4. default(no specifier)
  • 35. Real Time Example for Access Specifier
  • 36. private: • Private members of class in not accessible anywhere in program these are only accessible within the class. Private are also called class level access modifiers.
  • 37. class Hello { private int a=20; private void show() { System.out.println("Hello java"); } } public class Demo { public static void main(String args[]) { Hello obj=new Hello(); System.out.println(obj.a); //Compile Time Error, you can't access private data obj.show(); //Compile Time Error, you can't access private methods } }
  • 38. public: Public members of any class are accessible anywhere in the program in the same class and outside of class, within the same package and outside of the package. Public are also called universal access modifiers.
  • 39. class Hello { public int a=20; public void show() { System.out.println("Hello java"); } } public class Demo { public static void main(String args[]) { Hello obj=new Hello(); System.out.println(obj.a); obj.show(); } }
  • 41. protected: • Protected members of the class are accessible within the same class and another class of the same package and also accessible in inherited class of another package. Protected are also called derived level access modifiers.
  • 42. //save A.java package pack1; public class A { protected void show() { System.out.println("Hello Java"); } } //save B.java package pack2; import pack1.*; class B extends A { public static void main(String args[]) { B obj = new B(); obj.show(); } } Output Hello Java
  • 43. default: • Default members of the class are accessible only within the same class and another class of the same package. The default are also called package level access modifiers. //save by A.java package pack; class A { void show() { System.out.println("Hello Java"); } } //save by B.java package pack2; import pack1.*; c lass B { public static void main(String args[]) { A obj = new A(); //Compile Time Error, can't access outside the package obj.show(); //Compile Time Error, can't access outside the package } }
  • 44. Java static variable • f you declare any variable as static, it is known static variable. • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. • The static variable gets memory only once in class area at the time of class loading. • Advantage of static variable • It makes your program memory efficient (i.e it saves memory).
  • 45. Understanding problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
  • 46. Example of static variable /Program of static variable class Student8{ int rollno; String name; static String college ="ITS"; Student8(int r,String n){ rollno = r; name = n; } void display (){System.out.println(rollno+" "+name+" "+college);} public static void main(String args[]){ Student8 s1 = new Student8(111,"Karan"); Student8 s2 = new Student8(222,"Aryan"); s1.display(); s2.display(); } } Output:111 Karan ITS 222 Aryan ITS
  • 48. Java Comments There are 3 types of comments in java. Single Line Comment Multi Line Comment Documentation Comment • Java Single Line Comment • The single line comment is used to comment only one line. • Syntax: • //This is single line comment • Example • public class CommentExample1 { • public static void main(String[] args) { • int i=10;//Here, i is a variable • System.out.println(i); • } • }
  • 49. Java Multi Line Comment The multi line comment is used to comment multiple lines of code. /* This is multi line comment */ Example: public class CommentExample2 { public static void main(String[] args) { /* Let's declare and print variable in java. */ int i=10; System.out.println(i); } } Output: 10
  • 50. Java Documentation Comment The documentation comment is used to create documentation Syntax: /** This is documentation comment */
  • 51. Data Types in Java • Data types classify the different values to be stored in the variable. In java, there are two types of data types: • Primitive Data Types • Non-primitive Data Types • byte (1 byte) • short (2 bytes) • int (4 bytes) • long (8 bytes) • float (4 bytes) • double (8 bytes) • char (2 bytes) • boolean (1 byte) (true/false)
  • 52. Variables in Java A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In Java, all the variables must be declared before they can be used. How to declare variables? We can declare variables in java as follow datatype: Type of data that can be stored in this variable. variable_name: Name given to the variable. value: It is the initial value stored in the variable.